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/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus1022/Nexus1022RebuildRepositoryMavenMetadataTaskTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus1022/Nexus1022RebuildRepositoryMavenMetadataTaskTest.java
index c21218dba..00b5ca02e 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus1022/Nexus1022RebuildRepositoryMavenMetadataTaskTest.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus1022/Nexus1022RebuildRepositoryMavenMetadataTaskTest.java
@@ -1,67 +1,71 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.integrationtests.nexus1022;
import java.io.File;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest;
import org.sonatype.nexus.rest.model.ScheduledServiceListResource;
import org.sonatype.nexus.rest.model.ScheduledServicePropertyResource;
import org.sonatype.nexus.tasks.descriptors.RebuildMavenMetadataTaskDescriptor;
import org.sonatype.nexus.test.utils.TaskScheduleUtil;
public class Nexus1022RebuildRepositoryMavenMetadataTaskTest
extends AbstractNexusIntegrationTest
{
@Test
public void rebuildMavenMetadata()
throws Exception
{
+ if(true) {
+ printKnownErrorButDoNotFail( getClass(), "rebuildMavenMetadata" );
+ return;
+ }
String releaseRepoPath = "runtime/work/storage/nexus-test-harness-repo/";
ScheduledServicePropertyResource repo = new ScheduledServicePropertyResource();
repo.setId( "repositoryOrGroupId" );
repo.setValue( "repo_" + REPO_TEST_HARNESS_REPO );
ScheduledServiceListResource task = TaskScheduleUtil.runTask("RebuildMavenMetadata-Nexus1022", RebuildMavenMetadataTaskDescriptor.ID, 300, repo );
Assert.assertNotNull( "The ScheduledServicePropertyResource task didn't run", task );
File artifactDirMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/artifact/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", artifactDirMd.exists() );
File groupPluginMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/plugins/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", groupPluginMd.exists() );
}
@BeforeClass
public static void cleanWorkFolder() throws Exception {
cleanWorkDir();
}
}
| true | true | public void rebuildMavenMetadata()
throws Exception
{
String releaseRepoPath = "runtime/work/storage/nexus-test-harness-repo/";
ScheduledServicePropertyResource repo = new ScheduledServicePropertyResource();
repo.setId( "repositoryOrGroupId" );
repo.setValue( "repo_" + REPO_TEST_HARNESS_REPO );
ScheduledServiceListResource task = TaskScheduleUtil.runTask("RebuildMavenMetadata-Nexus1022", RebuildMavenMetadataTaskDescriptor.ID, 300, repo );
Assert.assertNotNull( "The ScheduledServicePropertyResource task didn't run", task );
File artifactDirMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/artifact/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", artifactDirMd.exists() );
File groupPluginMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/plugins/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", groupPluginMd.exists() );
}
| public void rebuildMavenMetadata()
throws Exception
{
if(true) {
printKnownErrorButDoNotFail( getClass(), "rebuildMavenMetadata" );
return;
}
String releaseRepoPath = "runtime/work/storage/nexus-test-harness-repo/";
ScheduledServicePropertyResource repo = new ScheduledServicePropertyResource();
repo.setId( "repositoryOrGroupId" );
repo.setValue( "repo_" + REPO_TEST_HARNESS_REPO );
ScheduledServiceListResource task = TaskScheduleUtil.runTask("RebuildMavenMetadata-Nexus1022", RebuildMavenMetadataTaskDescriptor.ID, 300, repo );
Assert.assertNotNull( "The ScheduledServicePropertyResource task didn't run", task );
File artifactDirMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/artifact/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", artifactDirMd.exists() );
File groupPluginMd = new File( nexusBaseDir, releaseRepoPath + "nexus1022/foo/bar/plugins/maven-metadata.xml" );
Assert.assertTrue( "Maven metadata file should be generated after rebuild", groupPluginMd.exists() );
}
|
diff --git a/src/anchovy/io/Parser.java b/src/anchovy/io/Parser.java
index a3a8b94..759aa8a 100644
--- a/src/anchovy/io/Parser.java
+++ b/src/anchovy/io/Parser.java
@@ -1,232 +1,237 @@
package anchovy.io;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import anchovy.GameEngine;
import anchovy.InfoPacket;
import anchovy.Pair;
import anchovy.Components.*;
import anchovy.Pair.Label;
/**
* This class is responsible for parsing text commands supplied by the user and then executing a fitting gameEngine method
* or interacting with a certain component
* Valid commands are: save; save as; show saves; load; valveName open/close
* pumpName RPM/rpm number;
* Control Rods name set/SET number;
* componentName repair
*
*/
public class Parser {
private GameEngine engine;
public Parser(GameEngine Engine)
{
engine = Engine;
}
/**
* Using the two input string determines what command should be executed by the gameEngine or
* one of the components
* @command command Command that will applied to a component
* @param componentName part of the input supplied by the user
* @return returns a message to the user that gets written into the output of the console
*/
public String parseCommand(String componentName, String command)
{
String result = new String();
//Check for for engine commands first
if (componentName.contains("save as")) {
return engine.saveGameState(engine.getAllComponentInfo(), command);
} else if (componentName.equals("save")) {
return engine.save(engine.getAllComponentInfo());
} else if (componentName.contains("load"))
{
try {
engine.readfile(command);
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return "Loaded game Successfully";
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("show saves")) {
return engine.findAvailableSaves();
} else if (componentName.equals("new game")){
try {
engine.readfile("newgame");
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return getGameIntroString(command);
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("exit") | componentName.equals("quit")){
System.exit(0);
}
//then check for components
try {
InfoPacket i = new InfoPacket();
Component component = null;
//Used for components that also need a numerical parameter (pumps and control rods for now)
- if (componentName.contains("Pump") || componentName.contains("rods"))
+ if (componentName.contains("Pump"))
{
String alterName = componentName.substring(0, componentName.lastIndexOf(' '));
component = engine.getPowerPlantComponent(alterName);
if (componentName.contains("RPM") || componentName.contains("rpm"))
{
i.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(command)));
- } else if(componentName.contains("set") || componentName.contains("SET"))
+ }
+ } else if(componentName.contains("rods")){
+ String alterName = componentName.substring(0, componentName.lastIndexOf(' '));
+ alterName = alterName.substring(0,alterName.lastIndexOf(" rods"));
+ component = engine.getPowerPlantComponent(alterName);
+ if(componentName.contains("set") || componentName.contains("SET"))
{
i.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(command)));
}
- }
+ }
else
{
component = engine.getPowerPlantComponent(componentName);
if (component.getName().contains("Valve"))
{
// i.namedValues.add(new Pair<String>(Pair.Label.cNme,
// component.getName()));
if (command.equals("open")) {
i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true));
} else if (command.equals("close"))
{
i.namedValues
.add(new Pair<Boolean>(Pair.Label.psit, false));
}
}
else if (command.equals("repair"))
{
engine.repair(component);
}
}
try {
component.takeInfo(i);
} catch (Exception e) {
return e.getMessage();
}
}
catch(Exception e)
{
result = "Component " + componentName + " does not exist";
}
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return result;
}
/**
* Checks for bad input and splits the string in two tokens, then calls parseCommand.
* @param in an input string (usually coming from the UI)
* @return a message for the user
* @throws FileNotFoundException
*/
public String parse(String text)
{
if(text.length() != 0)
{
String lowerCase= text;
if(lowerCase.equals("save") || lowerCase.equals("exit") || lowerCase.equals("quit"))
{
return parseCommand(lowerCase,lowerCase);
}
//String lowerCase = text.toLowerCase(); //Convert string to lower case to avoid case mismatches
if(lowerCase.contains(" "))
{
if(lowerCase.equals("show saves") || lowerCase.equals("save as") || lowerCase.equals("new game"))
return parseCommand(lowerCase, lowerCase);
String s= lowerCase.substring(0, lowerCase.lastIndexOf(' '));
String i= lowerCase.substring(lowerCase.lastIndexOf(' ') + 1, lowerCase.length());
return parseCommand(s,i);
}
else return "Invalid command";
}
else return "";
}
/**
* Method containing the background story of the game hardcoded into it. Brings the story and the user together.
* @param userName The name of the user.
* @return The story with the users name in it.
*/
public String getGameIntroString(String userName){
return "Fire Blanket " +
"On the 8th April 2013, students at the University of York prepared to demonstrate their second year software projects. " +
"A challenging task, several teams had prepared video game simulations of nuclear power plants for their professor's approval. " +
"Some projects were simple stand-alone affairs powered only by the department's computers. Others utilised the internet to provide " +
"automatic updates. One such system would change the world forever. \n" +
"Precisely one week from the initial deployment of the SEPR solutions, disaster shook the world. " +
"Propagating from one server to the next using obscure net technologies, an unidentified program began initiating the update protocols of the world's major nuclear power plants. " +
"Inexplicably replacing SCADA systems with the student's simulations, the world's power plants began melting down in quick succession. \n\n"+
"The ensuing blanket of fire engulfed the world, reducing civilisation to smouldering ash. \n\n"+
"But the human race proved more resilient than could have been hoped, and pockets of life survived. " +
"One such region, spared of destruction by the recent decommission of its own power plant was none other than the city that spawned its downfall. " +
"York had survived, and with it, it's university. \n\n"+
"In the weeks that followed, urgent discussion took place across what was left of the city. " +
"Unified by an impromptu council of community leaders and prominent academics, the course was set for humanity's fate. " +
"The survivors would require food, shelter, infrastructure and means of self-protection, and for this they would require electricity. \n\n"+
"Enlisting the might of the nearby garrison of Northern Command, " +
"the council lead its citizens on a journey to re-commission its fatefully dormant nuclear facility. \n\n"+
"Months passed, and the decision to mobilise Northern Command proved to be a crucial one. " +
"The first signs of mutation arose in the form of rodents emerging from the irradiated ground. Whilst of little danger to humans, " +
"these rodents would herald the coming of a much greater threat to humanity. \n\n"+
"With dwindling supplies, and rumours of larger mutating creatures converging towards the sounds of construction, " +
"the military remnants began a fevered fortification of the power plant. Enmeshed within electric fences and weapons systems, " +
"humanity's final revival would likely be carried out against the shadow of constant siege. " +
"And to some, lingering memories of the destructive potential of nuclear power outweighed the protection that it afforded... \n\n"+
"Six months have passed since the blanket of fire descended and the newly established outpost of Town has been born. " +
"The nuclear facility for which the town was created has been successfully commissioned by a team of surviving engineers lead by Professor Richard Paige, " +
"and in which you were involved. " +
"Following the untimely digestion of a senior operator by a stray mutated goose, " +
"you have been assigned a more prominent role in the functioning of the plant. " +
"Your presence in the control room has been requested by the Professor to explain your new responsibilities... \n\n"+
"\n\n"+
"*knocks*\n\n"+
"Richard: Come in! Hey, I recognise you from SEPR. Your name is...?\n\n"+
userName +"\n" +
"Richard: " + userName + ". That's right; I thought it was something like that. " +
"So I've heard that you've been promoted to replace our previous senior operator. " +
"Terrible thing that happened to him, I can't help wonder how a mutated goose made it past our defences. " +
"Well never mind, the job's yours now anyway, congratulations.\n\n"+
userName +": So what are my new responsibilities?\n\n"+
"Richard: Well, you have to manage the power plant's operation." +
" All of the more experienced engineers have been asked to help design additional infrastructure for the town, " +
"so you're the most qualified person left to make decisions about the facility's operation. " +
"That said you'll have a team of people who will implement the changes you request in the command terminal and someone else to distribute the power that you generate to the city. \n\n"+
"Richard: As you know, Town's population and industry is growing at quite a substantial rate so you're going to have your work cut out keeping up with demand. " +
"Additionally, the military will require prioritised use of the power to ensure that the city's defences remain operable.\n\n"+
userName + ": I see.\n\n"+
"Richard: The Lieutenant here will explain Town's structure and defensive capabilities in more detail.\n\n"+
"Lieutenant: Yes. The power generated by this facility is directed into three different zones. " +
"The first, and from a survival perspective the least important, is that of the city itself. Should you be unable to generate enough power, " +
"we'll cut off civilian homes and factories first. Next is the electric fence around the perimeter of the city, " +
"this is our first line of defence against the mutants. As more mutants gather, the fence will require more energy to repel them." +
" If the fence falls, then the city will be invariably overrun. Finally, and our highest priority is this facility's own defence systems. " +
"Over the last half year, we've built and supplied a fortified garrison around the power plant and this will be our final line of defence. If power goes out here, then we'll lose our Helicopters, SUVs, Weapons Systems, Emergency Power Grid and ultimately our lives.\n\n"+
"*Gulp*\n\n"+
userName + ": No pressure then...\n\n"+
"Richard: As I said, distribution of power will managed for you, but it's worthwhile considering the potential consequences of not outputting enough power from the system. " +
"Of course, if you try to generate too much power, the plant could overheat and we'll end up just as evaporated as every other region in the country.\n\n"+
userName + ": ...\n\n"+
"Richard: So, the power plant is in your hands! We don't have time to train you, but you can refer to your instruction manual if you forget the terminal's commands. " +
"Try not to blow everything up!\n\n"+
"*Richard and the Lieutenant leave the control room leaving you stood alone. " +
"Walking up to the facility's command system, you hope to redeem your past nuclear failings, " +
"and swear never to copy strange code from the internet again*\n";
}
}
| false | true | public String parseCommand(String componentName, String command)
{
String result = new String();
//Check for for engine commands first
if (componentName.contains("save as")) {
return engine.saveGameState(engine.getAllComponentInfo(), command);
} else if (componentName.equals("save")) {
return engine.save(engine.getAllComponentInfo());
} else if (componentName.contains("load"))
{
try {
engine.readfile(command);
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return "Loaded game Successfully";
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("show saves")) {
return engine.findAvailableSaves();
} else if (componentName.equals("new game")){
try {
engine.readfile("newgame");
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return getGameIntroString(command);
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("exit") | componentName.equals("quit")){
System.exit(0);
}
//then check for components
try {
InfoPacket i = new InfoPacket();
Component component = null;
//Used for components that also need a numerical parameter (pumps and control rods for now)
if (componentName.contains("Pump") || componentName.contains("rods"))
{
String alterName = componentName.substring(0, componentName.lastIndexOf(' '));
component = engine.getPowerPlantComponent(alterName);
if (componentName.contains("RPM") || componentName.contains("rpm"))
{
i.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(command)));
} else if(componentName.contains("set") || componentName.contains("SET"))
{
i.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(command)));
}
}
else
{
component = engine.getPowerPlantComponent(componentName);
if (component.getName().contains("Valve"))
{
// i.namedValues.add(new Pair<String>(Pair.Label.cNme,
// component.getName()));
if (command.equals("open")) {
i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true));
} else if (command.equals("close"))
{
i.namedValues
.add(new Pair<Boolean>(Pair.Label.psit, false));
}
}
else if (command.equals("repair"))
{
engine.repair(component);
}
}
try {
component.takeInfo(i);
} catch (Exception e) {
return e.getMessage();
}
}
catch(Exception e)
{
result = "Component " + componentName + " does not exist";
}
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return result;
}
| public String parseCommand(String componentName, String command)
{
String result = new String();
//Check for for engine commands first
if (componentName.contains("save as")) {
return engine.saveGameState(engine.getAllComponentInfo(), command);
} else if (componentName.equals("save")) {
return engine.save(engine.getAllComponentInfo());
} else if (componentName.contains("load"))
{
try {
engine.readfile(command);
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return "Loaded game Successfully";
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("show saves")) {
return engine.findAvailableSaves();
} else if (componentName.equals("new game")){
try {
engine.readfile("newgame");
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return getGameIntroString(command);
} catch (FileNotFoundException e) {
return "File not found.";
}
} else if (componentName.equals("exit") | componentName.equals("quit")){
System.exit(0);
}
//then check for components
try {
InfoPacket i = new InfoPacket();
Component component = null;
//Used for components that also need a numerical parameter (pumps and control rods for now)
if (componentName.contains("Pump"))
{
String alterName = componentName.substring(0, componentName.lastIndexOf(' '));
component = engine.getPowerPlantComponent(alterName);
if (componentName.contains("RPM") || componentName.contains("rpm"))
{
i.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(command)));
}
} else if(componentName.contains("rods")){
String alterName = componentName.substring(0, componentName.lastIndexOf(' '));
alterName = alterName.substring(0,alterName.lastIndexOf(" rods"));
component = engine.getPowerPlantComponent(alterName);
if(componentName.contains("set") || componentName.contains("SET"))
{
i.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(command)));
}
}
else
{
component = engine.getPowerPlantComponent(componentName);
if (component.getName().contains("Valve"))
{
// i.namedValues.add(new Pair<String>(Pair.Label.cNme,
// component.getName()));
if (command.equals("open")) {
i.namedValues.add(new Pair<Boolean>(Pair.Label.psit, true));
} else if (command.equals("close"))
{
i.namedValues
.add(new Pair<Boolean>(Pair.Label.psit, false));
}
}
else if (command.equals("repair"))
{
engine.repair(component);
}
}
try {
component.takeInfo(i);
} catch (Exception e) {
return e.getMessage();
}
}
catch(Exception e)
{
result = "Component " + componentName + " does not exist";
}
engine.updateInterfaceComponents(engine.getAllComponentInfo());
return result;
}
|
diff --git a/jason/asSemantics/TransitionSystem.java b/jason/asSemantics/TransitionSystem.java
index 7a714db..97305b6 100644
--- a/jason/asSemantics/TransitionSystem.java
+++ b/jason/asSemantics/TransitionSystem.java
@@ -1,889 +1,899 @@
// ----------------------------------------------------------------------------
// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
//
// 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
//
// To contact the authors:
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
//----------------------------------------------------------------------------
package jason.asSemantics;
import jason.JasonException;
import jason.RevisionFailedException;
import jason.architecture.AgArch;
import jason.asSyntax.Atom;
import jason.asSyntax.PlanBody;
import jason.asSyntax.DefaultTerm;
import jason.asSyntax.InternalActionLiteral;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Literal;
import jason.asSyntax.LogicalFormula;
import jason.asSyntax.Plan;
import jason.asSyntax.PlanLibrary;
import jason.asSyntax.Structure;
import jason.asSyntax.Term;
import jason.asSyntax.Trigger;
import jason.asSyntax.Trigger.TEOperator;
import jason.asSyntax.Trigger.TEType;
import jason.bb.BeliefBase;
import jason.runtime.Settings;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TransitionSystem {
public enum State { StartRC, SelEv, RelPl, ApplPl, SelAppl, FindOp, AddIM, ProcAct, SelInt, ExecInt, ClrInt }
private Logger logger = null;
private Agent ag = null;
private AgArch agArch = null;
private Circumstance C = null;
private Settings setts = null;
// first step of the SOS
private State step = State.StartRC;
// number of reasoning cycles since last belief revision
private int nrcslbr;
// both configuration and configuration' point to this
// object, this is just to make it look more like the SOS
private TransitionSystem confP;
// both configuration and configuration' point to this
// object, this is just to make it look more like the SOS
private TransitionSystem conf;
public TransitionSystem(Agent a, Circumstance c, Settings s, AgArch ar) {
ag = a;
C = c;
agArch = ar;
if (s == null)
setts = new Settings();
else
setts = s;
if (C == null)
C = new Circumstance();
// we need to initialise this "aliases"
conf = confP = this;
nrcslbr = setts.nrcbp(); // to do BR to start with
setLogger(agArch);
if (setts != null)
logger.setLevel(setts.logLevel());
}
public void setLogger(AgArch arch) {
if (arch != null)
logger = Logger.getLogger(TransitionSystem.class.getName() + "." + arch.getAgName());
else
logger = Logger.getLogger(TransitionSystem.class.getName());
}
/** ******************************************************************* */
/* SEMANTIC RULES */
/** ******************************************************************* */
private void applySemanticRule() throws JasonException {
// check the current step in the reasoning cycle
// only the main parts of the interpretation appear here
// the individual semantic rules appear below
switch (step) {
case StartRC: applyProcMsg(); break;
case SelEv: applySelEv(); break;
case RelPl: applyRelPl(); break;
case ApplPl: applyApplPl(); break;
case SelAppl: applySelAppl(); break;
case FindOp: applyFindOp(); break;
case AddIM: applyAddIM(); break;
case ProcAct: applyProcAct(); break;
case SelInt: applySelInt(); break;
case ExecInt: applyExecInt(); break;
case ClrInt: confP.step = State.StartRC;
applyClrInt(conf.C.SI);
break;
}
}
// the semantic rules are referred to in comments in the functions below
private void applyProcMsg() throws JasonException {
confP.step = State.SelEv;
if (!conf.C.MB.isEmpty()) {
Message m = conf.ag.selectMessage(conf.C.MB);
if (m == null) return;
// get the content, it can be any term (literal, list, number, ...; see ask)
Term content = null;
if (m.getPropCont() instanceof Term) {
content = (Term)m.getPropCont();
} else {
content = DefaultTerm.parse(m.getPropCont().toString());
}
// check if an intention was suspended waiting this message
Intention intention = null;
if (m.getInReplyTo() != null) {
intention = getC().getPendingIntentions().remove(m.getInReplyTo());
}
// is it a pending intention?
if (intention != null) {
// unify the message answer with the .send fourth argument.
// the send that put the intention in Pending state was
// something like
// .send(ag1,askOne, value, X)
// if the answer was tell 3, unifies X=3
// if the answer was untell 3, unifies X=false
Structure send = (Structure)intention.peek().removeCurrentStep();
if (m.isUnTell()) {
if (send.getTerm(1).toString().equals("askOne")) {
content = Literal.LFalse;
} else { // the .send is askAll
content = new ListTermImpl(); // the answer is an empty list
}
}
if (intention.peek().getUnif().unifies(send.getTerm(3), content)) {
getC().addIntention(intention);
} else {
conf.C.SI = intention;
generateGoalDeletion();
}
// the message is not an ask answer
} else if (conf.ag.socAcc(m)) {
// generate an event
Literal received = new Literal("kqml_received");
received.addTerm(new Atom(m.getSender()));
received.addTerm(new Atom(m.getIlForce()));
received.addTerm(content);
received.addTerm(new Atom(m.getMsgId()));
updateEvents(new Event(new Trigger(TEOperator.add, TEType.achieve, received), Intention.EmptyInt));
}
}
}
private void applySelEv() throws JasonException {
// Rule for atomic, if there is an atomic intention, do not select event
if (C.hasAtomicIntention()) {
confP.step = State.SelInt;
return;
}
if (conf.C.hasEvent()) {
// Rule for atomic, events from atomic intention has priority
confP.C.SE = C.removeAtomicEvent();
if (confP.C.SE != null) {
confP.step = State.RelPl;
return;
}
// Rule SelEv1
confP.C.SE = conf.ag.selectEvent(confP.C.getEvents());
if (confP.C.SE != null) {
if (ag.hasCustomSelectOption() || setts.verbose() == 2) // verbose == 2 means debug mode
confP.step = State.RelPl;
else
confP.step = State.FindOp;
return;
}
}
// Rule SelEv2
// directly to ProcAct if no event to handle
confP.step = State.ProcAct;
}
private void applyRelPl() throws JasonException {
// get all relevant plans for the selected event
confP.C.RP = relevantPlans(conf.C.SE.trigger);
// Rule Rel1
if (confP.C.RP != null || setts.retrieve())
// retrieve is mainly for Coo-AgentSpeak
confP.step = State.ApplPl;
else
applyRelApplPlRule2("relevant");
}
private void applyApplPl() throws JasonException {
confP.C.AP = applicablePlans(confP.C.RP);
// Rule Appl1
if (confP.C.AP != null || setts.retrieve())
// retrieve is mainly for Coo-AgentSpeak
confP.step = State.SelAppl;
else
applyRelApplPlRule2("applicable");
}
private void applyRelApplPlRule2(String m) throws JasonException {
confP.step = State.ProcAct; // default next step
if (conf.C.SE.trigger.isGoal()) {
// can't carry on, no relevant/applicable plan.
logger.warning("Found a goal for which there is no "+m+" plan:" + conf.C.SE);
generateGoalDeletionFromEvent();
} else {
if (conf.C.SE.isInternal()) {
// e.g. belief addition as internal event, just go ahead
// but note that the event was relevant, yet it is possible
// the programmer just wanted to add the belief and it was
// relevant by chance, so just carry on instead of dropping the
// intention
confP.C.SI = conf.C.SE.intention;
updateIntention();
} else if (setts.requeue()) {
// if external, then needs to check settings
confP.C.addEvent(conf.C.SE);
} else {
// current event is external and irrelevant,
// discard that event and select another one
confP.step = State.SelEv;
}
}
}
private void applySelAppl() throws JasonException {
// Rule SelAppl
confP.C.SO = conf.ag.selectOption(confP.C.AP);
if (confP.C.SO != null) {
confP.step = State.AddIM;
if (logger.isLoggable(Level.FINE)) logger.fine("Selected option "+confP.C.SO+" for event "+confP.C.SE);
} else {
logger.fine("** selectOption returned null!");
generateGoalDeletionFromEvent();
// can't carry on, no applicable plan.
confP.step = State.ProcAct;
}
}
/**
* This step is new in Jason 1.1 and replaces the steps RelPl->ApplPl->SelAppl when the user
* does not customise selectOption. This version does not create the RP and AP lists and thus
* optimise the reasoning cycle. It searches for the first option and automatically selects it.
*
* @since 1.1
*/
private void applyFindOp() throws JasonException {
confP.step = State.AddIM; // default next step
// get all relevant plans for the selected event
//Trigger te = (Trigger) conf.C.SE.trigger.clone();
List<Plan> candidateRPs = conf.ag.pl.getCandidatePlans(conf.C.SE.trigger);
if (candidateRPs != null) {
for (Plan pl : candidateRPs) {
Unifier relUn = pl.isRelevant(conf.C.SE.trigger);
if (relUn != null) { // is relevant
LogicalFormula context = pl.getContext();
if (context == null) { // context is true
confP.C.SO = new Option(pl, relUn);
return;
} else {
Iterator<Unifier> r = context.logicalConsequence(ag, relUn);
if (r != null && r.hasNext()) {
confP.C.SO = new Option(pl, r.next());
return;
}
}
}
}
}
// problem: no plan
applyRelApplPlRule2("relevant/applicable");
}
private void applyAddIM() throws JasonException {
// create a new intended means
IntendedMeans im = new IntendedMeans(conf.C.SO, conf.C.SE.getTrigger());
// Rule ExtEv
if (conf.C.SE.intention == Intention.EmptyInt) {
Intention intention = new Intention();
intention.push(im);
confP.C.addIntention(intention);
} else {
// Rule IntEv
confP.C.SE.intention.push(im);
confP.C.addIntention(confP.C.SE.intention);
}
confP.step = State.ProcAct;
}
private void applyProcAct() throws JasonException {
confP.step = State.SelInt; // default next step
if (conf.C.hasFeedbackAction()) {
ActionExec a = conf.ag.selectAction(conf.C.getFeedbackActions());
if (a != null) {
confP.C.SI = a.getIntention();
// remove the intention from PA (PA has all pending action, including those in FA;
// but, if the intention is not in PA, it means that the intention was dropped
// and should not return to I)
if (C.getPendingActions().remove(a.getIntention().getId()) != null) {
if (a.getResult()) {
// add the intention back in I
updateIntention();
applyClrInt(confP.C.SI);
} else {
generateGoalDeletion();
}
} else {
applyProcAct(); // get next action
}
}
}
}
private void applySelInt() throws JasonException {
confP.step = State.ExecInt; // default next step
// Rule for Atomic Intentions
confP.C.SI = C.removeAtomicIntention();
if (confP.C.SI != null) {
return;
}
// Rule SelInt1
if (conf.C.hasIntention()) {
confP.C.SI = conf.ag.selectIntention(conf.C.getIntentions());
if (confP.C.SI != null) { // the selectIntention function retuned null
return;
}
}
confP.step = State.StartRC;
}
@SuppressWarnings("unchecked")
private void applyExecInt() throws JasonException {
confP.step = State.ClrInt; // default next step
if (conf.C.SI.isFinished()) {
return;
}
// get next formula in the body of the intended means
// on the top of the selected intention
IntendedMeans im = conf.C.SI.peek();
if (im.isFinished()) {
// for empty plans! may need unif, etc
updateIntention();
return;
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
h.apply(u);
Literal body = null;
Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
switch (h.getBodyType()) {
// Rule Action
case action:
confP.C.A = new ActionExec(body, conf.C.SI);
break;
case internalAction:
boolean ok = false;
try {
InternalAction ia = ((InternalActionLiteral)body).getIA(ag);
Object oresult = ia.execute(this, u, body.getTermsArray());
if (oresult != null) {
ok = oresult instanceof Boolean && (Boolean)oresult;
if (!ok && oresult instanceof Iterator) { // ia result is an Iterator
Iterator<Unifier> iu = (Iterator<Unifier>)oresult;
if (iu.hasNext()) {
// change the unifier of the current IM to the first returned by the IA
im.unif = iu.next();
ok = true;
}
}
}
if (ok && !ia.suspendIntention())
updateIntention();
} catch (Exception e) {
logger.log(Level.SEVERE, body.getErrorMsg()+": "+ e.getMessage(), e);
ok = false;
}
if (!ok)
generateGoalDeletion();
break;
case constraint:
Iterator<Unifier> iu = ((LogicalFormula)bTerm).logicalConsequence(ag, u);
if (iu.hasNext()) {
im.unif = iu.next();
updateIntention();
} else {
if (logger.isLoggable(Level.FINE)) logger.fine("Constraint "+h+" was not satisfied ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
break;
// Rule Achieve
case achieve:
// free variables in an event cannot conflict with those in the plan
body = (Literal)body.clone();
+ if (!body.hasSource()) {
+ // do not add source(self) in case the
+ // programmer set some annotation
+ body.addAnnot(BeliefBase.TSelf);
+ }
body.makeVarsAnnon();
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
break;
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
body = (Literal)body.clone();
+ if (!body.hasSource()) {
+ // do not add source(self) in case the
+ // programmer set some annotation
+ body.addAnnot(BeliefBase.TSelf);
+ }
body.makeVarsAnnon();
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
break;
// Rule Test
case test:
LogicalFormula f = (LogicalFormula)bTerm;
if (conf.ag.believes(f, u)) {
updateIntention();
} else {
boolean fail = true;
if (f instanceof Literal) { // generate event when using literal in the test (no events for log. expr. like ?(a & b))
body = (Literal)f.clone();
if (body.isLiteral()) { // in case body is a var with content that is not a literal (note the VarTerm pass in the instanceof Literal)
body.makeVarsAnnon();
Trigger te = new Trigger(TEOperator.add, TEType.test, body);
if (ag.getPL().hasCandidatePlan(te)) {
Event evt = new Event(te, conf.C.SI);
if (logger.isLoggable(Level.FINE)) logger.fine("Test Goal '" + h + "' failed as simple query. Generating internal event for it: "+te);
conf.C.addEvent(evt);
confP.step = State.StartRC;
fail = false;
}
}
}
if (fail) {
if (logger.isLoggable(Level.FINE)) logger.fine("Test '"+h+"' failed ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
}
break;
case delAddBel:
// -+a(1,X) ===> remove a(_,_), add a(1,X)
// change all vars to anon vars to remove it
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
Literal bc = (Literal)body.clone();
bc.makeTermsAnnon();
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
try {
List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
if (result != null) { // really delete something
// generate events
updateEvents(result,Intention.EmptyInt);
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
break;
}
// add the belief, so no break;
// Rule AddBel
case addBel:
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
body.addAnnot(BeliefBase.TSelf);
}
// calculate focus
Intention newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// rename free vars
body.makeVarsAnnon();
// call BRF
try {
List<Literal>[] result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
if (result != null) { // really add something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
case delBel:
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// call BRF
try {
List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
if (result != null) { // really change something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
}
}
public void applyClrInt(Intention i) throws JasonException {
// Rule ClrInt
if (i == null)
return;
if (i.isFinished()) {
// intention finished, remove it
confP.C.removeIntention(i);
//conf.C.SI = null;
return;
}
IntendedMeans im = i.peek();
if (!im.isFinished()) {
// nothing to do
return;
}
// remove the finished IM from the top of the intention
IntendedMeans topIM = i.pop();
if (logger.isLoggable(Level.FINE)) logger.fine("Returning from IM "+topIM.getPlan().getLabel()+", te="+topIM.getPlan().getTrigger());
// if finished a failure handling IM ...
if (im.getTrigger().isGoal() && !im.getTrigger().isAddition() && i.size() > 0) {
// needs to get rid of the IM until a goal that
// has failure handling. E.g,
// -!b
// +!c
// +!d
// +!b
// +!s: !b; !z
// should became
// +!s: !z
im = i.pop(); // +!c above, old
while (!im.unif.unifies(topIM.getTrigger().getLiteral(), im.getTrigger().getLiteral()) && i.size() > 0) {
im = i.pop();
}
}
if (!i.isFinished()) {
im = i.peek(); // +!s or +?s
if (!im.isFinished()) {
// removes !b or ?s
Term g = im.removeCurrentStep();
// make the TE of finished plan ground and unify that
// with goal in the body
Literal tel = topIM.getPlan().getTrigger().getLiteral();
tel.apply(topIM.unif);
im.unif.unifies(tel, g);
}
}
// the new top may have become
// empty! need to keep checking.
applyClrInt(i);
}
/**********************************************/
/* auxiliary functions for the semantic rules */
/**********************************************/
public List<Option> relevantPlans(Trigger teP) throws JasonException {
Trigger te = (Trigger) teP.clone();
List<Option> rp = null;
List<Plan> candidateRPs = conf.ag.pl.getCandidatePlans(te);
if (candidateRPs != null) {
for (Plan pl : candidateRPs) {
Unifier relUn = pl.isRelevant(te);
if (relUn != null) {
if (rp == null) rp = new LinkedList<Option>();
rp.add(new Option(pl, relUn));
}
}
}
return rp;
}
public List<Option> applicablePlans(List<Option> rp) throws JasonException {
List<Option> ap = null;
if (rp != null) {
//ap = new ApplPlanTimeOut().get(rp);
for (Option opt: rp) {
LogicalFormula context = opt.getPlan().getContext();
if (context == null) { // context is true
if (ap == null) ap = new LinkedList<Option>();
ap.add(opt);
} else {
boolean allUnifs = opt.getPlan().isAllUnifs();
Iterator<Unifier> r = context.logicalConsequence(ag, opt.getUnifier());
if (r != null) {
while (r.hasNext()) {
opt.setUnifier(r.next());
if (ap == null) ap = new LinkedList<Option>();
ap.add(opt);
if (!allUnifs) break; // returns only the first unification
if (r.hasNext()) {
// create a new option for the next loop step
opt = new Option(opt.getPlan(), null);
}
}
}
}
}
}
return ap;
}
public void updateEvents(List<Literal>[] result, Intention focus) {
if (result == null) return;
// create the events
for (Literal ladd: result[0]) {
Trigger te = new Trigger(TEOperator.add, TEType.belief, ladd);
updateEvents(new Event(te, focus));
focus = Intention.EmptyInt;
}
for (Literal lrem: result[1]) {
Trigger te = new Trigger(TEOperator.del, TEType.belief, lrem);
updateEvents(new Event(te, focus));
focus = Intention.EmptyInt;
}
}
// only add External Event if it is relevant in respect to the PlanLibrary
public void updateEvents(Event e) {
// Note: we have to add events even if they are not relevant to
// a) allow the user to override selectOption and then provide an "unknown" plan; or then
// b) create the failure event (it is done by SelRelPlan)
if (e.isInternal() || C.hasListener() || ag.getPL().hasCandidatePlan(e.trigger)) {
C.addEvent(e);
if (logger.isLoggable(Level.FINE)) logger.fine("Added event " + e);
}
}
/** remove the top action and requeue the current intention */
private void updateIntention() {
if (!conf.C.SI.isFinished()) {
IntendedMeans im = conf.C.SI.peek();
im.removeCurrentStep();
confP.C.addIntention(conf.C.SI);
} else {
logger.fine("trying to update a finished intention!");
}
}
/** generate a failure event for the current intention */
private void generateGoalDeletion() throws JasonException {
IntendedMeans im = conf.C.SI.peek();
if (im.isGoalAdd()) {
Event failEvent = findEventForFailure(conf.C.SI, im.getTrigger());
if (failEvent != null) {
confP.C.addEvent(failEvent);
if (logger.isLoggable(Level.FINE)) logger.fine("Generating goal deletion " + failEvent.getTrigger() + " from goal: " + im.getTrigger());
} else {
logger.warning("No fail event was generated for " + im.getTrigger());
}
}
// if "discard" is set, we are deleting the whole intention!
// it is simply not going back to 'I' nor anywhere else!
else if (setts.requeue()) {
// get the external event (or the one that started
// the whole focus of attention) and requeue it
im = conf.C.SI.get(0);
confP.C.addExternalEv(im.getTrigger());
} else {
logger.warning("Could not finish intention: " + conf.C.SI);
}
}
// similar to the one above, but for an Event rather than intention
private void generateGoalDeletionFromEvent() throws JasonException {
Event ev = conf.C.SE;
if (ev == null) {
logger.warning("** It is not possible to generate a goal deletion event because SE is null! " + conf.C);
return;
}
Trigger tevent = ev.trigger;
if (tevent.isAddition() && tevent.isGoal()) {
Event failEvent = findEventForFailure(ev.intention, tevent);
if (failEvent != null) {
logger.warning("Generating goal deletion " + failEvent.getTrigger() + " from event: " + ev.getTrigger());
confP.C.addEvent(failEvent);
} else {
logger.warning("No fail event was generated for " + ev.getTrigger());
}
} else if (ev.isInternal()) {
logger.warning("Could not finish intention:\n" + ev.intention);
}
// if "discard" is set, we are deleting the whole intention!
// it is simply not going back to I nor anywhere else!
else if (setts.requeue()) {
confP.C.addEvent(ev);
logger.warning("Requeing external event: " + ev);
} else
logger.warning("Discarding external event: " + ev);
}
public Event findEventForFailure(Intention i, Trigger tevent) {
Trigger failTrigger = new Trigger(TEOperator.del, tevent.getType(), tevent.getLiteral());
if (i != Intention.EmptyInt) {
ListIterator<IntendedMeans> ii = i.iterator();
while (!getAg().getPL().hasCandidatePlan(failTrigger) && ii.hasPrevious()) {
IntendedMeans im = ii.previous();
tevent = im.getTrigger();
failTrigger = new Trigger(TEOperator.del, tevent.getType(), tevent.getLiteral());
}
}
// if some failure handling plan is found
if (tevent.isGoal() && getAg().getPL().hasCandidatePlan(failTrigger)) {
return new Event(failTrigger, i);
}
return null;
}
public boolean canSleep() {
return !conf.C.hasEvent() && !conf.C.hasIntention() &&
conf.C.MB.isEmpty() && !conf.C.hasFeedbackAction() &&
agArch.canSleep();
}
/**********************************************************************/
/* MAIN LOOP */
/**********************************************************************/
/* infinite loop on one reasoning cycle */
/* plus the other parts of the agent architecture besides */
/* the actual transition system of the AS interpreter */
/**********************************************************************/
public void reasoningCycle() {
try {
C.reset();
if (nrcslbr >= setts.nrcbp()) {
nrcslbr = 0;
ag.buf(agArch.perceive());
agArch.checkMail();
}
nrcslbr++; // counting number of cycles since last belief revision
if (canSleep()) {
if (ag.pl.getIdlePlans() != null) {
logger.fine("generating idle event");
C.addExternalEv(PlanLibrary.TE_IDLE);
} else {
agArch.sleep();
return;
}
}
step = State.StartRC;
do {
if (!agArch.isRunning()) return;
applySemanticRule();
} while (step != State.StartRC);
ActionExec action = C.getAction();
if (action != null) {
C.getPendingActions().put(action.getIntention().getId(), action);
agArch.act(action, C.getFeedbackActions());
}
} catch (Exception e) {
logger.log(Level.SEVERE, "*** ERROR in the transition system. "+conf.C+"\nCreating a new C!", e);
conf.C.create();
}
}
// Auxiliary functions
// (for Internal Actions to be able to access the configuration)
public Agent getAg() {
return ag;
}
public Circumstance getC() {
return C;
}
public State getStep() {
return step;
}
public Settings getSettings() {
return setts;
}
public AgArch getUserAgArch() {
return agArch;
}
public Logger getLogger() {
return logger;
}
}
| false | true | private void applyExecInt() throws JasonException {
confP.step = State.ClrInt; // default next step
if (conf.C.SI.isFinished()) {
return;
}
// get next formula in the body of the intended means
// on the top of the selected intention
IntendedMeans im = conf.C.SI.peek();
if (im.isFinished()) {
// for empty plans! may need unif, etc
updateIntention();
return;
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
h.apply(u);
Literal body = null;
Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
switch (h.getBodyType()) {
// Rule Action
case action:
confP.C.A = new ActionExec(body, conf.C.SI);
break;
case internalAction:
boolean ok = false;
try {
InternalAction ia = ((InternalActionLiteral)body).getIA(ag);
Object oresult = ia.execute(this, u, body.getTermsArray());
if (oresult != null) {
ok = oresult instanceof Boolean && (Boolean)oresult;
if (!ok && oresult instanceof Iterator) { // ia result is an Iterator
Iterator<Unifier> iu = (Iterator<Unifier>)oresult;
if (iu.hasNext()) {
// change the unifier of the current IM to the first returned by the IA
im.unif = iu.next();
ok = true;
}
}
}
if (ok && !ia.suspendIntention())
updateIntention();
} catch (Exception e) {
logger.log(Level.SEVERE, body.getErrorMsg()+": "+ e.getMessage(), e);
ok = false;
}
if (!ok)
generateGoalDeletion();
break;
case constraint:
Iterator<Unifier> iu = ((LogicalFormula)bTerm).logicalConsequence(ag, u);
if (iu.hasNext()) {
im.unif = iu.next();
updateIntention();
} else {
if (logger.isLoggable(Level.FINE)) logger.fine("Constraint "+h+" was not satisfied ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
break;
// Rule Achieve
case achieve:
// free variables in an event cannot conflict with those in the plan
body = (Literal)body.clone();
body.makeVarsAnnon();
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
break;
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
body = (Literal)body.clone();
body.makeVarsAnnon();
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
break;
// Rule Test
case test:
LogicalFormula f = (LogicalFormula)bTerm;
if (conf.ag.believes(f, u)) {
updateIntention();
} else {
boolean fail = true;
if (f instanceof Literal) { // generate event when using literal in the test (no events for log. expr. like ?(a & b))
body = (Literal)f.clone();
if (body.isLiteral()) { // in case body is a var with content that is not a literal (note the VarTerm pass in the instanceof Literal)
body.makeVarsAnnon();
Trigger te = new Trigger(TEOperator.add, TEType.test, body);
if (ag.getPL().hasCandidatePlan(te)) {
Event evt = new Event(te, conf.C.SI);
if (logger.isLoggable(Level.FINE)) logger.fine("Test Goal '" + h + "' failed as simple query. Generating internal event for it: "+te);
conf.C.addEvent(evt);
confP.step = State.StartRC;
fail = false;
}
}
}
if (fail) {
if (logger.isLoggable(Level.FINE)) logger.fine("Test '"+h+"' failed ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
}
break;
case delAddBel:
// -+a(1,X) ===> remove a(_,_), add a(1,X)
// change all vars to anon vars to remove it
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
Literal bc = (Literal)body.clone();
bc.makeTermsAnnon();
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
try {
List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
if (result != null) { // really delete something
// generate events
updateEvents(result,Intention.EmptyInt);
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
break;
}
// add the belief, so no break;
// Rule AddBel
case addBel:
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
body.addAnnot(BeliefBase.TSelf);
}
// calculate focus
Intention newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// rename free vars
body.makeVarsAnnon();
// call BRF
try {
List<Literal>[] result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
if (result != null) { // really add something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
case delBel:
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// call BRF
try {
List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
if (result != null) { // really change something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
}
}
| private void applyExecInt() throws JasonException {
confP.step = State.ClrInt; // default next step
if (conf.C.SI.isFinished()) {
return;
}
// get next formula in the body of the intended means
// on the top of the selected intention
IntendedMeans im = conf.C.SI.peek();
if (im.isFinished()) {
// for empty plans! may need unif, etc
updateIntention();
return;
}
Unifier u = im.unif;
PlanBody h = im.getCurrentStep();
h.apply(u);
Literal body = null;
Term bTerm = h.getBodyTerm();
if (bTerm instanceof Literal)
body = (Literal)bTerm;
switch (h.getBodyType()) {
// Rule Action
case action:
confP.C.A = new ActionExec(body, conf.C.SI);
break;
case internalAction:
boolean ok = false;
try {
InternalAction ia = ((InternalActionLiteral)body).getIA(ag);
Object oresult = ia.execute(this, u, body.getTermsArray());
if (oresult != null) {
ok = oresult instanceof Boolean && (Boolean)oresult;
if (!ok && oresult instanceof Iterator) { // ia result is an Iterator
Iterator<Unifier> iu = (Iterator<Unifier>)oresult;
if (iu.hasNext()) {
// change the unifier of the current IM to the first returned by the IA
im.unif = iu.next();
ok = true;
}
}
}
if (ok && !ia.suspendIntention())
updateIntention();
} catch (Exception e) {
logger.log(Level.SEVERE, body.getErrorMsg()+": "+ e.getMessage(), e);
ok = false;
}
if (!ok)
generateGoalDeletion();
break;
case constraint:
Iterator<Unifier> iu = ((LogicalFormula)bTerm).logicalConsequence(ag, u);
if (iu.hasNext()) {
im.unif = iu.next();
updateIntention();
} else {
if (logger.isLoggable(Level.FINE)) logger.fine("Constraint "+h+" was not satisfied ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
break;
// Rule Achieve
case achieve:
// free variables in an event cannot conflict with those in the plan
body = (Literal)body.clone();
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
body.makeVarsAnnon();
conf.C.addAchvGoal(body, conf.C.SI);
confP.step = State.StartRC;
break;
// Rule Achieve as a New Focus (the !! operator)
case achieveNF:
body = (Literal)body.clone();
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
body.makeVarsAnnon();
conf.C.addAchvGoal(body, Intention.EmptyInt);
updateIntention();
break;
// Rule Test
case test:
LogicalFormula f = (LogicalFormula)bTerm;
if (conf.ag.believes(f, u)) {
updateIntention();
} else {
boolean fail = true;
if (f instanceof Literal) { // generate event when using literal in the test (no events for log. expr. like ?(a & b))
body = (Literal)f.clone();
if (body.isLiteral()) { // in case body is a var with content that is not a literal (note the VarTerm pass in the instanceof Literal)
body.makeVarsAnnon();
Trigger te = new Trigger(TEOperator.add, TEType.test, body);
if (ag.getPL().hasCandidatePlan(te)) {
Event evt = new Event(te, conf.C.SI);
if (logger.isLoggable(Level.FINE)) logger.fine("Test Goal '" + h + "' failed as simple query. Generating internal event for it: "+te);
conf.C.addEvent(evt);
confP.step = State.StartRC;
fail = false;
}
}
}
if (fail) {
if (logger.isLoggable(Level.FINE)) logger.fine("Test '"+h+"' failed ("+h.getErrorMsg()+").");
generateGoalDeletion();
}
}
break;
case delAddBel:
// -+a(1,X) ===> remove a(_,_), add a(1,X)
// change all vars to anon vars to remove it
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
Literal bc = (Literal)body.clone();
bc.makeTermsAnnon();
// to delete, create events as external to avoid that
// remove/add create two events for the same intention
try {
List<Literal>[] result = ag.brf(null, bc, conf.C.SI); // the intention is not the new focus
if (result != null) { // really delete something
// generate events
updateEvents(result,Intention.EmptyInt);
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
break;
}
// add the belief, so no break;
// Rule AddBel
case addBel:
if (!body.hasSource()) {
// do not add source(self) in case the
// programmer set the source
body.addAnnot(BeliefBase.TSelf);
}
// calculate focus
Intention newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// rename free vars
body.makeVarsAnnon();
// call BRF
try {
List<Literal>[] result = ag.brf(body,null,conf.C.SI); // the intention is not the new focus
if (result != null) { // really add something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
case delBel:
if (!body.hasAnnot()) {
// do not add source(self) in case the
// programmer set some annotation
body.addAnnot(BeliefBase.TSelf);
}
newfocus = Intention.EmptyInt;
if (setts.sameFocus())
newfocus = conf.C.SI;
// call BRF
try {
List<Literal>[] result = ag.brf(null,body, conf.C.SI); // the intention is not the new focus
if (result != null) { // really change something
// generate events
updateEvents(result,newfocus);
if (!setts.sameFocus()) {
updateIntention();
}
} else {
updateIntention();
}
} catch (RevisionFailedException re) {
generateGoalDeletion();
}
break;
}
}
|
diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractSurefireIntegrationTestClass.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractSurefireIntegrationTestClass.java
index 612084d8..f25daa68 100644
--- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractSurefireIntegrationTestClass.java
+++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/AbstractSurefireIntegrationTestClass.java
@@ -1,41 +1,41 @@
package org.apache.maven.surefire.its;
import junit.framework.TestCase;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import java.util.ArrayList;
/**
* Base class of all integration test cases. Mainly used to pickup surefire version
* from system property
*
* @author Dan T. Tran
*/
public abstract class AbstractSurefireIntegrationTestClass
extends TestCase
{
private String surefireVersion = System.getProperty( "surefire.version" );
protected ArrayList getInitialGoals()
{
ArrayList goals = new ArrayList();
goals.add( "-Dsurefire.version=" + surefireVersion );
return goals;
}
protected void executeGoal( Verifier verifier, String goal )
throws VerificationException
{
ArrayList goals = this.getInitialGoals();
goals.add( goal );
if ( !verifier.getCliOptions().contains( "-s" ) )
{
verifier.getCliOptions().add( "-s" );
- verifier.getCliOptions().add( System.getProperty( "maven.staged.local.repo" ) );
+ verifier.getCliOptions().add( System.getProperty( "maven.settings.file" ) + ".staged" );
}
verifier.executeGoals( goals );
}
}
| true | true | protected void executeGoal( Verifier verifier, String goal )
throws VerificationException
{
ArrayList goals = this.getInitialGoals();
goals.add( goal );
if ( !verifier.getCliOptions().contains( "-s" ) )
{
verifier.getCliOptions().add( "-s" );
verifier.getCliOptions().add( System.getProperty( "maven.staged.local.repo" ) );
}
verifier.executeGoals( goals );
}
| protected void executeGoal( Verifier verifier, String goal )
throws VerificationException
{
ArrayList goals = this.getInitialGoals();
goals.add( goal );
if ( !verifier.getCliOptions().contains( "-s" ) )
{
verifier.getCliOptions().add( "-s" );
verifier.getCliOptions().add( System.getProperty( "maven.settings.file" ) + ".staged" );
}
verifier.executeGoals( goals );
}
|
diff --git a/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/create/DefectPanel.java b/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/create/DefectPanel.java
index 38b147e5..0370dbd2 100644
--- a/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/create/DefectPanel.java
+++ b/DefectTracker/src/edu/wpi/cs/wpisuitetng/modules/defecttracker/create/DefectPanel.java
@@ -1,130 +1,130 @@
package edu.wpi.cs.wpisuitetng.modules.defecttracker.create;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import edu.wpi.cs.wpisuitetng.modules.core.models.User;
import edu.wpi.cs.wpisuitetng.modules.defecttracker.models.Defect;
/**
* Panel to display the fields of a Defect and allow editing
*
*/
@SuppressWarnings("serial")
public class DefectPanel extends JPanel {
protected Defect model;
protected JTextField txtTitle;
protected JTextArea txtDescription;
protected JTextField txtCreator;
protected JTextField txtAssignee;
protected TagPanel tagPanel;
protected static final int HORIZONTAL_PADDING = 5;
protected static final int VERTICAL_PADDING = 15;
protected static final int LABEL_ALIGNMENT = JLabel.TRAILING;
public DefectPanel() {
this(new Defect());
}
public DefectPanel(Defect defect) {
this.model = defect;
SpringLayout layout = new SpringLayout();
this.setLayout(layout);
addComponents(layout);
// Populate the fields based on the given model
txtTitle.setText(defect.getTitle());
txtDescription.setText(defect.getDescription());
if (defect.getCreator() != null) {
txtCreator.setText(defect.getCreator().getUsername());
}
if (defect.getAssignee() != null) {
txtAssignee.setText(defect.getAssignee().getUsername());
}
}
/**
* Adds the components to the panel and places constraints on them
* for the SpringLayout manager.
* @param layout the layout manager
*/
protected void addComponents(SpringLayout layout) {
txtTitle = new JTextField(50);
txtDescription = new JTextArea();
txtDescription.setLineWrap(true);
txtDescription.setBorder(txtTitle.getBorder());
txtCreator = new JTextField(20);
txtAssignee = new JTextField(20);
tagPanel = new TagPanel(model);
JLabel lblTitle = new JLabel("Title:", LABEL_ALIGNMENT);
JLabel lblDescription = new JLabel("Description:", LABEL_ALIGNMENT);
JLabel lblCreator = new JLabel("Creator:", LABEL_ALIGNMENT);
JLabel lblAssignee = new JLabel("Assignee:", LABEL_ALIGNMENT);
int labelWidth = lblDescription.getPreferredSize().width;
layout.putConstraint(SpringLayout.NORTH, lblTitle, VERTICAL_PADDING, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, lblTitle, 15, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.EAST, lblTitle, labelWidth, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtTitle, 0, SpringLayout.VERTICAL_CENTER, lblTitle);
layout.putConstraint(SpringLayout.WEST, txtTitle, HORIZONTAL_PADDING, SpringLayout.EAST, lblTitle);
layout.putConstraint(SpringLayout.EAST, txtTitle, txtTitle.getPreferredSize().width, SpringLayout.WEST, txtTitle);
layout.putConstraint(SpringLayout.NORTH, txtDescription, VERTICAL_PADDING, SpringLayout.SOUTH, txtTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblDescription, 0, SpringLayout.VERTICAL_CENTER, txtDescription);
layout.putConstraint(SpringLayout.WEST, lblDescription, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblDescription, labelWidth, SpringLayout.WEST, lblDescription);
layout.putConstraint(SpringLayout.WEST, txtDescription, HORIZONTAL_PADDING, SpringLayout.EAST, lblDescription);
layout.putConstraint(SpringLayout.EAST, txtDescription, 0, SpringLayout.EAST, txtTitle);
- layout.putConstraint(SpringLayout.SOUTH, txtDescription, txtDescription.getPreferredSize().height * 4, SpringLayout.NORTH, txtDescription);
+ layout.putConstraint(SpringLayout.SOUTH, txtDescription, txtTitle.getPreferredSize().height * 4, SpringLayout.NORTH, txtDescription);
layout.putConstraint(SpringLayout.NORTH, txtCreator, VERTICAL_PADDING, SpringLayout.SOUTH, txtDescription);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblCreator, 0, SpringLayout.VERTICAL_CENTER, txtCreator);
layout.putConstraint(SpringLayout.WEST, lblCreator, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblCreator, labelWidth, SpringLayout.WEST, lblCreator);
layout.putConstraint(SpringLayout.WEST, txtCreator, HORIZONTAL_PADDING, SpringLayout.EAST, lblCreator);
layout.putConstraint(SpringLayout.NORTH, txtAssignee, VERTICAL_PADDING, SpringLayout.SOUTH, txtCreator);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblAssignee, 0, SpringLayout.VERTICAL_CENTER, txtAssignee);
layout.putConstraint(SpringLayout.WEST, lblAssignee, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblAssignee, labelWidth, SpringLayout.WEST, lblAssignee);
layout.putConstraint(SpringLayout.WEST, txtAssignee, HORIZONTAL_PADDING, SpringLayout.EAST, lblAssignee);
layout.putConstraint(SpringLayout.NORTH, tagPanel, VERTICAL_PADDING * 3, SpringLayout.NORTH, txtAssignee);
layout.putConstraint(SpringLayout.WEST, tagPanel, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, tagPanel, 0, SpringLayout.EAST, txtTitle);
layout.putConstraint(SpringLayout.SOUTH, this, 15, SpringLayout.SOUTH, tagPanel);
add(lblTitle);
add(txtTitle);
add(lblDescription);
add(txtDescription);
add(lblCreator);
add(txtCreator);
add(lblAssignee);
add(txtAssignee);
add(tagPanel);
}
/**
* Returns the model object represented by this view
* TODO: Change return type to the abstract class / interface
* TODO: Ensure that if id field is set to -1, that a new defect is created on the server
* TODO: Do some basic input verification
* TODO: Deal with tags and other assignee
* @return the model represented by this view
*/
public Defect getModel() {
return new Defect(-1, txtTitle.getText(), txtDescription.getText(), new User("", txtCreator.getText(), -1));
}
}
| true | true | protected void addComponents(SpringLayout layout) {
txtTitle = new JTextField(50);
txtDescription = new JTextArea();
txtDescription.setLineWrap(true);
txtDescription.setBorder(txtTitle.getBorder());
txtCreator = new JTextField(20);
txtAssignee = new JTextField(20);
tagPanel = new TagPanel(model);
JLabel lblTitle = new JLabel("Title:", LABEL_ALIGNMENT);
JLabel lblDescription = new JLabel("Description:", LABEL_ALIGNMENT);
JLabel lblCreator = new JLabel("Creator:", LABEL_ALIGNMENT);
JLabel lblAssignee = new JLabel("Assignee:", LABEL_ALIGNMENT);
int labelWidth = lblDescription.getPreferredSize().width;
layout.putConstraint(SpringLayout.NORTH, lblTitle, VERTICAL_PADDING, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, lblTitle, 15, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.EAST, lblTitle, labelWidth, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtTitle, 0, SpringLayout.VERTICAL_CENTER, lblTitle);
layout.putConstraint(SpringLayout.WEST, txtTitle, HORIZONTAL_PADDING, SpringLayout.EAST, lblTitle);
layout.putConstraint(SpringLayout.EAST, txtTitle, txtTitle.getPreferredSize().width, SpringLayout.WEST, txtTitle);
layout.putConstraint(SpringLayout.NORTH, txtDescription, VERTICAL_PADDING, SpringLayout.SOUTH, txtTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblDescription, 0, SpringLayout.VERTICAL_CENTER, txtDescription);
layout.putConstraint(SpringLayout.WEST, lblDescription, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblDescription, labelWidth, SpringLayout.WEST, lblDescription);
layout.putConstraint(SpringLayout.WEST, txtDescription, HORIZONTAL_PADDING, SpringLayout.EAST, lblDescription);
layout.putConstraint(SpringLayout.EAST, txtDescription, 0, SpringLayout.EAST, txtTitle);
layout.putConstraint(SpringLayout.SOUTH, txtDescription, txtDescription.getPreferredSize().height * 4, SpringLayout.NORTH, txtDescription);
layout.putConstraint(SpringLayout.NORTH, txtCreator, VERTICAL_PADDING, SpringLayout.SOUTH, txtDescription);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblCreator, 0, SpringLayout.VERTICAL_CENTER, txtCreator);
layout.putConstraint(SpringLayout.WEST, lblCreator, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblCreator, labelWidth, SpringLayout.WEST, lblCreator);
layout.putConstraint(SpringLayout.WEST, txtCreator, HORIZONTAL_PADDING, SpringLayout.EAST, lblCreator);
layout.putConstraint(SpringLayout.NORTH, txtAssignee, VERTICAL_PADDING, SpringLayout.SOUTH, txtCreator);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblAssignee, 0, SpringLayout.VERTICAL_CENTER, txtAssignee);
layout.putConstraint(SpringLayout.WEST, lblAssignee, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblAssignee, labelWidth, SpringLayout.WEST, lblAssignee);
layout.putConstraint(SpringLayout.WEST, txtAssignee, HORIZONTAL_PADDING, SpringLayout.EAST, lblAssignee);
layout.putConstraint(SpringLayout.NORTH, tagPanel, VERTICAL_PADDING * 3, SpringLayout.NORTH, txtAssignee);
layout.putConstraint(SpringLayout.WEST, tagPanel, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, tagPanel, 0, SpringLayout.EAST, txtTitle);
layout.putConstraint(SpringLayout.SOUTH, this, 15, SpringLayout.SOUTH, tagPanel);
add(lblTitle);
add(txtTitle);
add(lblDescription);
add(txtDescription);
add(lblCreator);
add(txtCreator);
add(lblAssignee);
add(txtAssignee);
add(tagPanel);
}
| protected void addComponents(SpringLayout layout) {
txtTitle = new JTextField(50);
txtDescription = new JTextArea();
txtDescription.setLineWrap(true);
txtDescription.setBorder(txtTitle.getBorder());
txtCreator = new JTextField(20);
txtAssignee = new JTextField(20);
tagPanel = new TagPanel(model);
JLabel lblTitle = new JLabel("Title:", LABEL_ALIGNMENT);
JLabel lblDescription = new JLabel("Description:", LABEL_ALIGNMENT);
JLabel lblCreator = new JLabel("Creator:", LABEL_ALIGNMENT);
JLabel lblAssignee = new JLabel("Assignee:", LABEL_ALIGNMENT);
int labelWidth = lblDescription.getPreferredSize().width;
layout.putConstraint(SpringLayout.NORTH, lblTitle, VERTICAL_PADDING, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, lblTitle, 15, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.EAST, lblTitle, labelWidth, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, txtTitle, 0, SpringLayout.VERTICAL_CENTER, lblTitle);
layout.putConstraint(SpringLayout.WEST, txtTitle, HORIZONTAL_PADDING, SpringLayout.EAST, lblTitle);
layout.putConstraint(SpringLayout.EAST, txtTitle, txtTitle.getPreferredSize().width, SpringLayout.WEST, txtTitle);
layout.putConstraint(SpringLayout.NORTH, txtDescription, VERTICAL_PADDING, SpringLayout.SOUTH, txtTitle);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblDescription, 0, SpringLayout.VERTICAL_CENTER, txtDescription);
layout.putConstraint(SpringLayout.WEST, lblDescription, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblDescription, labelWidth, SpringLayout.WEST, lblDescription);
layout.putConstraint(SpringLayout.WEST, txtDescription, HORIZONTAL_PADDING, SpringLayout.EAST, lblDescription);
layout.putConstraint(SpringLayout.EAST, txtDescription, 0, SpringLayout.EAST, txtTitle);
layout.putConstraint(SpringLayout.SOUTH, txtDescription, txtTitle.getPreferredSize().height * 4, SpringLayout.NORTH, txtDescription);
layout.putConstraint(SpringLayout.NORTH, txtCreator, VERTICAL_PADDING, SpringLayout.SOUTH, txtDescription);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblCreator, 0, SpringLayout.VERTICAL_CENTER, txtCreator);
layout.putConstraint(SpringLayout.WEST, lblCreator, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblCreator, labelWidth, SpringLayout.WEST, lblCreator);
layout.putConstraint(SpringLayout.WEST, txtCreator, HORIZONTAL_PADDING, SpringLayout.EAST, lblCreator);
layout.putConstraint(SpringLayout.NORTH, txtAssignee, VERTICAL_PADDING, SpringLayout.SOUTH, txtCreator);
layout.putConstraint(SpringLayout.VERTICAL_CENTER, lblAssignee, 0, SpringLayout.VERTICAL_CENTER, txtAssignee);
layout.putConstraint(SpringLayout.WEST, lblAssignee, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, lblAssignee, labelWidth, SpringLayout.WEST, lblAssignee);
layout.putConstraint(SpringLayout.WEST, txtAssignee, HORIZONTAL_PADDING, SpringLayout.EAST, lblAssignee);
layout.putConstraint(SpringLayout.NORTH, tagPanel, VERTICAL_PADDING * 3, SpringLayout.NORTH, txtAssignee);
layout.putConstraint(SpringLayout.WEST, tagPanel, 0, SpringLayout.WEST, lblTitle);
layout.putConstraint(SpringLayout.EAST, tagPanel, 0, SpringLayout.EAST, txtTitle);
layout.putConstraint(SpringLayout.SOUTH, this, 15, SpringLayout.SOUTH, tagPanel);
add(lblTitle);
add(txtTitle);
add(lblDescription);
add(txtDescription);
add(lblCreator);
add(txtCreator);
add(lblAssignee);
add(txtAssignee);
add(tagPanel);
}
|
diff --git a/src/com/eteks/sweethome3d/swing/HomeFurniturePanel.java b/src/com/eteks/sweethome3d/swing/HomeFurniturePanel.java
index 5fbfaefa..08d6e91f 100644
--- a/src/com/eteks/sweethome3d/swing/HomeFurniturePanel.java
+++ b/src/com/eteks/sweethome3d/swing/HomeFurniturePanel.java
@@ -1,540 +1,540 @@
/*
* HomeFurniturePanel.java 16 mai 07
*
* Copyright (c) 2007 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.swing;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.eteks.sweethome3d.model.UserPreferences;
import com.eteks.sweethome3d.tools.OperatingSystem;
import com.eteks.sweethome3d.viewcontroller.DialogView;
import com.eteks.sweethome3d.viewcontroller.HomeFurnitureController;
import com.eteks.sweethome3d.viewcontroller.View;
/**
* Home furniture editing panel.
* @author Emmanuel Puybaret
*/
public class HomeFurniturePanel extends JPanel implements DialogView {
private final HomeFurnitureController controller;
private JLabel nameLabel;
private JTextField nameTextField;
private NullableCheckBox nameVisibleCheckBox;
private JLabel xLabel;
private JSpinner xSpinner;
private JLabel yLabel;
private JSpinner ySpinner;
private JLabel elevationLabel;
private JSpinner elevationSpinner;
private JLabel angleLabel;
private JSpinner angleSpinner;
private JLabel widthLabel;
private JSpinner widthSpinner;
private JLabel depthLabel;
private JSpinner depthSpinner;
private JLabel heightLabel;
private JSpinner heightSpinner;
private JLabel colorLabel;
private ColorButton colorButton;
private NullableCheckBox visibleCheckBox;
private NullableCheckBox mirroredModelCheckBox;
private String dialogTitle;
/**
* Creates a panel that displays home furniture data according to the units
* set in <code>preferences</code>.
* @param preferences user preferences
* @param controller the controller of this panel
*/
public HomeFurniturePanel(UserPreferences preferences,
HomeFurnitureController controller) {
super(new GridBagLayout());
this.controller = controller;
createComponents(preferences, controller);
setMnemonics(preferences);
layoutComponents();
}
/**
* Creates and initializes components and spinners model.
*/
private void createComponents(UserPreferences preferences,
final HomeFurnitureController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create name label and its text field bound to NAME controller property
this.nameLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences, HomeFurniturePanel.class, "nameLabel.text"));
this.nameTextField = new JTextField(controller.getName(), 10);
if (!OperatingSystem.isMacOSX()) {
SwingTools.addAutoSelectionOnFocusGain(this.nameTextField);
}
final PropertyChangeListener nameChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameTextField.setText(controller.getName());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
this.nameTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
String name = nameTextField.getText();
if (name == null || name.trim().length() == 0) {
controller.setName(null);
} else {
controller.setName(name);
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
}
public void insertUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
public void removeUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
});
// Create name visible check box bound to NAME_VISIBLE controller property
this.nameVisibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "nameVisibleCheckBox.text"));
this.nameVisibleCheckBox.setNullable(controller.getNameVisible() == null);
this.nameVisibleCheckBox.setValue(controller.getNameVisible());
final PropertyChangeListener nameVisibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameVisibleCheckBox.setNullable(ev.getNewValue() == null);
nameVisibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
this.nameVisibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
controller.setNameVisible(nameVisibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
}
});
// Create X label and its spinner bound to X controller property
this.xLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.xSpinner = new NullableSpinner(xSpinnerModel);
xSpinnerModel.setNullable(controller.getX() == null);
xSpinnerModel.setLength(controller.getX());
final PropertyChangeListener xChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xSpinnerModel.setNullable(ev.getNewValue() == null);
xSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
xSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
controller.setX(xSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
}
});
// Create Y label and its spinner bound to Y controller property
this.yLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel ySpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.ySpinner = new NullableSpinner(ySpinnerModel);
ySpinnerModel.setNullable(controller.getY() == null);
ySpinnerModel.setLength(controller.getY());
final PropertyChangeListener yChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
ySpinnerModel.setNullable(ev.getNewValue() == null);
ySpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
ySpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
controller.setY(ySpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
}
});
// Create elevation label and its spinner bound to ELEVATION controller property
this.elevationLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "elevationLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel elevationSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0f, 1000f);
this.elevationSpinner = new NullableSpinner(elevationSpinnerModel);
elevationSpinnerModel.setNullable(controller.getElevation() == null);
elevationSpinnerModel.setLength(controller.getElevation());
final PropertyChangeListener elevationChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
elevationSpinnerModel.setNullable(ev.getNewValue() == null);
elevationSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
elevationSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
controller.setElevation(elevationSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
}
});
// Create angle label and its spinner bound to ANGLE_IN_DEGREES controller property
this.angleLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "angleLabel.text"));
final NullableSpinner.NullableSpinnerNumberModel angleSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(0, 0, 360, 1);
this.angleSpinner = new NullableSpinner(angleSpinnerModel);
Integer angle = controller.getAngleInDegrees();
angleSpinnerModel.setNullable(angle == null);
angleSpinnerModel.setValue(angle);
final PropertyChangeListener angleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
Float newAngle = (Float)ev.getNewValue();
angleSpinnerModel.setNullable(newAngle == null);
angleSpinnerModel.setValue(newAngle);
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
angleSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
Number value = (Number)angleSpinnerModel.getValue();
if (value == null) {
controller.setAngleInDegrees(null);
} else {
controller.setAngleInDegrees(value.intValue());
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
}
});
// Create width label and its spinner bound to WIDTH controller property
this.widthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "widthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel widthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
- this.widthSpinner = new AutoCommitSpinner(widthSpinnerModel);
+ this.widthSpinner = new NullableSpinner(widthSpinnerModel);
widthSpinnerModel.setNullable(controller.getWidth() == null);
widthSpinnerModel.setLength(controller.getWidth());
final PropertyChangeListener widthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
widthSpinnerModel.setNullable(ev.getNewValue() == null);
widthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
widthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
controller.setWidth(widthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
}
});
// Create depth label and its spinner bound to DEPTH controller property
this.depthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "depthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel depthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.depthSpinner = new NullableSpinner(depthSpinnerModel);
depthSpinnerModel.setNullable(controller.getDepth() == null);
depthSpinnerModel.setLength(controller.getDepth());
final PropertyChangeListener depthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
depthSpinnerModel.setNullable(ev.getNewValue() == null);
depthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
depthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
controller.setDepth(depthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
}
});
// Create height label and its spinner bound to HEIGHT controller property
this.heightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "heightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel heightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.heightSpinner = new NullableSpinner(heightSpinnerModel);
heightSpinnerModel.setNullable(controller.getHeight() == null);
heightSpinnerModel.setLength(controller.getHeight());
final PropertyChangeListener heightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
heightSpinnerModel.setNullable(ev.getNewValue() == null);
heightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
heightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
controller.setHeight(heightSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
}
});
// Create color label and its button bound to COLOR controller property
this.colorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "colorLabel.text"));
this.colorButton = new ColorButton();
this.colorButton.setColorDialogTitle(preferences.getLocalizedString(
HomeFurniturePanel.class, "colorDialog.title"));
this.colorButton.setColor(controller.getColor());
this.colorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setColor(colorButton.getColor());
}
});
controller.addPropertyChangeListener(HomeFurnitureController.Property.COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
colorButton.setColor(controller.getColor());
}
});
// Create visible check box bound to VISIBLE controller property
this.visibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "visibleCheckBox.text"));
this.visibleCheckBox.setNullable(controller.getVisible() == null);
this.visibleCheckBox.setValue(controller.getVisible());
final PropertyChangeListener visibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
visibleCheckBox.setNullable(ev.getNewValue() == null);
visibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
this.visibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
controller.setVisible(visibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
}
});
// Create mirror check box bound to MODEL_MIRRORED controller property
this.mirroredModelCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "mirroredModelCheckBox.text"));
this.mirroredModelCheckBox.setNullable(controller.getModelMirrored() == null);
this.mirroredModelCheckBox.setValue(controller.getModelMirrored());
final PropertyChangeListener mirroredModelChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
mirroredModelCheckBox.setNullable(ev.getNewValue() == null);
mirroredModelCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
this.mirroredModelCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
controller.setModelMirrored(mirroredModelCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
}
});
updateSizeComponents(controller);
// Add a listener that enables / disables size fields depending on furniture resizable
controller.addPropertyChangeListener(HomeFurnitureController.Property.RESIZABLE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateSizeComponents(controller);
}
});
this.dialogTitle = preferences.getLocalizedString(HomeFurniturePanel.class, "homeFurniture.title");
}
/**
* Updates size components depending on the fact that furniture is resizable or not.
*/
private void updateSizeComponents(final HomeFurnitureController controller) {
boolean editableSize = controller.isResizable();
this.widthLabel.setEnabled(editableSize);
this.widthSpinner.setEnabled(editableSize);
this.depthLabel.setEnabled(editableSize);
this.depthSpinner.setEnabled(editableSize);
this.heightLabel.setEnabled(editableSize);
this.heightSpinner.setEnabled(editableSize);
this.mirroredModelCheckBox.setEnabled(editableSize);
}
/**
* Sets components mnemonics and label / component associations.
*/
private void setMnemonics(UserPreferences preferences) {
if (!OperatingSystem.isMacOSX()) {
this.nameLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "nameLabel.mnemonic")).getKeyCode());
this.nameLabel.setLabelFor(this.nameTextField);
this.nameVisibleCheckBox.setMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "nameVisibleCheckBox.mnemonic")).getKeyCode());
this.xLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "xLabel.mnemonic")).getKeyCode());
this.xLabel.setLabelFor(this.xSpinner);
this.yLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "yLabel.mnemonic")).getKeyCode());
this.yLabel.setLabelFor(this.ySpinner);
this.elevationLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "elevationLabel.mnemonic")).getKeyCode());
this.elevationLabel.setLabelFor(this.elevationSpinner);
this.angleLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "angleLabel.mnemonic")).getKeyCode());
this.angleLabel.setLabelFor(this.angleSpinner);
this.widthLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "widthLabel.mnemonic")).getKeyCode());
this.widthLabel.setLabelFor(this.widthSpinner);
this.depthLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "depthLabel.mnemonic")).getKeyCode());
this.depthLabel.setLabelFor(this.depthSpinner);
this.heightLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "heightLabel.mnemonic")).getKeyCode());
this.heightLabel.setLabelFor(this.heightSpinner);
this.colorLabel.setDisplayedMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "colorLabel.mnemonic")).getKeyCode());
this.colorLabel.setLabelFor(this.colorButton);
this.visibleCheckBox.setMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "visibleCheckBox.mnemonic")).getKeyCode());
this.mirroredModelCheckBox.setMnemonic(KeyStroke.getKeyStroke(preferences.getLocalizedString(
HomeFurniturePanel.class, "mirroredModelCheckBox.mnemonic")).getKeyCode());
}
}
/**
* Layouts panel components in panel with their labels.
*/
private void layoutComponents() {
int labelAlignment = OperatingSystem.isMacOSX()
? GridBagConstraints.LINE_END
: GridBagConstraints.LINE_START;
// First row
Insets labelInsets = new Insets(0, 0, 10, 5);
add(this.nameLabel, new GridBagConstraints(
0, 0, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
Insets componentInsets = new Insets(0, 0, 10, 15);
add(this.nameTextField, new GridBagConstraints(
1, 0, 2, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 5), 0, 0));
Insets rightComponentInsets = new Insets(0, 0, 10, 0);
add(this.nameVisibleCheckBox, new GridBagConstraints(
3, 0, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, labelInsets, 0, 0));
// Second row
add(this.xLabel, new GridBagConstraints(
0, 1, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.xSpinner, new GridBagConstraints(
1, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, componentInsets, -15, 0));
add(this.widthLabel, new GridBagConstraints(
2, 1, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.widthSpinner, new GridBagConstraints(
3, 1, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, rightComponentInsets, -10, 0));
// Third row
add(this.yLabel, new GridBagConstraints(
0, 2, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.ySpinner, new GridBagConstraints(
1, 2, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, componentInsets, -15, 0));
add(this.depthLabel, new GridBagConstraints(
2, 2, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.depthSpinner, new GridBagConstraints(
3, 2, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, rightComponentInsets, -10, 0));
// Forth row
add(this.elevationLabel, new GridBagConstraints(
0, 3, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.elevationSpinner, new GridBagConstraints(
1, 3, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, componentInsets, -10, 0));
add(this.heightLabel, new GridBagConstraints(
2, 3, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.heightSpinner, new GridBagConstraints(
3, 3, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, rightComponentInsets, -10, 0));
// Fifth row
add(this.angleLabel, new GridBagConstraints(
0, 4, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, labelInsets, 0, 0));
add(this.angleSpinner, new GridBagConstraints(
1, 4, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL, componentInsets, -15, 0));
add(this.mirroredModelCheckBox, new GridBagConstraints(
3, 4, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, rightComponentInsets, 0, 0));
// Last row
Insets lastRowInsets = new Insets(0, 0, 0, 5);
add(this.colorLabel, new GridBagConstraints(
0, 5, 1, 1, 0, 0, labelAlignment,
GridBagConstraints.NONE, lastRowInsets, 0, 0));
add(this.colorButton, new GridBagConstraints(
1, 5, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 10), 0, 0));
add(this.visibleCheckBox, new GridBagConstraints(
3, 5, 1, 1, 0, 0, GridBagConstraints.LINE_START,
GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
}
/**
* Displays this panel in a modal dialog box.
*/
public void displayView(View parentView) {
if (SwingTools.showConfirmDialog((JComponent)parentView,
this, this.dialogTitle, this.nameTextField) == JOptionPane.OK_OPTION) {
this.controller.modifyFurniture();
}
}
}
| true | true | private void createComponents(UserPreferences preferences,
final HomeFurnitureController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create name label and its text field bound to NAME controller property
this.nameLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences, HomeFurniturePanel.class, "nameLabel.text"));
this.nameTextField = new JTextField(controller.getName(), 10);
if (!OperatingSystem.isMacOSX()) {
SwingTools.addAutoSelectionOnFocusGain(this.nameTextField);
}
final PropertyChangeListener nameChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameTextField.setText(controller.getName());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
this.nameTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
String name = nameTextField.getText();
if (name == null || name.trim().length() == 0) {
controller.setName(null);
} else {
controller.setName(name);
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
}
public void insertUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
public void removeUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
});
// Create name visible check box bound to NAME_VISIBLE controller property
this.nameVisibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "nameVisibleCheckBox.text"));
this.nameVisibleCheckBox.setNullable(controller.getNameVisible() == null);
this.nameVisibleCheckBox.setValue(controller.getNameVisible());
final PropertyChangeListener nameVisibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameVisibleCheckBox.setNullable(ev.getNewValue() == null);
nameVisibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
this.nameVisibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
controller.setNameVisible(nameVisibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
}
});
// Create X label and its spinner bound to X controller property
this.xLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.xSpinner = new NullableSpinner(xSpinnerModel);
xSpinnerModel.setNullable(controller.getX() == null);
xSpinnerModel.setLength(controller.getX());
final PropertyChangeListener xChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xSpinnerModel.setNullable(ev.getNewValue() == null);
xSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
xSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
controller.setX(xSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
}
});
// Create Y label and its spinner bound to Y controller property
this.yLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel ySpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.ySpinner = new NullableSpinner(ySpinnerModel);
ySpinnerModel.setNullable(controller.getY() == null);
ySpinnerModel.setLength(controller.getY());
final PropertyChangeListener yChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
ySpinnerModel.setNullable(ev.getNewValue() == null);
ySpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
ySpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
controller.setY(ySpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
}
});
// Create elevation label and its spinner bound to ELEVATION controller property
this.elevationLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "elevationLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel elevationSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0f, 1000f);
this.elevationSpinner = new NullableSpinner(elevationSpinnerModel);
elevationSpinnerModel.setNullable(controller.getElevation() == null);
elevationSpinnerModel.setLength(controller.getElevation());
final PropertyChangeListener elevationChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
elevationSpinnerModel.setNullable(ev.getNewValue() == null);
elevationSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
elevationSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
controller.setElevation(elevationSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
}
});
// Create angle label and its spinner bound to ANGLE_IN_DEGREES controller property
this.angleLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "angleLabel.text"));
final NullableSpinner.NullableSpinnerNumberModel angleSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(0, 0, 360, 1);
this.angleSpinner = new NullableSpinner(angleSpinnerModel);
Integer angle = controller.getAngleInDegrees();
angleSpinnerModel.setNullable(angle == null);
angleSpinnerModel.setValue(angle);
final PropertyChangeListener angleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
Float newAngle = (Float)ev.getNewValue();
angleSpinnerModel.setNullable(newAngle == null);
angleSpinnerModel.setValue(newAngle);
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
angleSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
Number value = (Number)angleSpinnerModel.getValue();
if (value == null) {
controller.setAngleInDegrees(null);
} else {
controller.setAngleInDegrees(value.intValue());
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
}
});
// Create width label and its spinner bound to WIDTH controller property
this.widthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "widthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel widthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.widthSpinner = new AutoCommitSpinner(widthSpinnerModel);
widthSpinnerModel.setNullable(controller.getWidth() == null);
widthSpinnerModel.setLength(controller.getWidth());
final PropertyChangeListener widthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
widthSpinnerModel.setNullable(ev.getNewValue() == null);
widthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
widthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
controller.setWidth(widthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
}
});
// Create depth label and its spinner bound to DEPTH controller property
this.depthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "depthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel depthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.depthSpinner = new NullableSpinner(depthSpinnerModel);
depthSpinnerModel.setNullable(controller.getDepth() == null);
depthSpinnerModel.setLength(controller.getDepth());
final PropertyChangeListener depthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
depthSpinnerModel.setNullable(ev.getNewValue() == null);
depthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
depthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
controller.setDepth(depthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
}
});
// Create height label and its spinner bound to HEIGHT controller property
this.heightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "heightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel heightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.heightSpinner = new NullableSpinner(heightSpinnerModel);
heightSpinnerModel.setNullable(controller.getHeight() == null);
heightSpinnerModel.setLength(controller.getHeight());
final PropertyChangeListener heightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
heightSpinnerModel.setNullable(ev.getNewValue() == null);
heightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
heightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
controller.setHeight(heightSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
}
});
// Create color label and its button bound to COLOR controller property
this.colorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "colorLabel.text"));
this.colorButton = new ColorButton();
this.colorButton.setColorDialogTitle(preferences.getLocalizedString(
HomeFurniturePanel.class, "colorDialog.title"));
this.colorButton.setColor(controller.getColor());
this.colorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setColor(colorButton.getColor());
}
});
controller.addPropertyChangeListener(HomeFurnitureController.Property.COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
colorButton.setColor(controller.getColor());
}
});
// Create visible check box bound to VISIBLE controller property
this.visibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "visibleCheckBox.text"));
this.visibleCheckBox.setNullable(controller.getVisible() == null);
this.visibleCheckBox.setValue(controller.getVisible());
final PropertyChangeListener visibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
visibleCheckBox.setNullable(ev.getNewValue() == null);
visibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
this.visibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
controller.setVisible(visibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
}
});
// Create mirror check box bound to MODEL_MIRRORED controller property
this.mirroredModelCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "mirroredModelCheckBox.text"));
this.mirroredModelCheckBox.setNullable(controller.getModelMirrored() == null);
this.mirroredModelCheckBox.setValue(controller.getModelMirrored());
final PropertyChangeListener mirroredModelChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
mirroredModelCheckBox.setNullable(ev.getNewValue() == null);
mirroredModelCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
this.mirroredModelCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
controller.setModelMirrored(mirroredModelCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
}
});
updateSizeComponents(controller);
// Add a listener that enables / disables size fields depending on furniture resizable
controller.addPropertyChangeListener(HomeFurnitureController.Property.RESIZABLE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateSizeComponents(controller);
}
});
this.dialogTitle = preferences.getLocalizedString(HomeFurniturePanel.class, "homeFurniture.title");
}
| private void createComponents(UserPreferences preferences,
final HomeFurnitureController controller) {
// Get unit name matching current unit
String unitName = preferences.getLengthUnit().getName();
// Create name label and its text field bound to NAME controller property
this.nameLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences, HomeFurniturePanel.class, "nameLabel.text"));
this.nameTextField = new JTextField(controller.getName(), 10);
if (!OperatingSystem.isMacOSX()) {
SwingTools.addAutoSelectionOnFocusGain(this.nameTextField);
}
final PropertyChangeListener nameChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameTextField.setText(controller.getName());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
this.nameTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
String name = nameTextField.getText();
if (name == null || name.trim().length() == 0) {
controller.setName(null);
} else {
controller.setName(name);
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME, nameChangeListener);
}
public void insertUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
public void removeUpdate(DocumentEvent ev) {
changedUpdate(ev);
}
});
// Create name visible check box bound to NAME_VISIBLE controller property
this.nameVisibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "nameVisibleCheckBox.text"));
this.nameVisibleCheckBox.setNullable(controller.getNameVisible() == null);
this.nameVisibleCheckBox.setValue(controller.getNameVisible());
final PropertyChangeListener nameVisibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
nameVisibleCheckBox.setNullable(ev.getNewValue() == null);
nameVisibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
this.nameVisibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
controller.setNameVisible(nameVisibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.NAME_VISIBLE, nameVisibleChangeListener);
}
});
// Create X label and its spinner bound to X controller property
this.xLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "xLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel xSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.xSpinner = new NullableSpinner(xSpinnerModel);
xSpinnerModel.setNullable(controller.getX() == null);
xSpinnerModel.setLength(controller.getX());
final PropertyChangeListener xChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
xSpinnerModel.setNullable(ev.getNewValue() == null);
xSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
xSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
controller.setX(xSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.X, xChangeListener);
}
});
// Create Y label and its spinner bound to Y controller property
this.yLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "yLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel ySpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, -100000f, 100000f);
this.ySpinner = new NullableSpinner(ySpinnerModel);
ySpinnerModel.setNullable(controller.getY() == null);
ySpinnerModel.setLength(controller.getY());
final PropertyChangeListener yChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
ySpinnerModel.setNullable(ev.getNewValue() == null);
ySpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
ySpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
controller.setY(ySpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.Y, yChangeListener);
}
});
// Create elevation label and its spinner bound to ELEVATION controller property
this.elevationLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "elevationLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel elevationSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0f, 1000f);
this.elevationSpinner = new NullableSpinner(elevationSpinnerModel);
elevationSpinnerModel.setNullable(controller.getElevation() == null);
elevationSpinnerModel.setLength(controller.getElevation());
final PropertyChangeListener elevationChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
elevationSpinnerModel.setNullable(ev.getNewValue() == null);
elevationSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
elevationSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
controller.setElevation(elevationSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.ELEVATION,
elevationChangeListener);
}
});
// Create angle label and its spinner bound to ANGLE_IN_DEGREES controller property
this.angleLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "angleLabel.text"));
final NullableSpinner.NullableSpinnerNumberModel angleSpinnerModel =
new NullableSpinner.NullableSpinnerNumberModel(0, 0, 360, 1);
this.angleSpinner = new NullableSpinner(angleSpinnerModel);
Integer angle = controller.getAngleInDegrees();
angleSpinnerModel.setNullable(angle == null);
angleSpinnerModel.setValue(angle);
final PropertyChangeListener angleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
Float newAngle = (Float)ev.getNewValue();
angleSpinnerModel.setNullable(newAngle == null);
angleSpinnerModel.setValue(newAngle);
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
angleSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
Number value = (Number)angleSpinnerModel.getValue();
if (value == null) {
controller.setAngleInDegrees(null);
} else {
controller.setAngleInDegrees(value.intValue());
}
controller.addPropertyChangeListener(HomeFurnitureController.Property.ANGLE_IN_DEGREES, angleChangeListener);
}
});
// Create width label and its spinner bound to WIDTH controller property
this.widthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "widthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel widthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.widthSpinner = new NullableSpinner(widthSpinnerModel);
widthSpinnerModel.setNullable(controller.getWidth() == null);
widthSpinnerModel.setLength(controller.getWidth());
final PropertyChangeListener widthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
widthSpinnerModel.setNullable(ev.getNewValue() == null);
widthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
widthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
controller.setWidth(widthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.WIDTH, widthChangeListener);
}
});
// Create depth label and its spinner bound to DEPTH controller property
this.depthLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "depthLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel depthSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.depthSpinner = new NullableSpinner(depthSpinnerModel);
depthSpinnerModel.setNullable(controller.getDepth() == null);
depthSpinnerModel.setLength(controller.getDepth());
final PropertyChangeListener depthChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
depthSpinnerModel.setNullable(ev.getNewValue() == null);
depthSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
depthSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
controller.setDepth(depthSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.DEPTH, depthChangeListener);
}
});
// Create height label and its spinner bound to HEIGHT controller property
this.heightLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "heightLabel.text", unitName));
final NullableSpinner.NullableSpinnerLengthModel heightSpinnerModel =
new NullableSpinner.NullableSpinnerLengthModel(preferences, 0.09999f, 100000f);
this.heightSpinner = new NullableSpinner(heightSpinnerModel);
heightSpinnerModel.setNullable(controller.getHeight() == null);
heightSpinnerModel.setLength(controller.getHeight());
final PropertyChangeListener heightChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
heightSpinnerModel.setNullable(ev.getNewValue() == null);
heightSpinnerModel.setLength((Float)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
heightSpinnerModel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
controller.setHeight(heightSpinnerModel.getLength());
controller.addPropertyChangeListener(HomeFurnitureController.Property.HEIGHT, heightChangeListener);
}
});
// Create color label and its button bound to COLOR controller property
this.colorLabel = new JLabel(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "colorLabel.text"));
this.colorButton = new ColorButton();
this.colorButton.setColorDialogTitle(preferences.getLocalizedString(
HomeFurniturePanel.class, "colorDialog.title"));
this.colorButton.setColor(controller.getColor());
this.colorButton.addPropertyChangeListener(ColorButton.COLOR_PROPERTY,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
controller.setColor(colorButton.getColor());
}
});
controller.addPropertyChangeListener(HomeFurnitureController.Property.COLOR,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
colorButton.setColor(controller.getColor());
}
});
// Create visible check box bound to VISIBLE controller property
this.visibleCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "visibleCheckBox.text"));
this.visibleCheckBox.setNullable(controller.getVisible() == null);
this.visibleCheckBox.setValue(controller.getVisible());
final PropertyChangeListener visibleChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
visibleCheckBox.setNullable(ev.getNewValue() == null);
visibleCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
this.visibleCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
controller.setVisible(visibleCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.VISIBLE, visibleChangeListener);
}
});
// Create mirror check box bound to MODEL_MIRRORED controller property
this.mirroredModelCheckBox = new NullableCheckBox(SwingTools.getLocalizedLabelText(preferences,
HomeFurniturePanel.class, "mirroredModelCheckBox.text"));
this.mirroredModelCheckBox.setNullable(controller.getModelMirrored() == null);
this.mirroredModelCheckBox.setValue(controller.getModelMirrored());
final PropertyChangeListener mirroredModelChangeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
mirroredModelCheckBox.setNullable(ev.getNewValue() == null);
mirroredModelCheckBox.setValue((Boolean)ev.getNewValue());
}
};
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
this.mirroredModelCheckBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ev) {
controller.removePropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
controller.setModelMirrored(mirroredModelCheckBox.getValue());
controller.addPropertyChangeListener(HomeFurnitureController.Property.MODEL_MIRRORED, mirroredModelChangeListener);
}
});
updateSizeComponents(controller);
// Add a listener that enables / disables size fields depending on furniture resizable
controller.addPropertyChangeListener(HomeFurnitureController.Property.RESIZABLE,
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent ev) {
updateSizeComponents(controller);
}
});
this.dialogTitle = preferences.getLocalizedString(HomeFurniturePanel.class, "homeFurniture.title");
}
|
diff --git a/skyline-hotels/src/dk/wallviz/skylinehotels/Hotel.java b/skyline-hotels/src/dk/wallviz/skylinehotels/Hotel.java
index 3b6018a..ba8ad85 100644
--- a/skyline-hotels/src/dk/wallviz/skylinehotels/Hotel.java
+++ b/skyline-hotels/src/dk/wallviz/skylinehotels/Hotel.java
@@ -1,76 +1,77 @@
package dk.wallviz.skylinehotels;
public class Hotel implements Record {
String id;
String name;
String address1;
String city;
String postalCode;
int propertyCategory;
double hotelRating;
//double confidenceRating":84,
double tripAdvisorRating;
double highRate;
double lat;
double lon;
double proximityDistance;
boolean internet;
boolean pool;
double distFromColosseum;
double distFromTreviFountain;
String picture;
public Hotel(String id, String name, String address1, String city,
String postalCode, int propertyCategory, double hotelRating,
double tripAdvisorRating, double highRate, double lat, double lon,
double proximityDistance, boolean internet, boolean pool,
double distFromColosseum, double distFromTreviFountain,
String picture) {
super();
this.id = id;
this.name = name;
this.address1 = address1;
this.city = city;
this.postalCode = postalCode;
this.propertyCategory = propertyCategory;
this.hotelRating = hotelRating;
this.tripAdvisorRating = tripAdvisorRating;
this.highRate = highRate;
this.lat = lat;
this.lon = lon;
this.proximityDistance = proximityDistance;
this.internet = internet;
this.pool = pool;
this.distFromColosseum = distFromColosseum;
this.distFromTreviFountain = distFromTreviFountain;
// custom conversion for this application: data might be placed in different directories
int numericId = Integer.parseInt(id);
String path = "";
+ String[] parts = picture.split("/");
if (numericId <= 297078)
- path = "hotel_images/low/";
- else path = "hotel_images/high/";
- this.picture = path + picture;
+ path = parts[0]+"/low/"+parts[1];
+ else path = parts[0]+"/high/"+parts[1];
+ this.picture = path;
}
public String toJSON(int order) {
return "{\"order\":"+order+","+
"\"id\":"+id+","+
"\"name\":\""+name+"\","+
"\"address1\":\""+address1+"\","+
"\"city\":\""+city+"\","+
"\"postalCode\":\""+postalCode+"\","+
"\"propertyCategory\":"+propertyCategory+","+
"\"hotelRating\":"+hotelRating+","+
//"\"confidenceRating\":"+confidenceRating+","+
"\"tripAdvisorRating\":"+tripAdvisorRating+","+
"\"highRate\":"+highRate+","+
"\"lat\":"+lat+","+
"\"lon\":"+lon+","+
"\"proximityDistance\":"+proximityDistance+","+
"\"internet\":"+internet+","+
"\"pool\":"+pool+","+
"\"distFromColosseum\":"+distFromColosseum+","+
"\"distFromTreviFountain\":"+distFromTreviFountain+","+
"\"picture\":\""+picture+"\"}";
}
}
| false | true | public Hotel(String id, String name, String address1, String city,
String postalCode, int propertyCategory, double hotelRating,
double tripAdvisorRating, double highRate, double lat, double lon,
double proximityDistance, boolean internet, boolean pool,
double distFromColosseum, double distFromTreviFountain,
String picture) {
super();
this.id = id;
this.name = name;
this.address1 = address1;
this.city = city;
this.postalCode = postalCode;
this.propertyCategory = propertyCategory;
this.hotelRating = hotelRating;
this.tripAdvisorRating = tripAdvisorRating;
this.highRate = highRate;
this.lat = lat;
this.lon = lon;
this.proximityDistance = proximityDistance;
this.internet = internet;
this.pool = pool;
this.distFromColosseum = distFromColosseum;
this.distFromTreviFountain = distFromTreviFountain;
// custom conversion for this application: data might be placed in different directories
int numericId = Integer.parseInt(id);
String path = "";
if (numericId <= 297078)
path = "hotel_images/low/";
else path = "hotel_images/high/";
this.picture = path + picture;
}
| public Hotel(String id, String name, String address1, String city,
String postalCode, int propertyCategory, double hotelRating,
double tripAdvisorRating, double highRate, double lat, double lon,
double proximityDistance, boolean internet, boolean pool,
double distFromColosseum, double distFromTreviFountain,
String picture) {
super();
this.id = id;
this.name = name;
this.address1 = address1;
this.city = city;
this.postalCode = postalCode;
this.propertyCategory = propertyCategory;
this.hotelRating = hotelRating;
this.tripAdvisorRating = tripAdvisorRating;
this.highRate = highRate;
this.lat = lat;
this.lon = lon;
this.proximityDistance = proximityDistance;
this.internet = internet;
this.pool = pool;
this.distFromColosseum = distFromColosseum;
this.distFromTreviFountain = distFromTreviFountain;
// custom conversion for this application: data might be placed in different directories
int numericId = Integer.parseInt(id);
String path = "";
String[] parts = picture.split("/");
if (numericId <= 297078)
path = parts[0]+"/low/"+parts[1];
else path = parts[0]+"/high/"+parts[1];
this.picture = path;
}
|
diff --git a/us7638/sapisync/src/test/com/funambol/sapisync/MockSapiSyncHandler.java b/us7638/sapisync/src/test/com/funambol/sapisync/MockSapiSyncHandler.java
index 8b770240..e580caa3 100755
--- a/us7638/sapisync/src/test/com/funambol/sapisync/MockSapiSyncHandler.java
+++ b/us7638/sapisync/src/test/com/funambol/sapisync/MockSapiSyncHandler.java
@@ -1,171 +1,171 @@
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.sapisync;
import java.util.Vector;
import java.util.Date;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.json.me.JSONArray;
import com.funambol.sync.SyncException;
import com.funambol.sync.SyncItem;
import com.funambol.sync.SyncListener;
/**
* Implements a Mock for the SapiSyncHandler interface
*/
public class MockSapiSyncHandler extends SapiSyncHandler {
private static final String TEST_SERVER = "http://test.server.url";
private static final String TEST_USERNAME = "user";
private static final String TEST_PASSWORD = "pwd";
private ChangesSet changesSet = null;
private JSONArray fullSyncItems[] = null;
private int itemsCount;
private Vector uploadedItems = new Vector();
private int loginCount = 0;
private int logoutCount = 0;
private int fullSyncItemsIdx = 0;
private Vector limitRequests = new Vector();
private Vector dateLimitRequests = new Vector();
private Vector dateLimitAllRequests = new Vector();
private Vector offsetRequests = new Vector();
private Vector idsRequests = new Vector();
public MockSapiSyncHandler() {
super(TEST_SERVER, TEST_USERNAME, TEST_PASSWORD);
}
public void login() throws SyncException {
loginCount++;
}
public void logout() throws SyncException {
logoutCount++;
}
public void uploadItem(SyncItem item, SyncListener listener)
throws SyncException {
uploadedItems.addElement(item);
}
public ChangesSet getIncrementalChanges(Date from, String dataType) throws JSONException {
return changesSet;
}
public void setIncrementalChanges(JSONArray added, JSONArray updated, JSONArray deleted) {
ChangesSet res = new ChangesSet();
res.added = added;
res.updated = updated;
res.deleted = deleted;
this.changesSet = res;
}
- public JSONArray getItems(String remoteUri, String dataTag, JSONArray ids,
+ public FullSet getItems(String remoteUri, String dataTag, JSONArray ids,
String limit, String offset, Date from) throws JSONException {
// Save this information to be checked later
if (from != null) {
dateLimitRequests.addElement(from);
}
if (limit != null) {
limitRequests.addElement(limit);
}
if (offset != null) {
offsetRequests.addElement(offset);
}
if (ids != null) {
idsRequests.addElement(ids);
}
+ FullSet res = new FullSet();
// Return the proper value
- if (fullSyncItems == null) {
- return null;
- } else {
- return fullSyncItems[fullSyncItemsIdx++];
+ if (fullSyncItems != null) {
+ res.items = fullSyncItems[fullSyncItemsIdx++];
}
+ return res;
}
public void setItems(JSONArray fullSyncItems[]) {
this.fullSyncItems = fullSyncItems;
}
public Vector getDateLimitRequests() {
return dateLimitRequests;
}
public Vector getDateLimitAllRequests() {
return dateLimitAllRequests;
}
public Vector getLimitRequests() {
return limitRequests;
}
public Vector getOffsetRequests() {
return offsetRequests;
}
public Vector getIdsRequests() {
return idsRequests;
}
public int getItemsCount(String remoteUri, Date from) throws JSONException {
if (from != null) {
dateLimitAllRequests.addElement(from);
}
return itemsCount;
}
public void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
public Vector getUploadedItems() {
return uploadedItems;
}
public int getLoginCount() {
return loginCount;
}
public int getLogoutCount() {
return logoutCount;
}
}
| false | true | public JSONArray getItems(String remoteUri, String dataTag, JSONArray ids,
String limit, String offset, Date from) throws JSONException {
// Save this information to be checked later
if (from != null) {
dateLimitRequests.addElement(from);
}
if (limit != null) {
limitRequests.addElement(limit);
}
if (offset != null) {
offsetRequests.addElement(offset);
}
if (ids != null) {
idsRequests.addElement(ids);
}
// Return the proper value
if (fullSyncItems == null) {
return null;
} else {
return fullSyncItems[fullSyncItemsIdx++];
}
}
| public FullSet getItems(String remoteUri, String dataTag, JSONArray ids,
String limit, String offset, Date from) throws JSONException {
// Save this information to be checked later
if (from != null) {
dateLimitRequests.addElement(from);
}
if (limit != null) {
limitRequests.addElement(limit);
}
if (offset != null) {
offsetRequests.addElement(offset);
}
if (ids != null) {
idsRequests.addElement(ids);
}
FullSet res = new FullSet();
// Return the proper value
if (fullSyncItems != null) {
res.items = fullSyncItems[fullSyncItemsIdx++];
}
return res;
}
|
diff --git a/graylog2-server/src/main/java/org/graylog2/metrics/jetty2/TimedMetricsFilter.java b/graylog2-server/src/main/java/org/graylog2/metrics/jetty2/TimedMetricsFilter.java
index d6eeccf99..bf867204d 100644
--- a/graylog2-server/src/main/java/org/graylog2/metrics/jetty2/TimedMetricsFilter.java
+++ b/graylog2-server/src/main/java/org/graylog2/metrics/jetty2/TimedMetricsFilter.java
@@ -1,37 +1,38 @@
package org.graylog2.metrics.jetty2;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.annotation.Timed;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Provider
@Priority(Integer.MIN_VALUE)
public class TimedMetricsFilter extends AbstractMetricsFilter {
private final Timer timer;
public TimedMetricsFilter(MetricRegistry metricRegistry, ResourceInfo resourceInfo) {
final Timed annotation = resourceInfo.getResourceMethod().getAnnotation(Timed.class);
timer = metricRegistry.timer(chooseName(annotation.name(), annotation.absolute(), resourceInfo.getResourceMethod()));
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setProperty("metricsTimerContext", timer.time());
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
final Timer.Context context = (Timer.Context) requestContext.getProperty("metricsTimerContext");
+ if (context == null) return;
final long elapsedNanos = context.stop();
responseContext.getHeaders().add("X-Runtime-Microseconds", TimeUnit.NANOSECONDS.toMicros(elapsedNanos));
}
}
| true | true | public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
final Timer.Context context = (Timer.Context) requestContext.getProperty("metricsTimerContext");
final long elapsedNanos = context.stop();
responseContext.getHeaders().add("X-Runtime-Microseconds", TimeUnit.NANOSECONDS.toMicros(elapsedNanos));
}
| public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
final Timer.Context context = (Timer.Context) requestContext.getProperty("metricsTimerContext");
if (context == null) return;
final long elapsedNanos = context.stop();
responseContext.getHeaders().add("X-Runtime-Microseconds", TimeUnit.NANOSECONDS.toMicros(elapsedNanos));
}
|
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/ContextToObjectLink.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/ContextToObjectLink.java
index 8f02fc6a0..9ed5f7ac8 100644
--- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/ContextToObjectLink.java
+++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/services/internal/context/ContextToObjectLink.java
@@ -1,688 +1,688 @@
/*******************************************************************************
* Copyright (c) 2009 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.e4.core.services.internal.context;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.e4.core.services.context.IEclipseContext;
import org.eclipse.e4.core.services.context.spi.ContextInjectionFactory;
import org.eclipse.e4.core.services.context.spi.IContextConstants;
import org.eclipse.e4.core.services.context.spi.IRunAndTrack;
/**
* Implements injection of context values into an object. Tracks context changes and makes the
* corresponding updates to injected objects. See class comment of {@link ContextInjectionFactory}
* for details on the injection algorithm.
*/
public class ContextToObjectLink implements IRunAndTrack, IContextConstants {
private static class PropertyChangeListenerImplementation implements PropertyChangeListener {
private final String name;
private final IEclipseContext outputContext;
private PropertyChangeListenerImplementation(String name, IEclipseContext outputContext) {
this.name = name;
this.outputContext = outputContext;
}
public void propertyChange(PropertyChangeEvent evt) {
outputContext.set(name, evt.getNewValue());
}
}
abstract private class Processor {
protected boolean isSetter;
protected Object userObject;
public Processor(boolean isSetter) {
this.isSetter = isSetter;
}
public void setObject(Object userObject) {
this.userObject = userObject;
}
abstract void processMethod(Method method, boolean optional);
abstract void processField(Field field, String injectName, boolean optional);
abstract void processPostConstructMethod(Method m);
public abstract void processOutMethod(Method m, String name);
}
final static private String JAVA_OBJECT = "java.lang.Object"; //$NON-NLS-1$
final protected String fieldPrefix;
final protected String setMethodPrefix;
final protected int fieldPrefixLength;
protected IEclipseContext context;
protected List userObjects = new ArrayList(3); // start small
public ContextToObjectLink(IEclipseContext context, String fieldPrefix, String setMethodPrefix) {
this.context = context;
this.fieldPrefix = (fieldPrefix != null) ? fieldPrefix : INJECTION_FIELD_PREFIX;
this.setMethodPrefix = (setMethodPrefix != null) ? setMethodPrefix
: INJECTION_SET_METHOD_PREFIX;
fieldPrefixLength = this.fieldPrefix.length();
}
public boolean notify(final IEclipseContext notifyContext, final String name,
final int eventType, final Object[] args) {
if (eventType == IRunAndTrack.DISPOSE) {
for (Iterator it = userObjects.iterator(); it.hasNext();) {
WeakReference ref = (WeakReference) it.next();
Object referent = ref.get();
if (referent != null)
findAndCallDispose(referent, referent.getClass(), new ProcessMethodsResult());
}
}
boolean isSetter = (eventType == IRunAndTrack.ADDED || eventType == IRunAndTrack.INITIAL);
Processor processor = new Processor(isSetter) {
void processField(final Field field, String injectName, boolean optional) {
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(injectName, field.getType());
if (key != null) {
setField(args[0], field, notifyContext.get(key));
} else {
if (!optional) {
throw new IllegalStateException("Could not set " + field
+ " because of missing: " + injectName);
}
}
break;
case IRunAndTrack.ADDED:
String injectKey = findKey(name, field.getType());
if (injectKey != null
&& (keyMatches(name, injectName) || field.getType().getName().equals(
name)))
setField(userObject, field, notifyContext.get(injectKey));
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, injectName) || field.getType().getName().equals(name))
setField(userObject, field, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processMethod(final Method method, boolean optional) {
String candidateName = method.getName();
if (candidateName.length() <= setMethodPrefix.length())
return;
candidateName = candidateName.substring(setMethodPrefix.length());
Class[] parameterTypes = method.getParameterTypes();
// only inject methods with a single parameter
if (parameterTypes.length != 1)
return;
switch (eventType) {
case IRunAndTrack.INITIAL:
// when initializing, inject every method that has a match in the context
String key = findKey(candidateName, parameterTypes[0]);
if (key != null) {
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
} else {
if (!optional) {
throw new IllegalStateException("Could not invoke " + method
+ " because of missing: " + candidateName);
}
}
break;
case IRunAndTrack.ADDED:
// on add event, only inject the method corresponding to the added context key
if (keyMatches(name, candidateName)) {
key = findKey(name, parameterTypes[0]);
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
}
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, candidateName))
setMethod(userObject, method, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processPostConstructMethod(Method m) {
if (eventType == IRunAndTrack.INITIAL) {
Object[] methodArgs = null;
if (m.getParameterTypes().length == 1)
methodArgs = new Object[] { context };
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(userObject, methodArgs);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(userObject, methodArgs);
}
} catch (Exception e) {
logWarning(userObject, e);
}
}
}
public void processOutMethod(Method m, final String name) {
final IEclipseContext outputContext = (IEclipseContext) notifyContext
.get("outputs");
- if (outputContext == null) {
- throw new IllegalStateException("No output context available for @Out " + m
- + " in " + userObject);
- }
if (eventType == IRunAndTrack.INITIAL) {
+ if (outputContext == null) {
+ throw new IllegalStateException("No output context available for @Out " + m
+ + " in " + userObject);
+ }
Object value;
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
value = m.invoke(userObject, new Object[0]);
} finally {
m.setAccessible(false);
}
} else {
value = m.invoke(userObject, new Object[0]);
}
outputContext.set(name, value);
userObject.getClass().getMethod("addPropertyChangeListener",
new Class[] { String.class, PropertyChangeListener.class }).invoke(
userObject,
new Object[] {
name,
new PropertyChangeListenerImplementation(name,
outputContext) });
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
if (eventType == IRunAndTrack.INITIAL) {
if (args == null || args.length == 0 || args[0] == null)
throw new IllegalArgumentException();
Object userObject = args[0];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
WeakReference ref = new WeakReference(userObject);
synchronized (userObjects) {
userObjects.add(ref);
}
} else {
Object[] objectsCopy = safeObjectsCopy();
for (int i = 0; i < objectsCopy.length; i++) {
Object userObject = objectsCopy[i];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
}
}
return (!userObjects.isEmpty());
}
private void findAndCallDispose(Object object, Class objectsClass, ProcessMethodsResult result) {
// 1. Try a method with dispose annotation
Method[] methods = objectsClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (method.getParameterTypes().length > 0)
continue;
try {
Object[] annotations = (Object[]) method.getClass().getMethod("getAnnotations", //$NON-NLS-1$
new Class[0]).invoke(method, new Object[0]);
for (int j = 0; j < annotations.length; j++) {
Object annotation = annotations[j];
try {
String annotationName = ((Class) annotation.getClass().getMethod(
"annotationType", new Class[0]).invoke(annotation, new Object[0])) //$NON-NLS-1$
.getName();
if (annotationName.endsWith(".PreDestroy")) { //$NON-NLS-1$
if (!result.seen(method))
callDispose(object, method, null);
}
} catch (Exception ex) {
logWarning(method, ex);
}
}
} catch (Exception e) {
// ignore - no annotation support
}
}
// 2. Try IEclipseContextAware#contextDisposed(IEclipseContext)
try {
Method dispose = objectsClass.getDeclaredMethod(
IContextConstants.INJECTION_DISPOSE_CONTEXT_METHOD,
new Class[] { IEclipseContext.class });
// only call this method if we haven't found any other dispose methods yet
if (result.seenMethods.isEmpty() && !result.seen(dispose))
callDispose(object, dispose, new Object[] { context });
} catch (SecurityException e) {
// ignore
} catch (NoSuchMethodException e) {
// ignore
}
// 3. Try contextDisposed()
try {
Method dispose = objectsClass.getDeclaredMethod(
IContextConstants.INJECTION_DISPOSE_CONTEXT_METHOD, new Class[0]);
// only call this method if we haven't found any other dispose methods yet
if (result.seenMethods.isEmpty() && !result.seen(dispose))
callDispose(object, dispose, null);
return;
} catch (SecurityException e) {
// ignore
} catch (NoSuchMethodException e) {
// ignore
}
// 4. Try dispose()
try {
Method dispose = objectsClass.getDeclaredMethod("dispose", null); //$NON-NLS-1$
// only call this method if we haven't found any other dispose methods yet
if (result.seenMethods.isEmpty() && !result.seen(dispose))
callDispose(object, dispose, null);
return;
} catch (SecurityException e) {
// ignore
} catch (NoSuchMethodException e) {
// ignore
}
// 5. Recurse on superclass
Class superClass = objectsClass.getSuperclass();
if (!superClass.getName().equals(JAVA_OBJECT)) {
findAndCallDispose(object, superClass, result);
}
}
private void callDispose(Object object, Method m, Object[] args) {
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(object, args);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(object, args);
}
} catch (Exception e) {
logWarning(object, e);
}
}
private Object[] safeObjectsCopy() {
Object[] result;
int pos = 0;
synchronized (userObjects) {
result = new Object[userObjects.size()];
for (Iterator i = userObjects.iterator(); i.hasNext();) {
WeakReference ref = (WeakReference) i.next();
Object userObject = ref.get();
if (userObject == null) { // user object got GCed, clean up refs
// for future
i.remove();
continue;
}
result[pos] = userObject;
pos++;
}
}
if (pos == result.length)
return result;
// reallocate the array
Object[] tmp = new Object[pos];
System.arraycopy(result, 0, tmp, 0, pos);
return tmp;
}
/**
* For setters: we set fields first, them methods. Otherwise, clear methods first, fields next
*/
private void processClassHierarchy(Class objectsClass, Processor processor) {
ProcessMethodsResult processMethodsResult = new ProcessMethodsResult();
processClass(objectsClass, processor, processMethodsResult);
for (Iterator it = processMethodsResult.postConstructMethods.iterator(); it.hasNext();) {
Method m = (Method) it.next();
processor.processPostConstructMethod(m);
}
for (Iterator it = processMethodsResult.outMethods.iterator(); it.hasNext();) {
Method m = (Method) it.next();
String name = m.getName();
if (name.startsWith("get") && name.length() > 3) {
name = name.substring(3);
char firstChar = name.charAt(0);
if (Character.isUpperCase(firstChar)) {
firstChar = Character.toLowerCase(firstChar);
if (name.length() == 1) {
name = Character.toString(firstChar);
} else {
name = Character.toString(firstChar) + name.substring(1);
}
}
}
processor.processOutMethod(m, name);
}
}
private void processClass(Class objectsClass, Processor processor, ProcessMethodsResult result) {
if (processor.isSetter) {
processFields(objectsClass, processor);
processMethods(objectsClass, processor, result);
} else {
processMethods(objectsClass, processor, result);
processFields(objectsClass, processor);
}
// recurse on superclass
Class superClass = objectsClass.getSuperclass();
if (!superClass.getName().equals(JAVA_OBJECT)) {
processClass(superClass, processor, result);
}
}
static class ProcessMethodsResult {
List postConstructMethods = new ArrayList();
List outMethods = new ArrayList();
Set seenMethods = new HashSet();
boolean seen(Method method) {
// uniquely identify methods by name+parameter types
StringBuffer sig = new StringBuffer();
sig.append(method.getName());
Class[] parms = method.getParameterTypes();
for (int i = 0; i < parms.length; i++) {
sig.append(parms[i]);
sig.append(',');
}
return !seenMethods.add(sig.toString());
}
}
private ProcessMethodsResult processMethods(Class objectsClass, Processor processor,
ProcessMethodsResult result) {
Method[] methods = objectsClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// don't process methods already visited in subclasses
if (result.seen(method))
continue;
if (isPostConstruct(method)) {
result.postConstructMethods.add(method);
continue;
}
String candidateName = method.getName();
boolean inject = candidateName.startsWith(setMethodPrefix);
boolean optional = false;
try {
Object[] annotations = (Object[]) method.getClass().getMethod("getAnnotations",
new Class[0]).invoke(method, new Object[0]);
for (int j = 0; j < annotations.length; j++) {
Object annotation = annotations[j];
try {
String annotationName = ((Class) annotation.getClass().getMethod(
"annotationType", new Class[0]).invoke(annotation, new Object[0]))
.getName();
if (annotationName.endsWith(".Inject") || annotationName.endsWith(".In")) {
inject = true;
try {
optional = ((Boolean) annotation.getClass().getMethod("optional",
new Class[0]).invoke(annotation, new Object[0]))
.booleanValue();
} catch (Exception e) {
e.printStackTrace();
}
} else if (annotationName.endsWith(".PostConstruct")) {
inject = false;
result.postConstructMethods.add(method);
} else if (annotationName.endsWith(".Out")) {
inject = false;
result.outMethods.add(method);
} else if (annotationName.endsWith(".PreDestroy")) {
}
} catch (Exception ex) {
logWarning(method, ex);
}
}
} catch (Exception e) {
// ignore - no annotation support
}
if (inject) {
processor.processMethod(method, optional);
}
}
return result;
}
/**
* Returns whether the given method is a post-construction process method, as defined by the
* class comment of {@link ContextInjectionFactory}.
*/
private boolean isPostConstruct(Method method) {
if (!method.getName().equals(IContextConstants.INJECTION_SET_CONTEXT_METHOD))
return false;
Class[] parms = method.getParameterTypes();
if (parms.length == 0)
return true;
if (parms.length == 1 && parms[0].equals(IEclipseContext.class))
return true;
return false;
}
private void processFields(Class objectsClass, Processor processor) {
Field[] fields = objectsClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String injectName = field.getName();
boolean inject = false;
boolean optional = true;
try {
Object[] annotations = (Object[]) field.getClass().getMethod("getAnnotations",
new Class[0]).invoke(field, new Object[0]);
for (int j = 0; j < annotations.length; j++) {
Object annotation = annotations[j];
try {
String annotationName = ((Class) annotation.getClass().getMethod(
"annotationType", new Class[0]).invoke(annotation, new Object[0]))
.getName();
if (annotationName.endsWith(".Inject") || annotationName.endsWith(".In")) {
inject = true;
try {
optional = ((Boolean) annotation.getClass().getMethod("optional",
new Class[0]).invoke(annotation, new Object[0]))
.booleanValue();
} catch (Exception e) {
e.printStackTrace();
}
} else if (annotationName.endsWith(".Named")) {
try {
injectName = (String) annotation.getClass().getMethod("value",
new Class[0]).invoke(annotation, new Object[0]);
} catch (Exception e) {
e.printStackTrace();
}
} else if (annotationName.endsWith(".Resource")) {
inject = true;
String resourceName = null;
try {
resourceName = (String) annotation.getClass().getMethod("name",
new Class[0]).invoke(annotation, new Object[0]);
} catch (Exception e) {
logWarning(field, e);
}
if (resourceName != null && !resourceName.equals("")) {
injectName = resourceName;
}
}
} catch (Exception e1) {
logWarning(field, e1);
}
}
} catch (Exception e2) {
// ignore - no annotation support
}
if (!inject && injectName.startsWith(fieldPrefix)) {
inject = true;
injectName = injectName.substring(fieldPrefixLength);
}
if (inject) {
processor.processField(field, injectName, optional);
}
}
}
// ///////////////////////////////////////////////////////////////////////////
protected String findKey(String key, Class clazz) {
if (context.containsKey(key)) // priority goes to exact match
return key;
// alternate capitalization of the first char if possible
String candidate = altKey(key);
if (candidate != null) {
if (context.containsKey(candidate)) {
return candidate;
}
}
// try type name
if (context.containsKey(clazz.getName())) {
return clazz.getName();
}
return null;
}
protected boolean keyMatches(String key1, String key2) {
if (key1 == null && key2 == null)
return true;
if (key1 == null || key2 == null)
return false;
if (key1.equals(key2))
return true;
String candidate = altKey(key2);
if (candidate == null) // no alternative spellings
return false;
return key1.equals(candidate);
}
/**
* Calculates alternative spelling of the key: "log" <-> "Log", if any. Returns null if there is
* no alternate.
*/
protected String altKey(String key) {
if (key.length() == 0)
return null;
char firstChar = key.charAt(0);
String candidate = null;
if (Character.isUpperCase(firstChar)) {
firstChar = Character.toLowerCase(firstChar);
if (key.length() == 1)
candidate = Character.toString(firstChar);
else
candidate = Character.toString(firstChar) + key.substring(1);
} else if (Character.isLowerCase(firstChar)) {
firstChar = Character.toUpperCase(firstChar);
if (key.length() == 1)
candidate = Character.toString(firstChar);
else
candidate = Character.toString(firstChar) + key.substring(1);
}
return candidate;
}
protected boolean setField(Object userObject, Field field, Object value) {
if ((value != null) && !field.getType().isAssignableFrom(value.getClass())) {
// TBD add debug option
return false;
}
boolean wasAccessible = true;
if (!field.isAccessible()) {
field.setAccessible(true);
wasAccessible = false;
}
try {
field.set(userObject, value);
} catch (IllegalArgumentException e) {
logWarning(field, e);
return false;
} catch (IllegalAccessException e) {
logWarning(field, e);
return false;
} finally {
if (!wasAccessible)
field.setAccessible(false);
}
return true;
}
protected boolean setMethod(Object userObject, Method method, Object value) {
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1)
return false;
if ((value != null) && !parameterTypes[0].isAssignableFrom(value.getClass()))
return false;
boolean wasAccessible = true;
if (!method.isAccessible()) {
method.setAccessible(true);
wasAccessible = false;
}
try {
method.invoke(userObject, new Object[] { value });
} catch (IllegalArgumentException e) {
logWarning(method, e);
return false;
} catch (IllegalAccessException e) {
logWarning(method, e);
return false;
} catch (InvocationTargetException e) {
logWarning(method, e);
return false;
} finally {
if (!wasAccessible)
method.setAccessible(false);
}
return true;
}
void logWarning(Object destination, Exception e) {
System.out.println("Injection failed " + destination.toString());
if (e != null)
e.printStackTrace();
// TBD convert this into real logging
// String msg = NLS.bind("Injection failed", destination.toString());
// RuntimeLog.log(new Status(IStatus.WARNING,
// IRuntimeConstants.PI_COMMON, 0, msg, e));
}
}
| false | true | public boolean notify(final IEclipseContext notifyContext, final String name,
final int eventType, final Object[] args) {
if (eventType == IRunAndTrack.DISPOSE) {
for (Iterator it = userObjects.iterator(); it.hasNext();) {
WeakReference ref = (WeakReference) it.next();
Object referent = ref.get();
if (referent != null)
findAndCallDispose(referent, referent.getClass(), new ProcessMethodsResult());
}
}
boolean isSetter = (eventType == IRunAndTrack.ADDED || eventType == IRunAndTrack.INITIAL);
Processor processor = new Processor(isSetter) {
void processField(final Field field, String injectName, boolean optional) {
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(injectName, field.getType());
if (key != null) {
setField(args[0], field, notifyContext.get(key));
} else {
if (!optional) {
throw new IllegalStateException("Could not set " + field
+ " because of missing: " + injectName);
}
}
break;
case IRunAndTrack.ADDED:
String injectKey = findKey(name, field.getType());
if (injectKey != null
&& (keyMatches(name, injectName) || field.getType().getName().equals(
name)))
setField(userObject, field, notifyContext.get(injectKey));
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, injectName) || field.getType().getName().equals(name))
setField(userObject, field, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processMethod(final Method method, boolean optional) {
String candidateName = method.getName();
if (candidateName.length() <= setMethodPrefix.length())
return;
candidateName = candidateName.substring(setMethodPrefix.length());
Class[] parameterTypes = method.getParameterTypes();
// only inject methods with a single parameter
if (parameterTypes.length != 1)
return;
switch (eventType) {
case IRunAndTrack.INITIAL:
// when initializing, inject every method that has a match in the context
String key = findKey(candidateName, parameterTypes[0]);
if (key != null) {
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
} else {
if (!optional) {
throw new IllegalStateException("Could not invoke " + method
+ " because of missing: " + candidateName);
}
}
break;
case IRunAndTrack.ADDED:
// on add event, only inject the method corresponding to the added context key
if (keyMatches(name, candidateName)) {
key = findKey(name, parameterTypes[0]);
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
}
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, candidateName))
setMethod(userObject, method, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processPostConstructMethod(Method m) {
if (eventType == IRunAndTrack.INITIAL) {
Object[] methodArgs = null;
if (m.getParameterTypes().length == 1)
methodArgs = new Object[] { context };
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(userObject, methodArgs);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(userObject, methodArgs);
}
} catch (Exception e) {
logWarning(userObject, e);
}
}
}
public void processOutMethod(Method m, final String name) {
final IEclipseContext outputContext = (IEclipseContext) notifyContext
.get("outputs");
if (outputContext == null) {
throw new IllegalStateException("No output context available for @Out " + m
+ " in " + userObject);
}
if (eventType == IRunAndTrack.INITIAL) {
Object value;
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
value = m.invoke(userObject, new Object[0]);
} finally {
m.setAccessible(false);
}
} else {
value = m.invoke(userObject, new Object[0]);
}
outputContext.set(name, value);
userObject.getClass().getMethod("addPropertyChangeListener",
new Class[] { String.class, PropertyChangeListener.class }).invoke(
userObject,
new Object[] {
name,
new PropertyChangeListenerImplementation(name,
outputContext) });
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
if (eventType == IRunAndTrack.INITIAL) {
if (args == null || args.length == 0 || args[0] == null)
throw new IllegalArgumentException();
Object userObject = args[0];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
WeakReference ref = new WeakReference(userObject);
synchronized (userObjects) {
userObjects.add(ref);
}
} else {
Object[] objectsCopy = safeObjectsCopy();
for (int i = 0; i < objectsCopy.length; i++) {
Object userObject = objectsCopy[i];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
}
}
return (!userObjects.isEmpty());
}
| public boolean notify(final IEclipseContext notifyContext, final String name,
final int eventType, final Object[] args) {
if (eventType == IRunAndTrack.DISPOSE) {
for (Iterator it = userObjects.iterator(); it.hasNext();) {
WeakReference ref = (WeakReference) it.next();
Object referent = ref.get();
if (referent != null)
findAndCallDispose(referent, referent.getClass(), new ProcessMethodsResult());
}
}
boolean isSetter = (eventType == IRunAndTrack.ADDED || eventType == IRunAndTrack.INITIAL);
Processor processor = new Processor(isSetter) {
void processField(final Field field, String injectName, boolean optional) {
switch (eventType) {
case IRunAndTrack.INITIAL:
String key = findKey(injectName, field.getType());
if (key != null) {
setField(args[0], field, notifyContext.get(key));
} else {
if (!optional) {
throw new IllegalStateException("Could not set " + field
+ " because of missing: " + injectName);
}
}
break;
case IRunAndTrack.ADDED:
String injectKey = findKey(name, field.getType());
if (injectKey != null
&& (keyMatches(name, injectName) || field.getType().getName().equals(
name)))
setField(userObject, field, notifyContext.get(injectKey));
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, injectName) || field.getType().getName().equals(name))
setField(userObject, field, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processMethod(final Method method, boolean optional) {
String candidateName = method.getName();
if (candidateName.length() <= setMethodPrefix.length())
return;
candidateName = candidateName.substring(setMethodPrefix.length());
Class[] parameterTypes = method.getParameterTypes();
// only inject methods with a single parameter
if (parameterTypes.length != 1)
return;
switch (eventType) {
case IRunAndTrack.INITIAL:
// when initializing, inject every method that has a match in the context
String key = findKey(candidateName, parameterTypes[0]);
if (key != null) {
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
} else {
if (!optional) {
throw new IllegalStateException("Could not invoke " + method
+ " because of missing: " + candidateName);
}
}
break;
case IRunAndTrack.ADDED:
// on add event, only inject the method corresponding to the added context key
if (keyMatches(name, candidateName)) {
key = findKey(name, parameterTypes[0]);
setMethod(userObject, method, notifyContext.get(key, parameterTypes));
}
break;
case IRunAndTrack.REMOVED:
if (keyMatches(name, candidateName))
setMethod(userObject, method, null);
break;
case IRunAndTrack.DISPOSE:
break;
default:
logWarning(userObject, new IllegalArgumentException("Unknown event type: "
+ eventType));
}
}
void processPostConstructMethod(Method m) {
if (eventType == IRunAndTrack.INITIAL) {
Object[] methodArgs = null;
if (m.getParameterTypes().length == 1)
methodArgs = new Object[] { context };
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
m.invoke(userObject, methodArgs);
} finally {
m.setAccessible(false);
}
} else {
m.invoke(userObject, methodArgs);
}
} catch (Exception e) {
logWarning(userObject, e);
}
}
}
public void processOutMethod(Method m, final String name) {
final IEclipseContext outputContext = (IEclipseContext) notifyContext
.get("outputs");
if (eventType == IRunAndTrack.INITIAL) {
if (outputContext == null) {
throw new IllegalStateException("No output context available for @Out " + m
+ " in " + userObject);
}
Object value;
try {
if (!m.isAccessible()) {
m.setAccessible(true);
try {
value = m.invoke(userObject, new Object[0]);
} finally {
m.setAccessible(false);
}
} else {
value = m.invoke(userObject, new Object[0]);
}
outputContext.set(name, value);
userObject.getClass().getMethod("addPropertyChangeListener",
new Class[] { String.class, PropertyChangeListener.class }).invoke(
userObject,
new Object[] {
name,
new PropertyChangeListenerImplementation(name,
outputContext) });
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
};
if (eventType == IRunAndTrack.INITIAL) {
if (args == null || args.length == 0 || args[0] == null)
throw new IllegalArgumentException();
Object userObject = args[0];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
WeakReference ref = new WeakReference(userObject);
synchronized (userObjects) {
userObjects.add(ref);
}
} else {
Object[] objectsCopy = safeObjectsCopy();
for (int i = 0; i < objectsCopy.length; i++) {
Object userObject = objectsCopy[i];
processor.setObject(userObject);
processClassHierarchy(userObject.getClass(), processor);
}
}
return (!userObjects.isEmpty());
}
|
diff --git a/src/java/gr/agroknow/metadata/agrif/Agrif.java b/src/java/gr/agroknow/metadata/agrif/Agrif.java
index 6b21e2c..bfa18d7 100644
--- a/src/java/gr/agroknow/metadata/agrif/Agrif.java
+++ b/src/java/gr/agroknow/metadata/agrif/Agrif.java
@@ -1,148 +1,148 @@
package gr.agroknow.metadata.agrif ;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Agrif
{
public JSONObject agrif ;
public JSONArray creators ;
public JSONArray rights ;
public JSONArray relations ;
public JSONArray expressions ;
public Agrif()
{
agrif = new JSONObject() ;
creators = new JSONArray() ;
rights = new JSONArray() ;
relations = new JSONArray() ;
expressions = new JSONArray() ;
}
@SuppressWarnings("unchecked")
public void setAgrifIdentifier( int agrifIdentifier )
{
agrif.put( "agrifIdentifier", agrifIdentifier ) ;
}
@SuppressWarnings("unchecked")
public void setSet( String set )
{
agrif.put( "set", set ) ;
}
@SuppressWarnings("unchecked")
public void setStatus( String status )
{
agrif.put( "status", status ) ;
}
@SuppressWarnings("unchecked")
public void setCreationDate( String date )
{
agrif.put( "creationDate", date ) ;
}
@SuppressWarnings("unchecked")
public void setLastUpdateDate( String date )
{
agrif.put( "lastUpdateDate", date ) ;
}
@SuppressWarnings("unchecked")
public void setOrigin( String providerId, String arn )
{
JSONObject origins ;
if ( agrif.containsKey( "origin" ) )
{
origins = (JSONObject) agrif.get( "origin" ) ;
}
else
{
origins = new JSONObject() ;
}
origins.put( providerId, arn ) ;
agrif.put( "origin", origins ) ;
}
@SuppressWarnings("unchecked")
public void setRights( Rights rights )
{
this.rights.add( rights.toJSONObject() ) ;
}
@SuppressWarnings("unchecked")
public void setCreator( Creator creator )
{
creators.add( creator.toJSONObject() ) ;
}
@SuppressWarnings("unchecked")
public void setRelation( Relation relation )
{
relations.add( relation.toJSONObject() ) ;
}
@SuppressWarnings("unchecked")
public void setLanguageBlocks( LanguageBlock lblock )
{
JSONObject languageBlocks ;
if ( agrif.containsKey( "languageBlocks" ) )
{
languageBlocks = (JSONObject)agrif.get( "languageBlocks" ) ;
}
else
{
languageBlocks = new JSONObject() ;
}
languageBlocks.putAll( lblock.toJSONObject() ) ;
agrif.put( "languageBlocks", languageBlocks ) ;
}
@SuppressWarnings("unchecked")
public void setControlled( ControlledBlock block )
{
agrif.put( "controlled" , block.toJSONObject() ) ;
}
@SuppressWarnings("unchecked")
public void setExpression( Expression expression )
{
expressions.add( expression.toJSONObject() ) ;
}
public JSONObject toJSONObject()
{
assemble() ;
return agrif ;
}
public String toJSONString()
{
assemble() ;
return agrif.toJSONString() ;
}
@SuppressWarnings("unchecked")
private void assemble()
{
if ( !creators.isEmpty() )
{
agrif.put( "creator" , creators ) ;
}
if ( !rights.isEmpty() )
{
agrif.put( "rights", rights ) ;
}
if ( !relations.isEmpty() )
{
agrif.put( "relation", relations ) ;
}
if ( !expressions.isEmpty() )
{
- agrif.put( "expression", expressions ) ;
+ agrif.put( "expressions", expressions ) ;
}
}
}
| true | true | private void assemble()
{
if ( !creators.isEmpty() )
{
agrif.put( "creator" , creators ) ;
}
if ( !rights.isEmpty() )
{
agrif.put( "rights", rights ) ;
}
if ( !relations.isEmpty() )
{
agrif.put( "relation", relations ) ;
}
if ( !expressions.isEmpty() )
{
agrif.put( "expression", expressions ) ;
}
}
| private void assemble()
{
if ( !creators.isEmpty() )
{
agrif.put( "creator" , creators ) ;
}
if ( !rights.isEmpty() )
{
agrif.put( "rights", rights ) ;
}
if ( !relations.isEmpty() )
{
agrif.put( "relation", relations ) ;
}
if ( !expressions.isEmpty() )
{
agrif.put( "expressions", expressions ) ;
}
}
|
diff --git a/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java b/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java
index 9b7f59e..d70143a 100644
--- a/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java
+++ b/api/src/main/java/org/openmrs/module/spreadsheetimport/DatabaseBackend.java
@@ -1,872 +1,872 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.spreadsheetimport;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.context.Context;
import org.openmrs.module.spreadsheetimport.objects.NameValue;
/**
*
*/
public class DatabaseBackend {
/** Logger for this class and subclasses */
protected static final Log log = LogFactory.getLog(SpreadsheetImportUtil.class);
/**
* Make name pretty
*/
public static String makePrettyName(String name) {
String result = "";
boolean capitalizeNext = true;
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '_') {
result += " ";
capitalizeNext = true;
} else if (capitalizeNext) {
result += Character.toUpperCase(c);
capitalizeNext = false;
} else {
result += c;
}
}
return result;
}
/**
* Convert table_name.column_name to Table Name: Column Name
*/
public static String makePrettyTableDotColumn(String tableDotColumn) {
int index = tableDotColumn.indexOf(".");
String table = tableDotColumn.substring(0, index);
String column = tableDotColumn.substring(index + 1);
return makePrettyName(table) + ": " + makePrettyName(column);
}
/**
* Map: key = tableName.column, value = Table: Column
*/
private static Map<String, String> tableColumnMap = null;
private static Map<String, List<String>> tableColumnListMap = null;
public static Map<String, List<String>> getTableColumnListMap() throws Exception {
if (tableColumnListMap == null)
reverseEngineerDatabaseTable();
return tableColumnListMap;
}
public static Map<String, String> getTableColumnMap() throws Exception {
if (tableColumnMap == null)
reverseEngineerDatabaseTable();
return tableColumnMap;
}
private static void reverseEngineerDatabaseTable() throws Exception {
tableColumnMap = new TreeMap<String, String>();
tableColumnListMap = new TreeMap<String, List<String>>();
Connection conn = null;
Exception exception = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
// All tables
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getTables(null, null, "", null);
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
// All columns
List<String> columnNames = new ArrayList<String>();
ResultSet rsColumns = dmd.getColumns(null, null, tableName, "");
while (rsColumns.next()) {
columnNames.add(rsColumns.getString("COLUMN_NAME"));
}
rsColumns.close();
// // Remove imported keys
ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName);
while (rsImportedKeys.next()) {
String columnName = rsImportedKeys.getString("FKCOLUMN_NAME");
if (columnNames.contains(columnName) && "obs".equalsIgnoreCase(tableName) && !"value_coded".equalsIgnoreCase(columnName)) { // hack: only allow obs.value_coded to go through
columnNames.remove(columnName);
}
}
rsImportedKeys.close();
List<String> clonedColumns = new ArrayList<String>();
clonedColumns.addAll(columnNames);
// Add to map
for (String columnName : clonedColumns) {
String tableDotColumn = tableName + "." + columnName;
tableColumnMap.put(tableDotColumn, makePrettyTableDotColumn(tableDotColumn));
}
// Remove primary key
ResultSet rsPrimaryKeys = dmd.getPrimaryKeys(null, null, tableName);
while (rsPrimaryKeys.next()) {
String columnName = rsPrimaryKeys.getString("COLUMN_NAME");
if (columnNames.contains(columnName)) {
columnNames.remove(columnName);
}
}
rsPrimaryKeys.close();
tableColumnListMap.put(tableName, columnNames);
}
}
catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
}
}
public static List<NameValue> getMapNameToAllowedValue(String tableName) throws Exception {
List<NameValue> retVal = new ArrayList<NameValue>();
// Map<String, String> result = new LinkedHashMap<String, String>();
Connection conn = null;
Statement s = null;
Exception exception = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
s = conn.createStatement();
// Primary key
String primaryKey = tableName + "_id"; // Guess
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rsPrimaryKeys = dmd.getPrimaryKeys(null, null, tableName);
if (rsPrimaryKeys.next()) {
primaryKey = rsPrimaryKeys.getString("COLUMN_NAME");
}
rsPrimaryKeys.close();
ResultSet rs = null;
// Try 0: if table is person, then look for person_name
if ("person".equals(tableName)) {
try {
rs = s.executeQuery("SELECT CONCAT(given_name, ' ', family_name) name, `person_name`.`person_id` primary_key FROM `users` INNER JOIN `person_name` on `users`.`person_id` = `person_name`.`person_id` INNER JOIN `user_role` on `users`.`user_id` = `user_role`.`user_id` WHERE `user_role`.`role` = 'Provider'");
}
catch (Exception e) {
log.debug(e.toString());
}
}
// Try 1: name field in tableName
if (rs == null) {
try {
rs = s.executeQuery("select name, " + primaryKey + " from " + tableName + " order by name");
}
catch (Exception e) {
log.debug(e.toString());
}
}
// Try 2: name field in table_name
if (rs == null) {
try {
rs = s.executeQuery("select name, " + primaryKey + " from " + tableName + "_name order by name");
}
catch (Exception e) {
log.debug(e.toString());
}
}
// Try 3: just use table_id as both key and value
if (rs == null) {
rs = s.executeQuery("select " + primaryKey + ", " + primaryKey + " from " + tableName);
}
while (rs.next()) {
NameValue nameValue = new NameValue();
nameValue.setName(rs.getString(1));
nameValue.setValue(rs.getString(2));
retVal.add(nameValue);
}
rs.close();
}
catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (s != null) {
try {
s.close();
}
catch (Exception e) {}
}
if (conn != null) {
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
} else {
return retVal;
}
}
public static Map<String, String> getMapOfImportedKeyTableNameToColumnNamesForTable(String tableName) throws Exception {
Map<String, String> result = new HashMap<String, String>();
Connection conn = null;
Exception exception = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
// Not NULLable columns
DatabaseMetaData dmd = conn.getMetaData();
List<String> columnNames = new ArrayList<String>();
ResultSet rsColumns = dmd.getColumns(null, null, tableName, "");
while (rsColumns.next()) {
if (!rsColumns.getString("IS_NULLABLE").equals("YES")) {
columnNames.add(rsColumns.getString("COLUMN_NAME"));
}
}
rsColumns.close();
// Imported keys
ResultSet rsImportedKeys = dmd.getImportedKeys(null, null, tableName);
while (rsImportedKeys.next()) {
String columnName = rsImportedKeys.getString("FKCOLUMN_NAME");
if (columnNames.contains(columnName)) {
result.put(rsImportedKeys.getString("PKTABLE_NAME"), columnName);
}
}
rsImportedKeys.close();
}
catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
} else {
return result;
}
}
public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData,
boolean rollbackTransaction) throws Exception {
Connection conn = null;
Statement s = null;
Exception exception = null;
String sql = null;
String encounterId = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
conn.setAutoCommit(false);
s = conn.createStatement();
List<String> importedTables = new ArrayList<String>();
// Import
for (UniqueImport uniqueImport : rowData.keySet()) {
String tableName = uniqueImport.getTableName();
boolean isEncounter = "encounter".equals(tableName);
boolean isPerson = "person".equals(tableName);
boolean isPatientIdentifier = "patient_identifier".equals(tableName);
boolean isObservation = "obs".equals(tableName);
boolean skip = false;
// SPECIAL TREATMENT
// for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter
// otherwise, we need to create a new encounter
if (isEncounter) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
Object columnValue = column.getValue();
if (!columnValue.equals("")) {
column.setGeneratedKey(columnValue.toString());
skip = true;
importedTables.add("encounter"); // fake as just imported encounter
break;
}
}
if (skip)
continue;
}
if (isPerson) {
// SPECIAL TREATMENT 1
// if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead
// note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436)
UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null);
if (rowData.containsKey(patientIdentifier)) {
Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier);
for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) {
String columnName = patientIdentifierColumn.getColumnName();
if ("identifier".equals(columnName)) {
sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue();
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
String patientId = rs.getString(1);
// no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(patientId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
importedTables.add("patient_identifier"); // fake as just imported patient_identifier
skip = true;
}
rs.close();
break;
}
}
}
if (skip)
continue;
// SPECIAL TREATMENT 2
// if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead
UniqueImport personName = new UniqueImport("person_name", null);
if (rowData.containsKey(personName)) {
Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName);
// getting gender, birthdate from person
Object gender = null;
Object birthdate = null;
for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) {
String columnName = personColumn.getColumnName();
if ("birth_date".equals(columnName))
birthdate = personColumn.getValue();
if ("gender".equals(columnName))
gender = personColumn.getValue();
}
// getting first name, last name, middle name from person
Object givenName = null;
Object familyName = null;
Object middleName = null;
for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) {
String columnName = personNameColumn.getColumnName();
if ("given_name".equals(columnName))
givenName = personNameColumn.getValue();
if ("family_name".equals(columnName))
familyName = personNameColumn.getValue();
if ("middle_name".equals(columnName))
middleName = personNameColumn.getValue();
}
// find matching person name
- sql = "select person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName);
+ sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName);
ResultSet rs = s.executeQuery(sql);
String personId = null;
if (rs.next()) {
// matched => no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(personId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
skip = true;
}
}
if (skip)
continue;
}
if (isPatientIdentifier && importedTables.contains("patient_identifier"))
continue;
// Data from columns
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
String columnNames = "";
String columnValues = "";
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null;
Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null;
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
// special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id
if (isEncounter) {
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
// inject date_created
columnNames += "date_created";
columnValues += "now()";
// find encounter_datetime based on observation date time
java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis());
Set<UniqueImport> uniqueImports = rowData.keySet();
for (UniqueImport u : uniqueImports) {
if ("obs".equals(u.getTableName())) {
Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u);
for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) {
if ("obs_datetime".equals(obsColumn.getColumnName())) {
String obsColumnValue = obsColumn.getValue().toString();
obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1);
Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue);
if (obsColumnValueDate.before(encounterDatetime))
encounterDatetime = obsColumnValueDate;
}
}
}
}
columnNames += ", encounter_datetime";
columnValues += ",'" + encounterDatetime.toString() + "'";
isFirst = false;
break;
}
// Check for duplicates
if (column.getDisallowDuplicateValue()) {
sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue();
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
ResultSet rs = s.executeQuery(sql);
boolean foundDuplicate = rs.next();
rs.close();
if (foundDuplicate) {
throw new SpreadsheetImportDuplicateValueException(column);
}
}
if (isFirst) {
// Should be same for all columns in unique import
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
isFirst = false;
} else {
columnNames += ",";
columnValues += ",";
}
columnNames += column.getColumnName();
columnValues += column.getValue().toString();
}
// Data from pre-specified values
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnPrespecifiedValue.getColumnName();
columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue();
}
// Data from columns import before
if (!columnColumnsImportBefore.isEmpty()) {
// Set up
Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>();
for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) {
String primaryKeyColumnName = columnColumn.getColumnName();
String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey();
if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) {
String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName);
if (!mapGeneratedKey.equals(columnGeneratedKey)) {
throw new SpreadsheetImportUnhandledCaseException();
}
} else {
mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey);
}
// TODO: I believe patient and person are only tables with this relationship, if not, then this
// needs to be generalized
if (primaryKeyColumnName.equals("patient_id") &&
importedTables.contains("person") &&
!importedTables.contains("patient")) {
sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
if (!columnGeneratedKey.equals(rs.getString(1))) {
throw new SpreadsheetImportUnhandledCaseException();
}
importedTables.add("patient");
}
}
// Add columns
for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnName;
columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName);
}
}
// SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time
if (isObservation) {
boolean hasDatetime = false;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("obs_datetime".equals(column.getColumnName())) {
hasDatetime = true;
break;
}
}
if (!hasDatetime) {
columnNames += ",obs_datetime";
columnValues += ",now()";
}
}
// creator
columnNames += ",creator";
columnValues += "," + Context.getAuthenticatedUser().getId();
// uuid
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid");
if (rsColumns.next()) {
columnNames += ",uuid";
columnValues += ",uuid()";
}
rsColumns.close();
// Insert tableName
sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values ("
+ columnValues + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(rs.getString(1));
}
// SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller
if (isEncounter)
encounterId = rs.getString(1);
rs.close();
importedTables.add(uniqueImport.getTableName());
}
} catch (SQLSyntaxErrorException e) {
throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage());
} catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (s != null) {
try {
s.close();
}
catch (Exception e) {}
}
if (conn != null) {
if (rollbackTransaction) {
conn.rollback();
} else {
conn.commit();
}
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
}
return encounterId;
}
public static void validateData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData) throws SQLException, SpreadsheetImportTemplateValidationException {
Connection conn = null;
Statement s = null;
String sql = null;
SQLException exception = null;
ResultSet rs = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
s = conn.createStatement();
for (UniqueImport uniqueImport : rowData.keySet()) {
if ("obs".equals(uniqueImport.getTableName())) {
Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) {
String columnName = obsColumn.getColumnName();
String conceptId = getPrespecifiedConceptIdFromObsColumn(obsColumn);
if (conceptId == null)
throw new SpreadsheetImportTemplateValidationException("no prespecified concept ID");
if ("value_coded".equals(columnName)) {
// verify the answers are the concepts which are possible answers
//sql = "select answer_concept from concept_answer join concept_name on concept_answer.answer_concept = concept_name.concept_id where concept_name.name = '" + obsColumn.getValue() + "' and concept_answer.concept_id = '" + conceptId + "'";
sql = "select answer_concept from concept_answer where answer_concept = '" + obsColumn.getValue() + "' and concept_id = '" + conceptId + "'";
rs = s.executeQuery(sql);
if (!rs.next())
throw new SpreadsheetImportTemplateValidationException("invalid concept answer for the prespecified concept ID " + conceptId);
} else if ("value_text".equals(columnName)) {
// verify the number of characters is less than the allowed length
} else if ("value_numeric".equals(columnName)) {
// verify it's within the range specified in the concept definition
sql = "select hi_absolute, low_absolute from concept_numeric where concept_id = '" + conceptId + "'";
rs = s.executeQuery(sql);
if (!rs.next())
throw new SpreadsheetImportTemplateValidationException("prespecified concept ID " + conceptId + " is not a numeric concept");
double hiAbsolute = rs.getDouble(1);
double lowAbsolute = rs.getDouble(2);
double value = 0.0;
try {
value = Double.parseDouble(obsColumn.getValue().toString());
} catch (NumberFormatException nfe) {
throw new SpreadsheetImportTemplateValidationException("concept value is not a number");
}
if (hiAbsolute < value || lowAbsolute > value)
throw new SpreadsheetImportTemplateValidationException("concept value " + value + " of column " + columnName + " is out of range " + lowAbsolute + " - " + hiAbsolute);
} else if ("value_datetime".equals(columnName) || "obs_datetime".equals(columnName)) {
// verify datetime is defined and it can not be in the future
String value = obsColumn.getValue().toString();
String date = value.substring(1, value.length()-1);
if (Date.valueOf(date).after(new Date(System.currentTimeMillis())))
throw new SpreadsheetImportTemplateValidationException("date is in the future");
}
}
} else if ("patient_identifier".equals(uniqueImport.getTableName())) {
Set<SpreadsheetImportTemplateColumn> piColumns = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn piColumn : piColumns) {
String columnName = piColumn.getColumnName();
if (!"identifier".equals(columnName))
continue;
String pitId = getPrespecifiedPatientIdentifierTypeIdFromPatientIdentifierColumn(piColumn);
if (pitId == null)
throw new SpreadsheetImportTemplateValidationException("no prespecified patient identifier type ID");
sql = "select format from patient_identifier_type where patient_identifier_type_id = " + pitId;
rs = s.executeQuery(sql);
if (!rs.next())
throw new SpreadsheetImportTemplateValidationException("invalid prespcified patient identifier type ID");
String format = rs.getString(1);
if (format != null && format.trim().length() != 0) {
String value = piColumn.getValue().toString();
value = value.substring(1, value.length()-1);
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(value);
if (!matcher.matches())
throw new SpreadsheetImportTemplateValidationException("Patient ID is not conforming to patient identifier type");
}
}
}
}
} catch (SQLException e) {
log.debug(e.toString());
exception = e;
} catch (IllegalAccessException e) {
log.debug(e.toString());
} catch (InstantiationException e) {
log.debug(e.toString());
} catch (ClassNotFoundException e) {
log.debug(e.toString());
} finally {
if (rs != null)
try {
rs.close();
}
catch (SQLException e) {}
if (s != null) {
try {
s.close();
}
catch (SQLException e) {}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {}
}
}
if (exception != null) {
throw exception;
}
}
public static Locale getCurrentUserLocale() {
Connection conn = null;
Statement s = null;
String language = "en_GB";
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
Integer userId = Context.getAuthenticatedUser().getId();
s = conn.createStatement();
ResultSet rs = s.executeQuery("select property_value from user_property where user_id=" + userId.toString());
if (rs.next())
language = rs.getString(1);
} catch (Exception e) {
log.debug(e.toString());
}
Locale locale = new Locale(language);
return locale;
}
private static String getPrespecifiedConceptIdFromObsColumn(SpreadsheetImportTemplateColumn obsColumn) {
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> prespecifiedColumns = obsColumn.getColumnPrespecifiedValues();
for (SpreadsheetImportTemplateColumnPrespecifiedValue prespecifiedColumn : prespecifiedColumns) {
String prespecifiedColumnName = prespecifiedColumn.getColumnName();
if ("concept_id".equals(prespecifiedColumnName))
return prespecifiedColumn.getPrespecifiedValue().getValue();
}
return null;
}
private static String getPrespecifiedPatientIdentifierTypeIdFromPatientIdentifierColumn(SpreadsheetImportTemplateColumn piColumn) {
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> prespecifiedColumns = piColumn.getColumnPrespecifiedValues();
for (SpreadsheetImportTemplateColumnPrespecifiedValue prespecifiedColumn : prespecifiedColumns) {
String prespecifiedColumnName = prespecifiedColumn.getColumnName();
if ("identifier_type".equals(prespecifiedColumnName))
return prespecifiedColumn.getPrespecifiedValue().getValue();
}
return null;
}
}
| true | true | public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData,
boolean rollbackTransaction) throws Exception {
Connection conn = null;
Statement s = null;
Exception exception = null;
String sql = null;
String encounterId = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
conn.setAutoCommit(false);
s = conn.createStatement();
List<String> importedTables = new ArrayList<String>();
// Import
for (UniqueImport uniqueImport : rowData.keySet()) {
String tableName = uniqueImport.getTableName();
boolean isEncounter = "encounter".equals(tableName);
boolean isPerson = "person".equals(tableName);
boolean isPatientIdentifier = "patient_identifier".equals(tableName);
boolean isObservation = "obs".equals(tableName);
boolean skip = false;
// SPECIAL TREATMENT
// for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter
// otherwise, we need to create a new encounter
if (isEncounter) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
Object columnValue = column.getValue();
if (!columnValue.equals("")) {
column.setGeneratedKey(columnValue.toString());
skip = true;
importedTables.add("encounter"); // fake as just imported encounter
break;
}
}
if (skip)
continue;
}
if (isPerson) {
// SPECIAL TREATMENT 1
// if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead
// note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436)
UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null);
if (rowData.containsKey(patientIdentifier)) {
Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier);
for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) {
String columnName = patientIdentifierColumn.getColumnName();
if ("identifier".equals(columnName)) {
sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue();
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
String patientId = rs.getString(1);
// no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(patientId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
importedTables.add("patient_identifier"); // fake as just imported patient_identifier
skip = true;
}
rs.close();
break;
}
}
}
if (skip)
continue;
// SPECIAL TREATMENT 2
// if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead
UniqueImport personName = new UniqueImport("person_name", null);
if (rowData.containsKey(personName)) {
Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName);
// getting gender, birthdate from person
Object gender = null;
Object birthdate = null;
for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) {
String columnName = personColumn.getColumnName();
if ("birth_date".equals(columnName))
birthdate = personColumn.getValue();
if ("gender".equals(columnName))
gender = personColumn.getValue();
}
// getting first name, last name, middle name from person
Object givenName = null;
Object familyName = null;
Object middleName = null;
for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) {
String columnName = personNameColumn.getColumnName();
if ("given_name".equals(columnName))
givenName = personNameColumn.getValue();
if ("family_name".equals(columnName))
familyName = personNameColumn.getValue();
if ("middle_name".equals(columnName))
middleName = personNameColumn.getValue();
}
// find matching person name
sql = "select person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName);
ResultSet rs = s.executeQuery(sql);
String personId = null;
if (rs.next()) {
// matched => no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(personId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
skip = true;
}
}
if (skip)
continue;
}
if (isPatientIdentifier && importedTables.contains("patient_identifier"))
continue;
// Data from columns
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
String columnNames = "";
String columnValues = "";
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null;
Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null;
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
// special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id
if (isEncounter) {
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
// inject date_created
columnNames += "date_created";
columnValues += "now()";
// find encounter_datetime based on observation date time
java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis());
Set<UniqueImport> uniqueImports = rowData.keySet();
for (UniqueImport u : uniqueImports) {
if ("obs".equals(u.getTableName())) {
Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u);
for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) {
if ("obs_datetime".equals(obsColumn.getColumnName())) {
String obsColumnValue = obsColumn.getValue().toString();
obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1);
Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue);
if (obsColumnValueDate.before(encounterDatetime))
encounterDatetime = obsColumnValueDate;
}
}
}
}
columnNames += ", encounter_datetime";
columnValues += ",'" + encounterDatetime.toString() + "'";
isFirst = false;
break;
}
// Check for duplicates
if (column.getDisallowDuplicateValue()) {
sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue();
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
ResultSet rs = s.executeQuery(sql);
boolean foundDuplicate = rs.next();
rs.close();
if (foundDuplicate) {
throw new SpreadsheetImportDuplicateValueException(column);
}
}
if (isFirst) {
// Should be same for all columns in unique import
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
isFirst = false;
} else {
columnNames += ",";
columnValues += ",";
}
columnNames += column.getColumnName();
columnValues += column.getValue().toString();
}
// Data from pre-specified values
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnPrespecifiedValue.getColumnName();
columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue();
}
// Data from columns import before
if (!columnColumnsImportBefore.isEmpty()) {
// Set up
Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>();
for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) {
String primaryKeyColumnName = columnColumn.getColumnName();
String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey();
if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) {
String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName);
if (!mapGeneratedKey.equals(columnGeneratedKey)) {
throw new SpreadsheetImportUnhandledCaseException();
}
} else {
mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey);
}
// TODO: I believe patient and person are only tables with this relationship, if not, then this
// needs to be generalized
if (primaryKeyColumnName.equals("patient_id") &&
importedTables.contains("person") &&
!importedTables.contains("patient")) {
sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
if (!columnGeneratedKey.equals(rs.getString(1))) {
throw new SpreadsheetImportUnhandledCaseException();
}
importedTables.add("patient");
}
}
// Add columns
for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnName;
columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName);
}
}
// SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time
if (isObservation) {
boolean hasDatetime = false;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("obs_datetime".equals(column.getColumnName())) {
hasDatetime = true;
break;
}
}
if (!hasDatetime) {
columnNames += ",obs_datetime";
columnValues += ",now()";
}
}
// creator
columnNames += ",creator";
columnValues += "," + Context.getAuthenticatedUser().getId();
// uuid
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid");
if (rsColumns.next()) {
columnNames += ",uuid";
columnValues += ",uuid()";
}
rsColumns.close();
// Insert tableName
sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values ("
+ columnValues + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(rs.getString(1));
}
// SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller
if (isEncounter)
encounterId = rs.getString(1);
rs.close();
importedTables.add(uniqueImport.getTableName());
}
} catch (SQLSyntaxErrorException e) {
throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage());
} catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (s != null) {
try {
s.close();
}
catch (Exception e) {}
}
if (conn != null) {
if (rollbackTransaction) {
conn.rollback();
} else {
conn.commit();
}
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
}
return encounterId;
}
| public static String importData(Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData,
boolean rollbackTransaction) throws Exception {
Connection conn = null;
Statement s = null;
Exception exception = null;
String sql = null;
String encounterId = null;
try {
// Connect to db
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties p = Context.getRuntimeProperties();
String url = p.getProperty("connection.url");
conn = DriverManager.getConnection(url, p.getProperty("connection.username"),
p.getProperty("connection.password"));
conn.setAutoCommit(false);
s = conn.createStatement();
List<String> importedTables = new ArrayList<String>();
// Import
for (UniqueImport uniqueImport : rowData.keySet()) {
String tableName = uniqueImport.getTableName();
boolean isEncounter = "encounter".equals(tableName);
boolean isPerson = "person".equals(tableName);
boolean isPatientIdentifier = "patient_identifier".equals(tableName);
boolean isObservation = "obs".equals(tableName);
boolean skip = false;
// SPECIAL TREATMENT
// for encounter, if the data is available in the row, it means we're UPDATING observations for an EXISTING encounter, so we don't have to create encounter
// otherwise, we need to create a new encounter
if (isEncounter) {
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
Object columnValue = column.getValue();
if (!columnValue.equals("")) {
column.setGeneratedKey(columnValue.toString());
skip = true;
importedTables.add("encounter"); // fake as just imported encounter
break;
}
}
if (skip)
continue;
}
if (isPerson) {
// SPECIAL TREATMENT 1
// if the patient_identifier.identifier is specified and it is linked to a person, then use that person instead
// note: patient.patient_id == person.person_id (http://forum.openmrs.org/viewtopic.php?f=2&t=436)
UniqueImport patientIdentifier = new UniqueImport("patient_identifier", null);
if (rowData.containsKey(patientIdentifier)) {
Set<SpreadsheetImportTemplateColumn> patientIdentifierColumns = rowData.get(patientIdentifier);
for (SpreadsheetImportTemplateColumn patientIdentifierColumn : patientIdentifierColumns) {
String columnName = patientIdentifierColumn.getColumnName();
if ("identifier".equals(columnName)) {
sql = "select patient_id from patient_identifier where identifier = " + patientIdentifierColumn.getValue();
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
String patientId = rs.getString(1);
// no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(patientId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
importedTables.add("patient_identifier"); // fake as just imported patient_identifier
skip = true;
}
rs.close();
break;
}
}
}
if (skip)
continue;
// SPECIAL TREATMENT 2
// if first name, last name, middle name, gender, and birthdate match existing record, then use that record instead
UniqueImport personName = new UniqueImport("person_name", null);
if (rowData.containsKey(personName)) {
Set<SpreadsheetImportTemplateColumn> personNameColumns = rowData.get(personName);
// getting gender, birthdate from person
Object gender = null;
Object birthdate = null;
for (SpreadsheetImportTemplateColumn personColumn : rowData.get(uniqueImport)) {
String columnName = personColumn.getColumnName();
if ("birth_date".equals(columnName))
birthdate = personColumn.getValue();
if ("gender".equals(columnName))
gender = personColumn.getValue();
}
// getting first name, last name, middle name from person
Object givenName = null;
Object familyName = null;
Object middleName = null;
for (SpreadsheetImportTemplateColumn personNameColumn : personNameColumns) {
String columnName = personNameColumn.getColumnName();
if ("given_name".equals(columnName))
givenName = personNameColumn.getValue();
if ("family_name".equals(columnName))
familyName = personNameColumn.getValue();
if ("middle_name".equals(columnName))
middleName = personNameColumn.getValue();
}
// find matching person name
sql = "select person.person_id from person_name join person where gender " + (gender == null ? "is NULL" : "= " + gender) + " and birthdate " + (birthdate == null ? "is NULL" : "= " + birthdate) + " and given_name " + (givenName == null ? "is NULL" : "= " + givenName) + " and family_name " + (familyName == null ? "is NULL" : "= " + familyName) + " and middle_name " + (middleName == null ? "is NULL" : "= " + middleName);
ResultSet rs = s.executeQuery(sql);
String personId = null;
if (rs.next()) {
// matched => no need to insert person, use the found patient_id as person_id
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(personId);
}
importedTables.add("person"); // fake as just imported person
importedTables.add("patient"); // fake as just imported patient
skip = true;
}
}
if (skip)
continue;
}
if (isPatientIdentifier && importedTables.contains("patient_identifier"))
continue;
// Data from columns
Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport);
String columnNames = "";
String columnValues = "";
Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = null;
Set<SpreadsheetImportTemplateColumnColumn> columnColumnsImportBefore = null;
boolean isFirst = true;
for (SpreadsheetImportTemplateColumn column : columnSet) {
// special treatment for encounter: simply ignore this loop since we don't want to insert encounter_id
if (isEncounter) {
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
// inject date_created
columnNames += "date_created";
columnValues += "now()";
// find encounter_datetime based on observation date time
java.sql.Date encounterDatetime = new java.sql.Date(System.currentTimeMillis());
Set<UniqueImport> uniqueImports = rowData.keySet();
for (UniqueImport u : uniqueImports) {
if ("obs".equals(u.getTableName())) {
Set<SpreadsheetImportTemplateColumn> obsColumns = rowData.get(u);
for (SpreadsheetImportTemplateColumn obsColumn : obsColumns) {
if ("obs_datetime".equals(obsColumn.getColumnName())) {
String obsColumnValue = obsColumn.getValue().toString();
obsColumnValue = obsColumnValue.substring(1, obsColumnValue.length()-1);
Date obsColumnValueDate = java.sql.Date.valueOf(obsColumnValue);
if (obsColumnValueDate.before(encounterDatetime))
encounterDatetime = obsColumnValueDate;
}
}
}
}
columnNames += ", encounter_datetime";
columnValues += ",'" + encounterDatetime.toString() + "'";
isFirst = false;
break;
}
// Check for duplicates
if (column.getDisallowDuplicateValue()) {
sql = "select " + column.getColumnName() + " from " + column.getTableName() + " where " + column.getColumnName() + " = " + column.getValue();
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
ResultSet rs = s.executeQuery(sql);
boolean foundDuplicate = rs.next();
rs.close();
if (foundDuplicate) {
throw new SpreadsheetImportDuplicateValueException(column);
}
}
if (isFirst) {
// Should be same for all columns in unique import
columnPrespecifiedValueSet = column.getColumnPrespecifiedValues();
columnColumnsImportBefore = column.getColumnColumnsImportBefore();
isFirst = false;
} else {
columnNames += ",";
columnValues += ",";
}
columnNames += column.getColumnName();
columnValues += column.getValue().toString();
}
// Data from pre-specified values
for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnPrespecifiedValue.getColumnName();
columnValues += columnPrespecifiedValue.getPrespecifiedValue().getValue();
}
// Data from columns import before
if (!columnColumnsImportBefore.isEmpty()) {
// Set up
Map<String, String> mapPrimaryKeyColumnNameToGeneratedKey = new HashMap<String, String>();
for (SpreadsheetImportTemplateColumnColumn columnColumn : columnColumnsImportBefore) {
String primaryKeyColumnName = columnColumn.getColumnName();
String columnGeneratedKey = columnColumn.getColumnImportFirst().getGeneratedKey();
if (mapPrimaryKeyColumnNameToGeneratedKey.containsKey(primaryKeyColumnName)) {
String mapGeneratedKey = mapPrimaryKeyColumnNameToGeneratedKey.get(primaryKeyColumnName);
if (!mapGeneratedKey.equals(columnGeneratedKey)) {
throw new SpreadsheetImportUnhandledCaseException();
}
} else {
mapPrimaryKeyColumnNameToGeneratedKey.put(primaryKeyColumnName, columnGeneratedKey);
}
// TODO: I believe patient and person are only tables with this relationship, if not, then this
// needs to be generalized
if (primaryKeyColumnName.equals("patient_id") &&
importedTables.contains("person") &&
!importedTables.contains("patient")) {
sql = "insert into patient (patient_id, creator) values (" + columnGeneratedKey + ", " + Context.getAuthenticatedUser().getId() + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
if (!columnGeneratedKey.equals(rs.getString(1))) {
throw new SpreadsheetImportUnhandledCaseException();
}
importedTables.add("patient");
}
}
// Add columns
for (String columnName : mapPrimaryKeyColumnNameToGeneratedKey.keySet()) {
if (isFirst)
isFirst = false;
else {
columnNames += ",";
columnValues += ",";
}
columnNames += columnName;
columnValues += mapPrimaryKeyColumnNameToGeneratedKey.get(columnName);
}
}
// SPECIAL TREATMENT: if this is observation, then check for column obs_datetime. If not available, then use current time
if (isObservation) {
boolean hasDatetime = false;
for (SpreadsheetImportTemplateColumn column : columnSet) {
if ("obs_datetime".equals(column.getColumnName())) {
hasDatetime = true;
break;
}
}
if (!hasDatetime) {
columnNames += ",obs_datetime";
columnValues += ",now()";
}
}
// creator
columnNames += ",creator";
columnValues += "," + Context.getAuthenticatedUser().getId();
// uuid
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rsColumns = dmd.getColumns(null, null, uniqueImport.getTableName(), "uuid");
if (rsColumns.next()) {
columnNames += ",uuid";
columnValues += ",uuid()";
}
rsColumns.close();
// Insert tableName
sql = "insert into " + uniqueImport.getTableName() + " (" + columnNames + ")" + " values ("
+ columnValues + ")";
if (log.isDebugEnabled()) {
log.debug(sql);
System.out.println(sql);
}
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
rs.next();
for (SpreadsheetImportTemplateColumn column : columnSet) {
column.setGeneratedKey(rs.getString(1));
}
// SPECIAL TREATMENT: update Encounter ID back to the Excel file by returning it to the caller
if (isEncounter)
encounterId = rs.getString(1);
rs.close();
importedTables.add(uniqueImport.getTableName());
}
} catch (SQLSyntaxErrorException e) {
throw new SpreadsheetImportSQLSyntaxException(sql, e.getMessage());
} catch (Exception e) {
log.debug(e.toString());
exception = e;
}
finally {
if (s != null) {
try {
s.close();
}
catch (Exception e) {}
}
if (conn != null) {
if (rollbackTransaction) {
conn.rollback();
} else {
conn.commit();
}
try {
conn.close();
}
catch (Exception e) {}
}
}
if (exception != null) {
throw exception;
}
return encounterId;
}
|
diff --git a/Extractor_psp_cz/src/main/java/cz/opendata/linked/psp_cz/metadata/ExtractorConfig.java b/Extractor_psp_cz/src/main/java/cz/opendata/linked/psp_cz/metadata/ExtractorConfig.java
index 46b6e5e8..5d2e8eb5 100644
--- a/Extractor_psp_cz/src/main/java/cz/opendata/linked/psp_cz/metadata/ExtractorConfig.java
+++ b/Extractor_psp_cz/src/main/java/cz/opendata/linked/psp_cz/metadata/ExtractorConfig.java
@@ -1,38 +1,38 @@
package cz.opendata.linked.psp_cz.metadata;
import java.util.Calendar;
import cz.cuni.xrg.intlib.commons.configuration.DPUConfigObject;
/**
*
* Put your DPU's configuration here.
*
*/
public class ExtractorConfig implements DPUConfigObject {
/**
*
*/
private static final long serialVersionUID = -5577275030298541080L;
public int Start_year = 1918;
public int End_year = Calendar.getInstance().get(Calendar.YEAR);
public String outputFileName = "sbirka.ttl";
public boolean rewriteCache = false;
public boolean cachedLists = false;
public int timeout = 10000;
public int interval = 2000;
@Override
public boolean isValid() {
- return Start_year < End_year && Start_year >= 1918 && End_year <= Calendar.getInstance().get(Calendar.YEAR);
+ return Start_year <= End_year && Start_year >= 1918 && End_year <= Calendar.getInstance().get(Calendar.YEAR);
}
}
| true | true | public boolean isValid() {
return Start_year < End_year && Start_year >= 1918 && End_year <= Calendar.getInstance().get(Calendar.YEAR);
}
| public boolean isValid() {
return Start_year <= End_year && Start_year >= 1918 && End_year <= Calendar.getInstance().get(Calendar.YEAR);
}
|
diff --git a/ScopeDemo/src/ScopeDemo.java b/ScopeDemo/src/ScopeDemo.java
index 90f0fff..fcdaefe 100644
--- a/ScopeDemo/src/ScopeDemo.java
+++ b/ScopeDemo/src/ScopeDemo.java
@@ -1,22 +1,22 @@
//Demonstrate block scope.
class ScopeDemo {
public static void main(String args[]) {
int x; // know to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // know only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
- // y = 100; Error! y not known here. Here, y is outside of its scope.
+ y = 100; // Error! y not known here. Here, y is outside of its scope.
// x is still known here.
System.out.println("x is " + x);
}
}
| true | true | public static void main(String args[]) {
int x; // know to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // know only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; Error! y not known here. Here, y is outside of its scope.
// x is still known here.
System.out.println("x is " + x);
}
| public static void main(String args[]) {
int x; // know to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // know only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
y = 100; // Error! y not known here. Here, y is outside of its scope.
// x is still known here.
System.out.println("x is " + x);
}
|
diff --git a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/game/Board.java b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/game/Board.java
index 30e98c6..5d43e15 100644
--- a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/game/Board.java
+++ b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/game/Board.java
@@ -1,240 +1,240 @@
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
* this software, either in source code form or as a compiled binary, for any
* purpose, commercial or non-commercial, and by any means.
*
* In jurisdictions that recognize copyright laws, the author or authors of this
* software dedicate any and all copyright interest in the software to the
* public domain. We make this dedication for the benefit of the public at large
* and to the detriment of our heirs and successors. We intend this dedication
* to be an overt act of relinquishment in perpetuity of all present and future
* rights to this software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to [http://unlicense.org]
*/
package ch.bfh.bti7301.w2013.battleship.game;
import java.util.ArrayList;
import ch.bfh.bti7301.w2013.battleship.game.players.GenericPlayer.PlayerState;
/**
* @author Simon Krenger <[email protected]>
*
*/
public class Board {
/**
* Default board size
*/
private static int DEFAULT_BOARD_SIZE = 10;
private int size;
private Player owner;
private ArrayList<Ship> placedShips = new ArrayList<Ship>();
private ArrayList<Missile> placedMissiles = new ArrayList<Missile>();
private BoardSetup setup = new BoardSetup();
public Board(Player p) {
this(p, DEFAULT_BOARD_SIZE);
}
public Board(Player p, int size) {
this.size = size;
this.owner = p;
}
public int getBoardSize() {
return this.size;
}
/**
* Function to place a missile on the opponents board
*
* @param m
*/
public void placeMissile(Missile m) {
// This operation can only be made on the opponents board
if (owner == Game.getInstance().getOpponent()) {
// Check if its the players turn
if (Game.getInstance().getLocalPlayer().getPlayerState() == PlayerState.PLAYING) {
// Check if coordinates of missile were already used
for (Missile placed : placedMissiles) {
if (placed.getCoordinates().equals(m.getCoordinates())) {
throw new RuntimeException(
"Missile coordinates were already used!");
}
}
placedMissiles.add(m);
- owner.placeMissile(m);
+ owner.sendMissile(m);
System.out.println("placeMissile() called with " + m);
// TODO: Notify oberserver pattern
} else {
throw new RuntimeException("Player" + owner + " is in state "
+ owner.getPlayerState()
+ ", cannot place missile just yet!");
}
} else {
throw new RuntimeException(
"placeMissile() can only be called on the opponents board!");
}
}
public void updateMissile(Missile m) {
for (Missile placed : placedMissiles) {
if (placed.getCoordinates().equals(m.getCoordinates())) {
placed.setMissileState(m.getMissileState());
System.out.println("Missile UPDATED! Missile: "+ m);
// TODO: Notify observer pattern
return;
}
}
throw new RuntimeException("Missile " + m
+ " not found on board! placedMissiles: " + placedMissiles);
}
public ArrayList<Ship> getPlacedShips() {
return this.placedShips;
}
public ArrayList<Missile> getPlacedMissiles() {
return this.placedMissiles;
}
public boolean withinBoard(Coordinates c) {
return ((c.x <= size) && (c.y <= size)) && ((c.x > 0) && (c.y > 0));
}
public boolean checkAllShipsSunk() {
for (Ship s : getPlacedShips()) {
if (!s.isSunk()) {
return false;
}
}
return true;
}
public BoardSetup getBoardSetup() {
return this.setup;
}
public class BoardSetup {
private BoardSetup() {
}
public void moveShip(Ship s, Coordinates newStartCoordinates,
Direction d) {
}
public void moveShip(Ship s, Coordinates newStartCoordinates,
Coordinates newEndCoordinates) {
}
public void placeShip(Ship s) {
// Check boundaries of board
if (withinBoard(s.getStartCoordinates())
&& withinBoard(s.getEndCoordinates())) {
// Check if coordinates are already used
for (Ship placed : placedShips) {
for (Coordinates d : s.getExtrapolatedCoordinates()) {
for (Coordinates c : placed.getCoordinatesForShip()) {
if (c.equals(d)) {
throw new RuntimeException(
"Conflicting coordinates for ship "
+ placed + " and " + s);
}
}
}
}
placedShips.add(s);
} else {
throw new RuntimeException("Coordinates not within board!");
}
}
public void done() {
setup = null;
}
}
/**
* Class to store coordinates (X and Y)
*
* @author simon
*
*/
public static class Coordinates {
/**
* X coordinates
*/
public int x;
/**
* Y coordinates
*/
public int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
// Stolen from here:
// http://stackoverflow.com/questions/10813154/converting-number-to-letter
String alpha = x > 0 && x < 27 ? String
.valueOf((char) (x + 'A' - 1)) : null;
return alpha + y;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Coordinates other = (Coordinates) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
/**
* Enumeration for direction. This direction can be used to place ships
*
* @author simon
*
*/
public static enum Direction {
NORTH, SOUTH, WEST, EAST
}
}
| true | true | public void placeMissile(Missile m) {
// This operation can only be made on the opponents board
if (owner == Game.getInstance().getOpponent()) {
// Check if its the players turn
if (Game.getInstance().getLocalPlayer().getPlayerState() == PlayerState.PLAYING) {
// Check if coordinates of missile were already used
for (Missile placed : placedMissiles) {
if (placed.getCoordinates().equals(m.getCoordinates())) {
throw new RuntimeException(
"Missile coordinates were already used!");
}
}
placedMissiles.add(m);
owner.placeMissile(m);
System.out.println("placeMissile() called with " + m);
// TODO: Notify oberserver pattern
} else {
throw new RuntimeException("Player" + owner + " is in state "
+ owner.getPlayerState()
+ ", cannot place missile just yet!");
}
} else {
throw new RuntimeException(
"placeMissile() can only be called on the opponents board!");
}
}
| public void placeMissile(Missile m) {
// This operation can only be made on the opponents board
if (owner == Game.getInstance().getOpponent()) {
// Check if its the players turn
if (Game.getInstance().getLocalPlayer().getPlayerState() == PlayerState.PLAYING) {
// Check if coordinates of missile were already used
for (Missile placed : placedMissiles) {
if (placed.getCoordinates().equals(m.getCoordinates())) {
throw new RuntimeException(
"Missile coordinates were already used!");
}
}
placedMissiles.add(m);
owner.sendMissile(m);
System.out.println("placeMissile() called with " + m);
// TODO: Notify oberserver pattern
} else {
throw new RuntimeException("Player" + owner + " is in state "
+ owner.getPlayerState()
+ ", cannot place missile just yet!");
}
} else {
throw new RuntimeException(
"placeMissile() can only be called on the opponents board!");
}
}
|
diff --git a/extensions/entitlements/source/com/sun/identity/admin/model/TransferLimitCondition.java b/extensions/entitlements/source/com/sun/identity/admin/model/TransferLimitCondition.java
index 69079d357..58a1f279a 100644
--- a/extensions/entitlements/source/com/sun/identity/admin/model/TransferLimitCondition.java
+++ b/extensions/entitlements/source/com/sun/identity/admin/model/TransferLimitCondition.java
@@ -1,82 +1,82 @@
package com.sun.identity.admin.model;
import com.sun.identity.admin.Resources;
import com.sun.identity.entitlement.BankTransferLimitCondition;
import com.sun.identity.entitlement.EntitlementCondition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.model.SelectItem;
public class TransferLimitCondition
extends ViewCondition
implements Serializable {
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public LimitType getLimitType() {
return limitType;
}
public void setLimitType(LimitType limitType) {
this.limitType = limitType;
}
public enum LimitType {
LOWER,
UPPER;
public List<SelectItem> getItems() {
List<SelectItem> items = new ArrayList<SelectItem>();
for (LimitType lt: values()) {
items.add(new SelectItem(lt, lt.getTitle()));
}
return items;
}
public String getTitle() {
Resources r = new Resources();
return r.getString(this, toString() + ".title");
}
}
private int limit = 0;
private LimitType limitType = LimitType.UPPER;
public EntitlementCondition getEntitlementCondition() {
BankTransferLimitCondition btlc = new BankTransferLimitCondition();
btlc.setTransferLimit(limit);
switch (limitType) {
case LOWER:
btlc.setLimitType(btlc.MIN_TRANSFER_LIMIT);
break;
case UPPER:
- btlc.setLimitType(btlc.MIN_TRANSFER_LIMIT);
+ btlc.setLimitType(btlc.MAX_TRANSFER_LIMIT);
break;
}
return btlc;
}
public String getLimitTypeString() {
return limitType.toString();
}
public void setLimitTypeString(String limitTypeString) {
limitType = LimitType.valueOf(limitTypeString);
}
@Override
public String toString() {
return getTitle() + ": {" + limitType.getTitle() + " " + limit + "}";
}
}
| true | true | public EntitlementCondition getEntitlementCondition() {
BankTransferLimitCondition btlc = new BankTransferLimitCondition();
btlc.setTransferLimit(limit);
switch (limitType) {
case LOWER:
btlc.setLimitType(btlc.MIN_TRANSFER_LIMIT);
break;
case UPPER:
btlc.setLimitType(btlc.MIN_TRANSFER_LIMIT);
break;
}
return btlc;
}
| public EntitlementCondition getEntitlementCondition() {
BankTransferLimitCondition btlc = new BankTransferLimitCondition();
btlc.setTransferLimit(limit);
switch (limitType) {
case LOWER:
btlc.setLimitType(btlc.MIN_TRANSFER_LIMIT);
break;
case UPPER:
btlc.setLimitType(btlc.MAX_TRANSFER_LIMIT);
break;
}
return btlc;
}
|
diff --git a/src/team/win/WhiteBoardView.java b/src/team/win/WhiteBoardView.java
index 7cee920..105003b 100644
--- a/src/team/win/WhiteBoardView.java
+++ b/src/team/win/WhiteBoardView.java
@@ -1,217 +1,220 @@
package team.win;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
public class WhiteBoardView extends View {
private static final float TOUCH_TOLERANCE = 4;
private final Paint mPaint = new Paint();
private final DataStore mDataStore;
private List<Point> mPoints;
private boolean mPendingEventDown;
private Timer mEventDownTimer;
private float mZoomLevel = 2.0f;
private float mBoardOffsetX = 0.0f;
private float mBoardOffsetY = 0.0f;
private float mWidth, mHeight;
private float mStrokeWidth;
private float mX, mY;
private int mColor;
private class EventDownTimerTask extends TimerTask {
private float mX, mY;
public EventDownTimerTask(float x, float y) {
mX = x;
mY = y;
}
@Override
public void run() {
mPendingEventDown = false;
touchStart(mX, mY);
}
}
public WhiteBoardView(Context context, DataStore ds, int strokeWidth, int color) {
super(context);
mDataStore = ds;
resetPoints();
initPaintState();
setPrimColor(color);
setPrimStrokeWidth(strokeWidth);
initSize(getResources().getDisplayMetrics().widthPixels,
getResources().getDisplayMetrics().heightPixels);
mStrokeWidth = strokeWidth;
mColor = color;
}
private void initSize(float w, float h) {
mDataStore.setAspectRatio(w / h);
mWidth = w;
mHeight = h;
}
private void initPaintState() {
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
private void resetPoints() {
mPoints = new LinkedList<Point>();
}
public void undo() {
if (mDataStore.size() <= 0)
return;
mDataStore.remove(mDataStore.size() - 1);
invalidate();
}
protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
+ // Keep this algorithm synchronized with HTML5 canvas paint function
for (Primitive p : mDataStore.mPrimitiveList) {
- Point screenPoint = worldToScreen(p.mPoints.get(0));
+ Point firstScreenPoint = worldToScreen(p.mPoints.get(0));
+ float firstPointX = firstScreenPoint.mX;
+ float firstPointY = firstScreenPoint.mY;
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth * mZoomLevel);
if (p.mPoints.size() > 1) {
Path path = new Path();
- float lX = screenPoint.mX;
- float lY = screenPoint.mY;
- path.moveTo(lX, lY);
+ float lastX = firstPointX;
+ float lastY = firstPointY;
+ path.moveTo(lastX, lastY);
for (int i = 1; i < p.mPoints.size() - 1; i++) {
- screenPoint = worldToScreen(p.mPoints.get(i));
- float pX = screenPoint.mX;
- float pY = screenPoint.mY;
- path.quadTo(lX, lY, (lX + pX) / 2, (lY + pY) / 2);
- lX = pX;
- lY = pY;
+ firstScreenPoint = worldToScreen(p.mPoints.get(i));
+ float pointX = firstScreenPoint.mX;
+ float pointY = firstScreenPoint.mY;
+ path.quadTo(lastX, lastY, (lastX + pointX) / 2, (lastY + pointY) / 2);
+ lastX = pointX;
+ lastY = pointY;
}
c.drawPath(path, mPaint);
} else {
- c.drawPoint(screenPoint.mX, screenPoint.mY, mPaint);
+ c.drawPoint(firstPointX, firstPointY, mPaint);
}
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initSize(w, h);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(mPendingEventDown) {
toggleZoomLevel(x, y);
mPendingEventDown = false;
mEventDownTimer.cancel();
invalidate();
} else {
mPendingEventDown = true;
mEventDownTimer = new Timer();
mEventDownTimer.schedule(new EventDownTimerTask(x, y), 150);
}
break;
case MotionEvent.ACTION_MOVE:
if(!mPendingEventDown)
touchMove(x, y);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
private void touchStart(float x, float y) {
// WTF?
if(x < 0.0 || y < 0.0 || x > mWidth || y > mHeight)
return;
resetPoints();
mPoints.add(screenToWorld(x, y));
mDataStore.add(new Primitive(mStrokeWidth / mWidth, mColor, mPoints));
postInvalidate();
}
private void touchMove(float x, float y) {
// WTF?
if(x < 0.0 || y < 0.0 || x > mWidth || y > mHeight)
return;
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPoints.add(screenToWorld(x, y));
mDataStore.remove(mDataStore.size() - 1);
mDataStore.add(new Primitive(mStrokeWidth / mWidth, mColor, mPoints));
mX = x;
mY = y;
}
invalidate();
}
protected void setPrimColor(int c) {
mColor = c;
}
protected void setPrimStrokeWidth(int w) {
mStrokeWidth = w;
}
private void toggleZoomLevel(float x, float y) {
if(mZoomLevel == 2.0f) {
// zooming out, don't want offsets
mBoardOffsetX = 0.0f;
mBoardOffsetY = 0.0f;
mZoomLevel = 1.0f;
} else {
// x,y are the centre of zoom box; compute top-left
// corner and rewrite in world coordinates
x = (x / mWidth) - 0.25f;
y = (y / mHeight) - 0.25f;
// clamp to max 0.5f,0.5f (bottom-right quadrant)
x = Math.max(Math.min(x, 0.5f), 0.0f);
y = Math.max(Math.min(y, 0.5f), 0.0f);
mBoardOffsetX = x;
mBoardOffsetY = y;
mZoomLevel = 2.0f;
}
}
private Point worldToScreen(Point p) {
return new Point((p.mX - mBoardOffsetX) * mWidth * mZoomLevel,
(p.mY - mBoardOffsetY) * mHeight * mZoomLevel);
}
private Point screenToWorld(float x, float y) {
return new Point(x / mWidth / mZoomLevel + mBoardOffsetX,
y / mHeight / mZoomLevel + mBoardOffsetY);
}
}
| false | true | protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
for (Primitive p : mDataStore.mPrimitiveList) {
Point screenPoint = worldToScreen(p.mPoints.get(0));
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth * mZoomLevel);
if (p.mPoints.size() > 1) {
Path path = new Path();
float lX = screenPoint.mX;
float lY = screenPoint.mY;
path.moveTo(lX, lY);
for (int i = 1; i < p.mPoints.size() - 1; i++) {
screenPoint = worldToScreen(p.mPoints.get(i));
float pX = screenPoint.mX;
float pY = screenPoint.mY;
path.quadTo(lX, lY, (lX + pX) / 2, (lY + pY) / 2);
lX = pX;
lY = pY;
}
c.drawPath(path, mPaint);
} else {
c.drawPoint(screenPoint.mX, screenPoint.mY, mPaint);
}
}
}
| protected void onDraw(Canvas c) {
Paint temp = new Paint();
temp.setColor(Color.WHITE);
temp.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, mWidth, mHeight, temp);
// Keep this algorithm synchronized with HTML5 canvas paint function
for (Primitive p : mDataStore.mPrimitiveList) {
Point firstScreenPoint = worldToScreen(p.mPoints.get(0));
float firstPointX = firstScreenPoint.mX;
float firstPointY = firstScreenPoint.mY;
mPaint.setColor(p.mColor | 0xFF000000);
mPaint.setStrokeWidth(p.mStrokeWidth * mWidth * mZoomLevel);
if (p.mPoints.size() > 1) {
Path path = new Path();
float lastX = firstPointX;
float lastY = firstPointY;
path.moveTo(lastX, lastY);
for (int i = 1; i < p.mPoints.size() - 1; i++) {
firstScreenPoint = worldToScreen(p.mPoints.get(i));
float pointX = firstScreenPoint.mX;
float pointY = firstScreenPoint.mY;
path.quadTo(lastX, lastY, (lastX + pointX) / 2, (lastY + pointY) / 2);
lastX = pointX;
lastY = pointY;
}
c.drawPath(path, mPaint);
} else {
c.drawPoint(firstPointX, firstPointY, mPaint);
}
}
}
|
diff --git a/src/lucandra/IndexReader.java b/src/lucandra/IndexReader.java
index a3db8ec..6b74ecb 100644
--- a/src/lucandra/IndexReader.java
+++ b/src/lucandra/IndexReader.java
@@ -1,601 +1,601 @@
/**
* Copyright T Jake Luciani
*
* 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 lucandra;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import lucandra.cluster.CassandraIndexManager;
import com.google.common.collect.MapMaker;
import org.apache.cassandra.db.*;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.OpenBitSet;
import solandra.SolandraFieldSelector;
public class IndexReader extends org.apache.lucene.index.IndexReader
{
private final static int numDocs = CassandraIndexManager.maxDocsPerShard;
private final static byte defaultNorm = Similarity.encodeNorm(1.0f);
private final static Directory mockDirectory = new RAMDirectory();
static
{
try
{
new IndexWriter(mockDirectory, new SimpleAnalyzer(), true, MaxFieldLength.LIMITED);
}
catch (CorruptIndexException e)
{
throw new RuntimeException(e);
}
catch (LockObtainFailedException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
private final static ThreadLocal<String> indexName = new ThreadLocal<String>();
private final static ThreadLocal<ReaderCache> activeCache = new ThreadLocal<ReaderCache>();
private final static ConcurrentMap<String, ReaderCache> globalCache = new MapMaker().makeMap();
private static final Logger logger = Logger.getLogger(IndexReader.class);
public IndexReader(String name)
{
super();
setIndexName(name);
}
public synchronized IndexReader reopen() throws CorruptIndexException, IOException
{
clearCache();
return this;
}
@Override
public synchronized IndexReader reopen(boolean openReadOnly) throws CorruptIndexException, IOException
{
return reopen();
}
@Override
public synchronized IndexReader reopen(IndexCommit commit) throws CorruptIndexException, IOException
{
return reopen();
}
public void clearCache()
{
String activeIndex = getIndexName();
if (activeIndex != null)
{
globalCache.remove(activeIndex);
}
activeCache.remove();
}
public ReaderCache getCache() throws IOException
{
String activeIndex = getIndexName();
if (activeIndex == null)
throw new IllegalStateException();
ReaderCache cache = activeCache.get();
if (cache != null)
return cache;
else
cache = globalCache.get(activeIndex);
if (cache == null)
{
synchronized (activeIndex.intern())
{
cache = globalCache.get(activeIndex);
if (cache == null)
{
cache = new ReaderCache(activeIndex);
globalCache.put(activeIndex, cache);
}
}
}
activeCache.set(cache);
return cache;
}
protected void doClose() throws IOException
{
clearCache();
}
protected void doCommit() throws IOException
{
clearCache();
}
protected void doDelete(int arg0) throws CorruptIndexException, IOException
{
}
protected void doSetNorm(int arg0, String arg1, byte arg2) throws CorruptIndexException, IOException
{
}
protected void doUndeleteAll() throws CorruptIndexException, IOException
{
}
public int docFreq(Term term) throws IOException
{
LucandraTermInfo[] docs = getCache().termCache.get(term);
if (docs != null)
return docs.length;
LucandraTermEnum termEnum = new LucandraTermEnum(this);
if (termEnum.skipTo(term) && termEnum.term().equals(term))
{
return termEnum.docFreq();
}
return 0;
}
public Document document(int docNum, FieldSelector selector) throws CorruptIndexException, IOException
{
Map<Integer, Document> documentCache = getCache().documents;
Document doc = documentCache.get(docNum);
if (doc != null)
{
if (logger.isDebugEnabled())
logger.debug("Found doc in cache");
return doc;
}
String indexName = getIndexName();
List<ByteBuffer> fieldNames = null;
Map<Integer, ByteBuffer> keyMap = new HashMap<Integer, ByteBuffer>();
keyMap.put(docNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"), CassandraUtils.delimeterBytes, Integer
.toHexString(docNum).getBytes("UTF-8")));
// Special field selector used to carry list of other docIds to cache in
// Parallel for Solr Performance
if (selector != null && selector instanceof SolandraFieldSelector)
{
List<Integer> otherDocIds = ((SolandraFieldSelector) selector).getOtherDocsToCache();
fieldNames = ((SolandraFieldSelector) selector).getFieldNames();
if (logger.isDebugEnabled())
logger.debug("Going to bulk load " + otherDocIds.size() + " documents");
for (Integer otherDocNum : otherDocIds)
{
if (otherDocNum == docNum)
continue;
if (documentCache.containsKey(otherDocNum))
continue;
byte[] docKey = Integer.toHexString(otherDocNum).getBytes("UTF-8");
if (docKey == null)
continue;
keyMap.put(otherDocNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"),
CassandraUtils.delimeterBytes, docKey));
}
}
ColumnParent columnParent = new ColumnParent();
columnParent.setColumn_family(CassandraUtils.docColumnFamily);
long start = System.currentTimeMillis();
try
{
List<Row> rows = null;
List<ReadCommand> readCommands = new ArrayList<ReadCommand>();
for (ByteBuffer key : keyMap.values())
{
if (fieldNames == null || fieldNames.size() == 0)
{
// get all columns ( except this skips meta info )
readCommands.add(new SliceFromReadCommand(CassandraUtils.keySpace, key, columnParent,
ByteBufferUtil.EMPTY_BYTE_BUFFER, CassandraUtils.finalTokenBytes, false, Integer.MAX_VALUE));
}
else
{
readCommands
.add(new SliceByNamesReadCommand(CassandraUtils.keySpace, key, columnParent, fieldNames));
}
}
rows = CassandraUtils.robustRead(CassandraUtils.consistency, readCommands.toArray(new ReadCommand[]{}));
// allow lookup by row
Map<ByteBuffer, Row> rowMap = new HashMap<ByteBuffer, Row>(keyMap.size());
for (Row row : rows)
{
rowMap.put(row.key.key, row);
}
for (Map.Entry<Integer, ByteBuffer> key : keyMap.entrySet())
{
Document cacheDoc = new Document();
Row row = rowMap.get(key.getValue());
if (row == null || row.cf == null)
{
logger.warn("Missing document in multiget_slice for: "
+ ByteBufferUtil.string(key.getValue(), CassandraUtils.UTF_8) + " " + rowMap);
}
else
{
for (IColumn col : row.cf.getSortedColumns())
{
Field field = null;
String fieldName = ByteBufferUtil.string(col.name());
// Incase __META__ slips through
if (ByteBufferUtil.compare(col.name(), CassandraUtils.documentMetaFieldBytes.array()) == 0)
{
logger.warn("Filtering out __META__ key");
continue;
}
byte[] value;
ByteBuffer v = col.value();
- int vlimit = v.limit();
+ int vlimit = v.limit() - v.position();
- if (v.get(vlimit - 1) != Byte.MAX_VALUE && v.get(vlimit - 1) != Byte.MIN_VALUE)
+ if (v.get(v.limit() - 1) != Byte.MAX_VALUE && v.get(v.limit() - 1) != Byte.MIN_VALUE)
{
throw new CorruptIndexException("Lucandra field is not properly encoded: " + docNum + "("
+ fieldName + ")");
}
- else if (v.get(vlimit - 1) == Byte.MAX_VALUE)
+ else if (v.get(v.limit() - 1) == Byte.MAX_VALUE)
{ // Binary
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
field = new Field(fieldName, value, Store.YES);
cacheDoc.add(field);
}
- else if (v.get(vlimit - 1) == Byte.MIN_VALUE)
+ else if (v.get(v.limit() - 1) == Byte.MIN_VALUE)
{ // String
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
// Check for multi-fields
String fieldString = new String(value, "UTF-8");
if (fieldString.indexOf(CassandraUtils.delimeter) >= 0)
{
StringTokenizer tok = new StringTokenizer(fieldString, CassandraUtils.delimeter);
while (tok.hasMoreTokens())
{
field = new Field(fieldName, tok.nextToken(), Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
else
{
field = new Field(fieldName, fieldString, Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
}
}
// Mark the required doc
if (key.getKey().equals(docNum))
doc = cacheDoc;
// only cache complete docs
if (fieldNames == null || fieldNames.size() == 0)
documentCache.put(key.getKey(), cacheDoc);
}
long end = System.currentTimeMillis();
if (logger.isDebugEnabled())
logger.debug("Document read took: " + (end - start) + "ms");
return doc;
}
catch (Exception e)
{
throw new IOException(e);
}
}
@Override
public Object getFieldCacheKey()
{
try
{
return getCache().fieldCacheKey;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public Collection getFieldNames(FieldOption fieldOption)
{
return Arrays.asList(new String[] {});
}
@Override
public TermFreqVector getTermFreqVector(int docNum, String field) throws IOException
{
TermFreqVector termVector = new lucandra.TermFreqVector(getIndexName(), field, docNum);
return termVector;
}
@Override
public void getTermFreqVector(int arg0, TermVectorMapper arg1) throws IOException
{
throw new RuntimeException();
}
@Override
public void getTermFreqVector(int arg0, String arg1, TermVectorMapper arg2) throws IOException
{
throw new RuntimeException();
}
@Override
public TermFreqVector[] getTermFreqVectors(int arg0) throws IOException
{
throw new RuntimeException();
}
@Override
public boolean hasDeletions()
{
return false;
}
@Override
public boolean isDeleted(int arg0)
{
return false;
}
@Override
public int maxDoc()
{
return numDocs + 1;
}
@Override
public byte[] norms(String field) throws IOException
{
return getCache().fieldNorms.get(field);
}
@Override
public void norms(String arg0, byte[] arg1, int arg2) throws IOException
{
throw new RuntimeException("This operation is not supported");
}
@Override
public int numDocs()
{
return numDocs;
}
@Override
public TermDocs termDocs(Term term) throws IOException
{
if (term == null)
return new LucandraAllTermDocs(this);
return super.termDocs(term);
}
@Override
public TermDocs termDocs() throws IOException
{
return new LucandraTermDocs(this);
}
@Override
public TermPositions termPositions() throws IOException
{
return new LucandraTermDocs(this);
}
@Override
public TermEnum terms() throws IOException
{
return new LucandraTermEnum(this);
}
@Override
public TermEnum terms(Term term) throws IOException
{
TermEnum termEnum = new LucandraTermEnum(this);
termEnum.skipTo(term);
return termEnum;
}
public void addDocumentNormalizations(LucandraTermInfo[] allDocs, String field, ReaderCache cache)
{
byte[] norms = cache.fieldNorms.get(field);
OpenBitSet docHits = cache.docHits;
for (LucandraTermInfo docInfo : allDocs)
{
int idx = docInfo.docId;
if (idx > numDocs)
throw new IllegalStateException("numDocs reached");
Byte norm = docInfo.norm;
if (norm == null)
norm = defaultNorm;
// Check for cached reads
if (norms != null && norms.length > idx && norms[idx] == norm)
continue;
docHits.fastSet(idx);
if (norms == null)
norms = new byte[numDocs];
norms[idx] = norm;
}
cache.fieldNorms.put(field, norms);
}
public String getIndexName()
{
String name = indexName.get();
return name == null ? "" : name;
}
public void setIndexName(String name)
{
activeCache.remove();
indexName.set(name);
}
@Override
public Directory directory()
{
return mockDirectory;
}
@Override
public long getVersion()
{
return Long.MAX_VALUE;
}
@Override
public boolean isOptimized()
{
return true;
}
@Override
public boolean isCurrent()
{
return true;
}
public OpenBitSet getDocsHit()
{
try
{
return getCache().docHits;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
| false | true | public Document document(int docNum, FieldSelector selector) throws CorruptIndexException, IOException
{
Map<Integer, Document> documentCache = getCache().documents;
Document doc = documentCache.get(docNum);
if (doc != null)
{
if (logger.isDebugEnabled())
logger.debug("Found doc in cache");
return doc;
}
String indexName = getIndexName();
List<ByteBuffer> fieldNames = null;
Map<Integer, ByteBuffer> keyMap = new HashMap<Integer, ByteBuffer>();
keyMap.put(docNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"), CassandraUtils.delimeterBytes, Integer
.toHexString(docNum).getBytes("UTF-8")));
// Special field selector used to carry list of other docIds to cache in
// Parallel for Solr Performance
if (selector != null && selector instanceof SolandraFieldSelector)
{
List<Integer> otherDocIds = ((SolandraFieldSelector) selector).getOtherDocsToCache();
fieldNames = ((SolandraFieldSelector) selector).getFieldNames();
if (logger.isDebugEnabled())
logger.debug("Going to bulk load " + otherDocIds.size() + " documents");
for (Integer otherDocNum : otherDocIds)
{
if (otherDocNum == docNum)
continue;
if (documentCache.containsKey(otherDocNum))
continue;
byte[] docKey = Integer.toHexString(otherDocNum).getBytes("UTF-8");
if (docKey == null)
continue;
keyMap.put(otherDocNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"),
CassandraUtils.delimeterBytes, docKey));
}
}
ColumnParent columnParent = new ColumnParent();
columnParent.setColumn_family(CassandraUtils.docColumnFamily);
long start = System.currentTimeMillis();
try
{
List<Row> rows = null;
List<ReadCommand> readCommands = new ArrayList<ReadCommand>();
for (ByteBuffer key : keyMap.values())
{
if (fieldNames == null || fieldNames.size() == 0)
{
// get all columns ( except this skips meta info )
readCommands.add(new SliceFromReadCommand(CassandraUtils.keySpace, key, columnParent,
ByteBufferUtil.EMPTY_BYTE_BUFFER, CassandraUtils.finalTokenBytes, false, Integer.MAX_VALUE));
}
else
{
readCommands
.add(new SliceByNamesReadCommand(CassandraUtils.keySpace, key, columnParent, fieldNames));
}
}
rows = CassandraUtils.robustRead(CassandraUtils.consistency, readCommands.toArray(new ReadCommand[]{}));
// allow lookup by row
Map<ByteBuffer, Row> rowMap = new HashMap<ByteBuffer, Row>(keyMap.size());
for (Row row : rows)
{
rowMap.put(row.key.key, row);
}
for (Map.Entry<Integer, ByteBuffer> key : keyMap.entrySet())
{
Document cacheDoc = new Document();
Row row = rowMap.get(key.getValue());
if (row == null || row.cf == null)
{
logger.warn("Missing document in multiget_slice for: "
+ ByteBufferUtil.string(key.getValue(), CassandraUtils.UTF_8) + " " + rowMap);
}
else
{
for (IColumn col : row.cf.getSortedColumns())
{
Field field = null;
String fieldName = ByteBufferUtil.string(col.name());
// Incase __META__ slips through
if (ByteBufferUtil.compare(col.name(), CassandraUtils.documentMetaFieldBytes.array()) == 0)
{
logger.warn("Filtering out __META__ key");
continue;
}
byte[] value;
ByteBuffer v = col.value();
int vlimit = v.limit();
if (v.get(vlimit - 1) != Byte.MAX_VALUE && v.get(vlimit - 1) != Byte.MIN_VALUE)
{
throw new CorruptIndexException("Lucandra field is not properly encoded: " + docNum + "("
+ fieldName + ")");
}
else if (v.get(vlimit - 1) == Byte.MAX_VALUE)
{ // Binary
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
field = new Field(fieldName, value, Store.YES);
cacheDoc.add(field);
}
else if (v.get(vlimit - 1) == Byte.MIN_VALUE)
{ // String
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
// Check for multi-fields
String fieldString = new String(value, "UTF-8");
if (fieldString.indexOf(CassandraUtils.delimeter) >= 0)
{
StringTokenizer tok = new StringTokenizer(fieldString, CassandraUtils.delimeter);
while (tok.hasMoreTokens())
{
field = new Field(fieldName, tok.nextToken(), Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
else
{
field = new Field(fieldName, fieldString, Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
}
}
// Mark the required doc
if (key.getKey().equals(docNum))
doc = cacheDoc;
// only cache complete docs
if (fieldNames == null || fieldNames.size() == 0)
documentCache.put(key.getKey(), cacheDoc);
}
long end = System.currentTimeMillis();
if (logger.isDebugEnabled())
logger.debug("Document read took: " + (end - start) + "ms");
return doc;
}
catch (Exception e)
{
throw new IOException(e);
}
}
| public Document document(int docNum, FieldSelector selector) throws CorruptIndexException, IOException
{
Map<Integer, Document> documentCache = getCache().documents;
Document doc = documentCache.get(docNum);
if (doc != null)
{
if (logger.isDebugEnabled())
logger.debug("Found doc in cache");
return doc;
}
String indexName = getIndexName();
List<ByteBuffer> fieldNames = null;
Map<Integer, ByteBuffer> keyMap = new HashMap<Integer, ByteBuffer>();
keyMap.put(docNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"), CassandraUtils.delimeterBytes, Integer
.toHexString(docNum).getBytes("UTF-8")));
// Special field selector used to carry list of other docIds to cache in
// Parallel for Solr Performance
if (selector != null && selector instanceof SolandraFieldSelector)
{
List<Integer> otherDocIds = ((SolandraFieldSelector) selector).getOtherDocsToCache();
fieldNames = ((SolandraFieldSelector) selector).getFieldNames();
if (logger.isDebugEnabled())
logger.debug("Going to bulk load " + otherDocIds.size() + " documents");
for (Integer otherDocNum : otherDocIds)
{
if (otherDocNum == docNum)
continue;
if (documentCache.containsKey(otherDocNum))
continue;
byte[] docKey = Integer.toHexString(otherDocNum).getBytes("UTF-8");
if (docKey == null)
continue;
keyMap.put(otherDocNum, CassandraUtils.hashKeyBytes(indexName.getBytes("UTF-8"),
CassandraUtils.delimeterBytes, docKey));
}
}
ColumnParent columnParent = new ColumnParent();
columnParent.setColumn_family(CassandraUtils.docColumnFamily);
long start = System.currentTimeMillis();
try
{
List<Row> rows = null;
List<ReadCommand> readCommands = new ArrayList<ReadCommand>();
for (ByteBuffer key : keyMap.values())
{
if (fieldNames == null || fieldNames.size() == 0)
{
// get all columns ( except this skips meta info )
readCommands.add(new SliceFromReadCommand(CassandraUtils.keySpace, key, columnParent,
ByteBufferUtil.EMPTY_BYTE_BUFFER, CassandraUtils.finalTokenBytes, false, Integer.MAX_VALUE));
}
else
{
readCommands
.add(new SliceByNamesReadCommand(CassandraUtils.keySpace, key, columnParent, fieldNames));
}
}
rows = CassandraUtils.robustRead(CassandraUtils.consistency, readCommands.toArray(new ReadCommand[]{}));
// allow lookup by row
Map<ByteBuffer, Row> rowMap = new HashMap<ByteBuffer, Row>(keyMap.size());
for (Row row : rows)
{
rowMap.put(row.key.key, row);
}
for (Map.Entry<Integer, ByteBuffer> key : keyMap.entrySet())
{
Document cacheDoc = new Document();
Row row = rowMap.get(key.getValue());
if (row == null || row.cf == null)
{
logger.warn("Missing document in multiget_slice for: "
+ ByteBufferUtil.string(key.getValue(), CassandraUtils.UTF_8) + " " + rowMap);
}
else
{
for (IColumn col : row.cf.getSortedColumns())
{
Field field = null;
String fieldName = ByteBufferUtil.string(col.name());
// Incase __META__ slips through
if (ByteBufferUtil.compare(col.name(), CassandraUtils.documentMetaFieldBytes.array()) == 0)
{
logger.warn("Filtering out __META__ key");
continue;
}
byte[] value;
ByteBuffer v = col.value();
int vlimit = v.limit() - v.position();
if (v.get(v.limit() - 1) != Byte.MAX_VALUE && v.get(v.limit() - 1) != Byte.MIN_VALUE)
{
throw new CorruptIndexException("Lucandra field is not properly encoded: " + docNum + "("
+ fieldName + ")");
}
else if (v.get(v.limit() - 1) == Byte.MAX_VALUE)
{ // Binary
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
field = new Field(fieldName, value, Store.YES);
cacheDoc.add(field);
}
else if (v.get(v.limit() - 1) == Byte.MIN_VALUE)
{ // String
value = new byte[vlimit - 1];
ByteBufferUtil.arrayCopy(v, v.position(), value, 0, vlimit - 1);
// Check for multi-fields
String fieldString = new String(value, "UTF-8");
if (fieldString.indexOf(CassandraUtils.delimeter) >= 0)
{
StringTokenizer tok = new StringTokenizer(fieldString, CassandraUtils.delimeter);
while (tok.hasMoreTokens())
{
field = new Field(fieldName, tok.nextToken(), Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
else
{
field = new Field(fieldName, fieldString, Store.YES, Index.ANALYZED);
cacheDoc.add(field);
}
}
}
}
// Mark the required doc
if (key.getKey().equals(docNum))
doc = cacheDoc;
// only cache complete docs
if (fieldNames == null || fieldNames.size() == 0)
documentCache.put(key.getKey(), cacheDoc);
}
long end = System.currentTimeMillis();
if (logger.isDebugEnabled())
logger.debug("Document read took: " + (end - start) + "ms");
return doc;
}
catch (Exception e)
{
throw new IOException(e);
}
}
|
diff --git a/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/GmlHandler.java b/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/GmlHandler.java
index 3f9ba4180..9d5e2779f 100644
--- a/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/GmlHandler.java
+++ b/gmlhandler/src/main/java/eu/esdihumboldt/gmlhandler/GmlHandler.java
@@ -1,323 +1,330 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2010.
*/
package eu.esdihumboldt.gmlhandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.log4j.Logger;
import org.deegree.commons.xml.XMLParsingException;
import org.deegree.commons.xml.stax.IndentingXMLStreamWriter;
import org.deegree.cs.exceptions.TransformationException;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.types.ApplicationSchema;
import org.deegree.gml.GMLInputFactory;
import org.deegree.gml.GMLStreamReader;
import org.deegree.gml.GMLVersion;
import org.deegree.gml.feature.schema.ApplicationSchemaXSDDecoder;
import org.opengis.feature.Feature;
import org.opengis.feature.type.FeatureType;
import eu.esdihumboldt.gmlhandler.deegree.GMLStreamWriter;
import eu.esdihumboldt.gmlhandler.gt2deegree.GtToDgConvertor;
import eu.esdihumboldt.gmlhandler.gt2deegree.TypeIndex;
/**
* <p>
* This class implements methods for handling of the gml data.
* </p>
*
* <p>
* Supported GML versions:
* <ul>
* <li>gml_2</li>
* <li>gml_3_0</li>
* <li>gml_3_1</li>
* <li>gml_3_2</li>
* </ul>
* </p>
*
*
*
* @author Anna Pitaev, Simon Templer
* @partner 04 / Logica, 01 / Fraunhofer Institute for Computer Graphics Research
* @version $Id$
*/
public class GmlHandler {
/** Logger for this class */
private static final Logger LOG = Logger.getLogger(GmlHandler.class);
/** gml version */
private GMLVersion gmlVersion;
/** schema location */
private String schemaUrl;
/** data location */
private String gmlUrl;
/** target gml location */
private String targetGmlUrl;
/**
* Constructor
*
* @param gmlVersion
* gml format to be processed,
* @param schemaUrl
* schema location
*/
public GmlHandler(GMLVersions gmlVersion, String schemaUrl) {
this.gmlVersion = getGMLVersion(gmlVersion);
this.schemaUrl = schemaUrl;
}
public static GmlHandler getDefaultInstance(String xsdUrl, String gmlUrl){
// set up GMLHandler with the test configuration
GmlHandler handler = new GmlHandler(GMLVersions.gml3_2_1, xsdUrl);
handler.setTargetGmlUrl(gmlUrl);
return handler;
}
/**
* Loads the underlying schema.
*
* @return ApplicationSchema object
* @throws MalformedURLException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws ClassCastException
*/
public ApplicationSchema readSchema() throws MalformedURLException,
ClassCastException, ClassNotFoundException, InstantiationException,
IllegalAccessException {
LOG.info("Parsing the underlying schema at " + this.schemaUrl); //$NON-NLS-1$
// Convert the schema location to the URL format
String schemaURL = new URL(this.schemaUrl).toString();
// Create the schema-decoder
ApplicationSchemaXSDDecoder decoder = new ApplicationSchemaXSDDecoder(
this.gmlVersion, null, schemaURL);
// Read in the schema and return the ApplicationSchema
ApplicationSchema gmlSchema = decoder.extractFeatureTypeSchema();
if (gmlSchema != null) {
LOG.info("Schema loaded successfully"); //$NON-NLS-1$
} else {
LOG.error("Schema is NULL"); //$NON-NLS-1$
}
return gmlSchema;
}
/**
* Reads deegree3 based FeatureCollection from the gml-instance.
*
* @return Feature Collection.
* @throws IOException
* @throws FactoryConfigurationError
* @throws XMLStreamException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws ClassCastException
* @throws UnknownCRSException
* @throws XMLParsingException
* @throws Exception
*/
public FeatureCollection readFC() throws XMLStreamException,
FactoryConfigurationError, IOException, ClassCastException,
ClassNotFoundException, InstantiationException,
IllegalAccessException, XMLParsingException, UnknownCRSException {
LOG.info("Reading the gml instance at " + this.gmlUrl); //$NON-NLS-1$
// Converts gml location to the URL format
URL url = new URL(this.gmlUrl);
// Creates reader to parse gml
GMLStreamReader gmlStreamReader = GMLInputFactory
.createGMLStreamReader(this.gmlVersion, url);
// Sets application schema
gmlStreamReader.setApplicationSchema(readSchema());
FeatureCollection fc = (FeatureCollection) gmlStreamReader
.readFeature();
// resolves local references
gmlStreamReader.getIdContext().resolveLocalRefs();
return fc;
}
/**
* Encodes a deegree3-based Feature/FeatureCollection instance.
*
* @param fc
* - FeatureCollection to be encoded.
* @param defaultNamespace the default namespace
* @param prefixes namespaces mapped to prefixes, may be <code>null</code>
* @throws XMLStreamException
* @throws FileNotFoundException
* @throws TransformationException
* @throws UnknownCRSException
*
*/
public void writeFC(FeatureCollection fc, String defaultNamespace,
Map<String, String> prefixes) throws FileNotFoundException,
XMLStreamException, UnknownCRSException, TransformationException {
LOG.info("Exporting the gml-instance to the location " //$NON-NLS-1$
+ this.targetGmlUrl);
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// will set namespaces if these not set explicitly
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", //$NON-NLS-1$
new Boolean(true));
// create XML File Stream Writer
+ FileOutputStream fos = new FileOutputStream(new File(this.targetGmlUrl));
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(
- new FileOutputStream(new File(this.targetGmlUrl)), "UTF-8"); //$NON-NLS-1$
+ fos, "UTF-8"); //$NON-NLS-1$
// SchemaLocationXMLStreamWriter writer = new SchemaLocationXMLStreamWriter(
// xmlStreamWriter, this.schemaUrl);
// set namespaces, this should be done explicitly
// TODO define a nicer way to set the default namespace
// writer.setDefaultNamespace(defaultNamespace);
// read the namespaces from the map containing namespaces
if (prefixes != null) {
for (Entry<String, String> entry : prefixes.entrySet()) {
writer.setPrefix(entry.getValue(), entry.getKey());
}
}
// create exporter to export files
GMLStreamWriter exporter = createWriter(
GMLVersion.GML_32, new IndentingXMLStreamWriter(writer));
try {
exporter.write(fc);
writer.flush();
} finally {
exporter.close();
+ writer.close();
+ try {
+ fos.close();
+ } catch (IOException e) {
+ LOG.error("Could not close stream.", e);
+ }
}
LOG.debug("Gml instance has been exported successfully "); //$NON-NLS-1$
}
private GMLStreamWriter createWriter(GMLVersion version,
XMLStreamWriter writer) throws XMLStreamException {
// return GMLOutputFactory.createGMLStreamWriter(version, writer);
return new GMLStreamWriter(version, writer);
}
/**
* Converts from the Humboldt version to the deegree3 version
*
* @param gmlVersion
* @return deegree3-based version
*/
private GMLVersion getGMLVersion(GMLVersions gmlVersion) {
GMLVersion version = null;
if (gmlVersion.equals(GMLVersions.gml2)) {
version = GMLVersion.GML_2;
} else if (gmlVersion.equals(GMLVersions.gml3_0)) {
version = GMLVersion.GML_30;
} else if (gmlVersion.equals(GMLVersions.gml3_1)) {
version = GMLVersion.GML_31;
} else if (gmlVersion.equals(GMLVersions.gml3_2_1)) {
version = GMLVersion.GML_32;
}
return version;
}
/**
* @return the schemaUrl
*/
public String getSchemaUrl() {
return schemaUrl;
}
/**
* @param schemaUrl
* the schemaUrl to set
*/
public void setSchemaUrl(String schemaUrl) {
this.schemaUrl = schemaUrl;
}
/**
* @return the gmlUrl
*/
public String getGmlUrl() {
return gmlUrl;
}
/**
* @param gmlUrl
* the gmlUrl to set
*/
public void setGmlUrl(String gmlUrl) {
this.gmlUrl = gmlUrl;
}
/**
* @return the targetGmlUrl
*/
public String getTargetGmlUrl() {
return targetGmlUrl;
}
/**
* @param targetGmlUrl
* the targetGmlUrl to set
*/
public void setTargetGmlUrl(String targetGmlUrl) {
this.targetGmlUrl = targetGmlUrl;
}
/**
* Write Geotools features to the GML file
*
* @param features the features to write
* @param types the type definitions
* @param defaultNamespace the default namespace
* @param prefixes namespaces mapped to prefixes, may be <code>null</code>
* @throws TransformationException
* @throws UnknownCRSException
* @throws XMLStreamException
* @throws FileNotFoundException
*/
public void writeFC(
org.geotools.feature.FeatureCollection<FeatureType, Feature> features,
TypeIndex types, String defaultNamespace, Map<String, String> prefixes) throws FileNotFoundException, XMLStreamException, UnknownCRSException, TransformationException {
GtToDgConvertor converter = new GtToDgConvertor(types);
FeatureCollection fc = converter.convertGtToDg(features);
writeFC(fc, defaultNamespace, prefixes);
}
}
| false | true | public void writeFC(FeatureCollection fc, String defaultNamespace,
Map<String, String> prefixes) throws FileNotFoundException,
XMLStreamException, UnknownCRSException, TransformationException {
LOG.info("Exporting the gml-instance to the location " //$NON-NLS-1$
+ this.targetGmlUrl);
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// will set namespaces if these not set explicitly
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", //$NON-NLS-1$
new Boolean(true));
// create XML File Stream Writer
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(
new FileOutputStream(new File(this.targetGmlUrl)), "UTF-8"); //$NON-NLS-1$
// SchemaLocationXMLStreamWriter writer = new SchemaLocationXMLStreamWriter(
// xmlStreamWriter, this.schemaUrl);
// set namespaces, this should be done explicitly
// TODO define a nicer way to set the default namespace
// writer.setDefaultNamespace(defaultNamespace);
// read the namespaces from the map containing namespaces
if (prefixes != null) {
for (Entry<String, String> entry : prefixes.entrySet()) {
writer.setPrefix(entry.getValue(), entry.getKey());
}
}
// create exporter to export files
GMLStreamWriter exporter = createWriter(
GMLVersion.GML_32, new IndentingXMLStreamWriter(writer));
try {
exporter.write(fc);
writer.flush();
} finally {
exporter.close();
}
LOG.debug("Gml instance has been exported successfully "); //$NON-NLS-1$
}
| public void writeFC(FeatureCollection fc, String defaultNamespace,
Map<String, String> prefixes) throws FileNotFoundException,
XMLStreamException, UnknownCRSException, TransformationException {
LOG.info("Exporting the gml-instance to the location " //$NON-NLS-1$
+ this.targetGmlUrl);
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// will set namespaces if these not set explicitly
outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", //$NON-NLS-1$
new Boolean(true));
// create XML File Stream Writer
FileOutputStream fos = new FileOutputStream(new File(this.targetGmlUrl));
XMLStreamWriter writer = outputFactory.createXMLStreamWriter(
fos, "UTF-8"); //$NON-NLS-1$
// SchemaLocationXMLStreamWriter writer = new SchemaLocationXMLStreamWriter(
// xmlStreamWriter, this.schemaUrl);
// set namespaces, this should be done explicitly
// TODO define a nicer way to set the default namespace
// writer.setDefaultNamespace(defaultNamespace);
// read the namespaces from the map containing namespaces
if (prefixes != null) {
for (Entry<String, String> entry : prefixes.entrySet()) {
writer.setPrefix(entry.getValue(), entry.getKey());
}
}
// create exporter to export files
GMLStreamWriter exporter = createWriter(
GMLVersion.GML_32, new IndentingXMLStreamWriter(writer));
try {
exporter.write(fc);
writer.flush();
} finally {
exporter.close();
writer.close();
try {
fos.close();
} catch (IOException e) {
LOG.error("Could not close stream.", e);
}
}
LOG.debug("Gml instance has been exported successfully "); //$NON-NLS-1$
}
|
diff --git a/libraries/javalib/java/util/Properties.java b/libraries/javalib/java/util/Properties.java
index 59d890bb2..0a3a72b0a 100644
--- a/libraries/javalib/java/util/Properties.java
+++ b/libraries/javalib/java/util/Properties.java
@@ -1,346 +1,346 @@
/*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.PushbackInputStream;
import java.io.Writer;
import java.lang.String;
import java.lang.System;
public class Properties extends Hashtable {
private static final long serialVersionUID = 4112578634029874840L;
protected Properties defaults;
private StringBuffer key, value;
public Properties() {
this(null);
}
public Properties(Properties defaults) {
this.defaults=defaults;
}
private static String escape(String str, boolean isKey) {
StringBuffer sb = new StringBuffer();
for (int pos = 0; pos < str.length(); pos++) {
char ch = str.charAt(pos);
switch (ch) {
case '!':
case '#':
if (pos == 0)
sb.append("\\");
sb.append(ch);
break;
case ':':
case '=':
case ' ':
if (!isKey) {
sb.append(ch);
break;
} // fall through
case '\\':
sb.append("\\" + ch);
break;
case '\n':
sb.append("\\n");
break;
case '\t':
sb.append("\\t");
break;
case '\r':
sb.append("\\r");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
sb.append("\\u");
sb.append(Character.forDigit((ch >> 12) & 0xf, 16));
sb.append(Character.forDigit((ch >> 8) & 0xf, 16));
sb.append(Character.forDigit((ch >> 4) & 0xf, 16));
sb.append(Character.forDigit(ch & 0xf, 16));
} else
sb.append(ch);
break;
}
}
return sb.toString();
}
public String getProperty(String key) {
// Apparently we should use the superclass get method rather than
// our own because it may be overridden
// Software: HotJava
// if (System.out != null) System.out.println("getProperty: " + key);
Object propSearch = super.get(key);
if (propSearch != null) {
return ((String)propSearch);
}
else if (defaults != null) {
return (defaults.getProperty(key));
}
else {
return (null);
}
}
public String getProperty(String key, String defaultValue) {
String result=getProperty(key);
if (result==null) return defaultValue; else return result;
}
public Object setProperty(String key, String value) {
return super.put(key, value);
}
public void list(PrintStream out) {
list(new PrintWriter(out, true));
}
public void list(PrintWriter out) {
try {
save(out, "Properties list");
} catch (IOException _) {
System.err.println("unable to list properties");
}
}
public Enumeration propertyNames() {
SortedSet nameSet = new TreeSet(); // sort keys just for fun
// Add main properties
for (Enumeration e = keys(); e.hasMoreElements(); ) {
nameSet.add(e.nextElement());
}
// Add non-overridden default properties
if (defaults != null) {
for (Enumeration e = defaults.keys(); e.hasMoreElements(); ) {
Object def = e.nextElement();
if (!nameSet.contains(def))
nameSet.add(def);
}
}
// Return enumeration of vector
return Collections.enumeration(nameSet);
}
public synchronized void load(InputStream in) throws IOException {
PushbackInputStream pin = new PushbackInputStream(in, 16);
while (readKeyAndValue(pin)) {
put(key.toString(), value.toString());
}
key = null;
value = null;
//pin.close(); ??
}
private boolean readKeyAndValue(PushbackInputStream in) throws IOException {
int ch;
while (true) {
// Eat initial white space
while ((ch = in.read()) != -1 && ch <= ' ');
// Skip comments
switch (ch) {
case '#':
case '!':
- while ((ch = in.read()) != '\n');
+ while ((ch = in.read()) != -1 && ch != '\n');
continue;
case -1:
return false;
}
// Initialize
this.key = new StringBuffer();
this.value = new StringBuffer();
// Read in key
boolean eatSeparator = false;
getKey: while (true) {
switch (ch) {
case '=':
case ':':
break getKey;
case '\r':
switch ((ch = in.read())) {
case '\n':
break;
case -1:
return true;
default:
in.unread(ch);
break getKey;
} // fall through
case -1:
case '\n':
return true;
default:
if (ch <= ' ') {
eatSeparator = true;
break getKey;
}
in.unread(ch);
key.append((char) getEscapedChar(in));
}
ch = in.read();
}
// Eat white space (and separator, if expecting) before value
while (true) {
while ((ch = in.read()) <= ' ') {
if (ch == -1 || ch == '\n')
return true;
}
if (eatSeparator && (ch == '=' || ch == ':')) {
eatSeparator = false;
} else {
break;
}
}
// Read in value
while (true) {
switch (ch) {
case '\r':
switch ((ch = in.read())) {
case -1:
value.append('\r'); // fall through
case '\n':
return true;
default:
in.unread(ch);
value.append('\r');
break;
}
break;
case -1:
case '\n':
return true;
default:
in.unread(ch);
value.append((char) getEscapedChar(in));
break;
}
ch = in.read();
}
}
}
// Get next char, respecting backslash escape codes and end-of-line stuff
private static int getEscapedChar(PushbackInputStream in) throws IOException {
int ch;
switch ((ch = in.read())) {
case '\\':
switch ((ch = in.read())) {
case '\r':
switch ((ch = in.read())) {
default:
in.unread(ch); // fall through
case -1:
in.unread('\r');
return '\\';
case '\n':
break;
} // fall through
case '\n': // line continuation
while ((ch = in.read()) != -1 && ch <= ' ');
in.unread(ch);
return getEscapedChar(in);
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'u':
{
int[] dig = new int[4];
int n;
getUnicode:
{
int dval, cval = 0;
for (n = 0; n < 4; ) {
if ((dig[n] = in.read()) == -1)
break getUnicode;
if ((dval = Character.digit(
(char) dig[n++], 16)) == -1)
break getUnicode;
cval = (cval << 4) | dval;
}
return cval;
}
// not unreachable, break getUnicode go here
while (n > 0)
in.unread(dig[--n]);
return 'u';
}
// not fall through, previous switch always return
case -1:
return '\\';
default:
return ch;
}
// not fall through, previous switch always return
case '\r':
switch ((ch = in.read())) {
default:
in.unread(ch); // fall through
case -1:
return '\r';
case '\n':
break;
} // fall through
default:
return ch;
}
}
public synchronized void save(OutputStream out, String header) {
try {
store(out, header);
}
catch (IOException e) {
System.err.println("Unable to save properties: "+header);
}
}
public synchronized void store(OutputStream out, String header) throws IOException {
save(new PrintWriter(out, true), header);
}
// NB: use a PrintWriter here to get platform-specific line separator
private synchronized void save(PrintWriter out, String header) throws IOException {
if (header != null) {
out.println("# " + escape(header, false));
}
Enumeration keys = propertyNames();
while (keys.hasMoreElements()) {
String key=(String)keys.nextElement();
out.println(escape(key, true)
+ "=" + escape(getProperty(key), false));
}
out.flush(); // shouldn't be necessary
}
}
| true | true | private boolean readKeyAndValue(PushbackInputStream in) throws IOException {
int ch;
while (true) {
// Eat initial white space
while ((ch = in.read()) != -1 && ch <= ' ');
// Skip comments
switch (ch) {
case '#':
case '!':
while ((ch = in.read()) != '\n');
continue;
case -1:
return false;
}
// Initialize
this.key = new StringBuffer();
this.value = new StringBuffer();
// Read in key
boolean eatSeparator = false;
getKey: while (true) {
switch (ch) {
case '=':
case ':':
break getKey;
case '\r':
switch ((ch = in.read())) {
case '\n':
break;
case -1:
return true;
default:
in.unread(ch);
break getKey;
} // fall through
case -1:
case '\n':
return true;
default:
if (ch <= ' ') {
eatSeparator = true;
break getKey;
}
in.unread(ch);
key.append((char) getEscapedChar(in));
}
ch = in.read();
}
// Eat white space (and separator, if expecting) before value
while (true) {
while ((ch = in.read()) <= ' ') {
if (ch == -1 || ch == '\n')
return true;
}
if (eatSeparator && (ch == '=' || ch == ':')) {
eatSeparator = false;
} else {
break;
}
}
// Read in value
while (true) {
switch (ch) {
case '\r':
switch ((ch = in.read())) {
case -1:
value.append('\r'); // fall through
case '\n':
return true;
default:
in.unread(ch);
value.append('\r');
break;
}
break;
case -1:
case '\n':
return true;
default:
in.unread(ch);
value.append((char) getEscapedChar(in));
break;
}
ch = in.read();
}
}
}
| private boolean readKeyAndValue(PushbackInputStream in) throws IOException {
int ch;
while (true) {
// Eat initial white space
while ((ch = in.read()) != -1 && ch <= ' ');
// Skip comments
switch (ch) {
case '#':
case '!':
while ((ch = in.read()) != -1 && ch != '\n');
continue;
case -1:
return false;
}
// Initialize
this.key = new StringBuffer();
this.value = new StringBuffer();
// Read in key
boolean eatSeparator = false;
getKey: while (true) {
switch (ch) {
case '=':
case ':':
break getKey;
case '\r':
switch ((ch = in.read())) {
case '\n':
break;
case -1:
return true;
default:
in.unread(ch);
break getKey;
} // fall through
case -1:
case '\n':
return true;
default:
if (ch <= ' ') {
eatSeparator = true;
break getKey;
}
in.unread(ch);
key.append((char) getEscapedChar(in));
}
ch = in.read();
}
// Eat white space (and separator, if expecting) before value
while (true) {
while ((ch = in.read()) <= ' ') {
if (ch == -1 || ch == '\n')
return true;
}
if (eatSeparator && (ch == '=' || ch == ':')) {
eatSeparator = false;
} else {
break;
}
}
// Read in value
while (true) {
switch (ch) {
case '\r':
switch ((ch = in.read())) {
case -1:
value.append('\r'); // fall through
case '\n':
return true;
default:
in.unread(ch);
value.append('\r');
break;
}
break;
case -1:
case '\n':
return true;
default:
in.unread(ch);
value.append((char) getEscapedChar(in));
break;
}
ch = in.read();
}
}
}
|
diff --git a/src/edu/worcester/cs499summer2012/activity/MainActivity.java b/src/edu/worcester/cs499summer2012/activity/MainActivity.java
index 26ef712..70699d4 100644
--- a/src/edu/worcester/cs499summer2012/activity/MainActivity.java
+++ b/src/edu/worcester/cs499summer2012/activity/MainActivity.java
@@ -1,324 +1,324 @@
/*
* MainActivity.java
*
* Copyright 2012 Jonathan Hasenzahl, James Celona
*
* 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 edu.worcester.cs499summer2012.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import edu.worcester.cs499summer2012.R;
import edu.worcester.cs499summer2012.adapter.TaskListAdapter;
import edu.worcester.cs499summer2012.database.TasksDataSource;
import edu.worcester.cs499summer2012.service.TaskAlarm;
import edu.worcester.cs499summer2012.task.Task;
/**
* Main app activity. Displays current task list and allows user to access
* task creation, task modification, and task sorting activities.
* @author Jonathan Hasenzahl
* @author James Celona
*/
public class MainActivity extends SherlockListActivity implements OnItemLongClickListener,
ActionMode.Callback {
/**************************************************************************
* Static fields and methods *
**************************************************************************/
public static final String PREF_SORT_TYPE = "sort_type";
public static final int ADD_TASK_REQUEST = 0;
public static final int VIEW_TASK_REQUEST = 1;
public static final int DELETE_MODE_SINGLE = 0;
public static final int DELETE_MODE_FINISHED = 1;
public static final int DELETE_MODE_ALL = 2;
/**************************************************************************
* Private fields *
**************************************************************************/
private TasksDataSource data_source;
private SharedPreferences prefs;
private SharedPreferences.Editor prefs_editor;
private TaskListAdapter adapter;
private Object action_mode;
private int selected_task;
/**************************************************************************
* Class methods *
**************************************************************************/
/**
* Displays a message in a Toast notification for a short duration.
*/
private void toast(String message)
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void deleteAlert(String question, final int mode)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(question)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int deleted_tasks;
switch (mode) {
case DELETE_MODE_SINGLE:
data_source.deleteTask(adapter.getItem(selected_task));
adapter.remove(adapter.getItem(selected_task));
toast("Task deleted");
break;
case DELETE_MODE_FINISHED:
deleted_tasks = data_source.deleteFinishedTasks();
for (int i = 0; i < adapter.getCount(); i++)
{
if (adapter.getItem(i).isCompleted())
{
adapter.remove(adapter.getItem(i));
i--;
}
}
toast(deleted_tasks + " tasks deleted");
break;
case DELETE_MODE_ALL:
deleted_tasks = data_source.deleteAllTasks();
adapter.clear();
toast(deleted_tasks + " tasks deleted");
break;
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**************************************************************************
* Overridden parent methods *
**************************************************************************/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Assign the layout to this activity
setContentView(R.layout.activity_main);
// Open the database
data_source = TasksDataSource.getInstance(getApplicationContext());
//data_source.open();
// Create an adapter for the task list
adapter = new TaskListAdapter(this, data_source.getAllTasks());
setListAdapter(adapter);
// Read preferences from file
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs_editor = prefs.edit();
// Set sort type and sort the list
adapter.setSortType(prefs.getInt(PREF_SORT_TYPE,
TaskListAdapter.AUTO_SORT));
adapter.sort();
// Set up a long item click listener
getListView().setOnItemLongClickListener(this);
}
@Override
public void onStop() {
// Save preferences to file
prefs_editor.commit();
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_main_add_task:
startActivityForResult(new Intent(this, AddTaskActivity.class),
ADD_TASK_REQUEST);
return true;
case R.id.menu_main_sort:
SubMenu sort_menu = item.getSubMenu();
sort_menu.getItem(adapter.getSortType()).setChecked(true);
return true;
case R.id.menu_main_auto_sort:
adapter.setSortType(TaskListAdapter.AUTO_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.AUTO_SORT);
adapter.sort();
return true;
case R.id.menu_main_custom_sort:
adapter.setSortType(TaskListAdapter.CUSTOM_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.CUSTOM_SORT);
return true;
case R.id.menu_delete_finished:
deleteAlert("Are you sure you want to delete all completed tasks? This cannot be undone.",
DELETE_MODE_FINISHED);
return true;
case R.id.menu_delete_all:
deleteAlert("Are you sure you want to delete all tasks? This cannot be undone.",
DELETE_MODE_ALL);
return true;
case R.id.menu_main_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
- case R.id.menu_main_help:
- toast("Help coming soon!");
+ case R.id.menu_main_about:
+ toast("Coming soon!");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onListItemClick(ListView list_view, View view, int position,
long id) {
/*adapter.getItem(position).toggleIsCompleted();
adapter.getItem(position).setDateModified(GregorianCalendar.getInstance().getTimeInMillis());
// Update database
data_source.updateTask(adapter.getItem(position));
// Sort the list
adapter.sort();*/
Intent intent = new Intent(this, ViewTaskActivity.class);
intent.putExtra(Task.EXTRA_TASK_ID, adapter.getItem(position).getID());
startActivityForResult(intent, VIEW_TASK_REQUEST);
}
@Override
public void onActivityResult(int request_code, int result_code,
Intent intent) {
if ((request_code == ADD_TASK_REQUEST || request_code == VIEW_TASK_REQUEST)
&& result_code == RESULT_OK) {
// Get the task from the db using the ID in the intent
Task task = data_source.getTask(intent.getIntExtra(Task.EXTRA_TASK_ID, 0));
// Update the adapter
if (request_code == VIEW_TASK_REQUEST)
adapter.remove(task);
adapter.add(task);
adapter.sort();
if (task.hasDateDue() && !task.isCompleted()) {
TaskAlarm alarm = new TaskAlarm();
alarm.setOnetimeAlarm(this, task.getID());
}
}
}
/**************************************************************************
* Methods implementing OnItemLongClickListener interface *
**************************************************************************/
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (action_mode != null)
return false;
selected_task = position;
action_mode = startActionMode(this);
view.setSelected(true);
return true;
}
/**************************************************************************
* Methods implementing ActionMode.Callback interface *
**************************************************************************/
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_modify_task, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Return false if nothing is done
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_main_edit_task:
toast("Coming soon!");
mode.finish();
return true;
case R.id.menu_main_delete_task:
deleteAlert("Are you sure you want to delete this task?",
DELETE_MODE_SINGLE);
mode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
action_mode = null;
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_main_add_task:
startActivityForResult(new Intent(this, AddTaskActivity.class),
ADD_TASK_REQUEST);
return true;
case R.id.menu_main_sort:
SubMenu sort_menu = item.getSubMenu();
sort_menu.getItem(adapter.getSortType()).setChecked(true);
return true;
case R.id.menu_main_auto_sort:
adapter.setSortType(TaskListAdapter.AUTO_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.AUTO_SORT);
adapter.sort();
return true;
case R.id.menu_main_custom_sort:
adapter.setSortType(TaskListAdapter.CUSTOM_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.CUSTOM_SORT);
return true;
case R.id.menu_delete_finished:
deleteAlert("Are you sure you want to delete all completed tasks? This cannot be undone.",
DELETE_MODE_FINISHED);
return true;
case R.id.menu_delete_all:
deleteAlert("Are you sure you want to delete all tasks? This cannot be undone.",
DELETE_MODE_ALL);
return true;
case R.id.menu_main_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.menu_main_help:
toast("Help coming soon!");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
| public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_main_add_task:
startActivityForResult(new Intent(this, AddTaskActivity.class),
ADD_TASK_REQUEST);
return true;
case R.id.menu_main_sort:
SubMenu sort_menu = item.getSubMenu();
sort_menu.getItem(adapter.getSortType()).setChecked(true);
return true;
case R.id.menu_main_auto_sort:
adapter.setSortType(TaskListAdapter.AUTO_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.AUTO_SORT);
adapter.sort();
return true;
case R.id.menu_main_custom_sort:
adapter.setSortType(TaskListAdapter.CUSTOM_SORT);
prefs_editor.putInt(PREF_SORT_TYPE, TaskListAdapter.CUSTOM_SORT);
return true;
case R.id.menu_delete_finished:
deleteAlert("Are you sure you want to delete all completed tasks? This cannot be undone.",
DELETE_MODE_FINISHED);
return true;
case R.id.menu_delete_all:
deleteAlert("Are you sure you want to delete all tasks? This cannot be undone.",
DELETE_MODE_ALL);
return true;
case R.id.menu_main_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.menu_main_about:
toast("Coming soon!");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
|
diff --git a/src/net/sf/freecol/server/ai/AIMain.java b/src/net/sf/freecol/server/ai/AIMain.java
index d91bfa2aa..d2d0bd5a8 100644
--- a/src/net/sf/freecol/server/ai/AIMain.java
+++ b/src/net/sf/freecol/server/ai/AIMain.java
@@ -1,534 +1,535 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.ai;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.FreeCol;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.FreeColGameObjectListener;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.model.ServerPlayer;
import org.w3c.dom.Element;
/**
* The main AI-class. Keeps references to all other AI-classes.
*/
public class AIMain extends FreeColObject
implements FreeColGameObjectListener {
private static final Logger logger = Logger.getLogger(AIMain.class.getName());
private FreeColServer freeColServer;
private int nextID = 1;
/**
* Contains mappings between <code>FreeColGameObject</code>s
* and <code>AIObject</code>s.
*/
private HashMap<String, AIObject> aiObjects = new HashMap<String, AIObject>();
/**
* Creates a new <code>AIMain</code> and searches the current
* game for <code>FreeColGameObject</code>s.
*
* @param freeColServer The main controller object for the
* server.
* @see #findNewObjects()
*/
public AIMain(FreeColServer freeColServer) {
this.freeColServer = freeColServer;
findNewObjects();
}
/**
* Creates a new <code>AIMain</code> and reads the given element.
*
* @param freeColServer The main controller object for the
* server.
* @param element The <code>Element</code> (in a DOM-parsed XML-tree)
* that describes this object.
* @see #readFromXMLElement
*/
public AIMain(FreeColServer freeColServer, Element element) {
this(freeColServer);
readFromXMLElement(element);
}
/**
* Creates a new <code>AIMain</code> and reads the given element.
*
* @param freeColServer The main controller object for the
* server.
* @param in The input stream containing the XML.
* @throws XMLStreamException if a problem was encountered
* during parsing.
* @see #readFromXML
*/
public AIMain(FreeColServer freeColServer, XMLStreamReader in) throws XMLStreamException {
this(freeColServer);
readFromXML(in);
}
/**
* Gets the main controller object for the server.
* @return The <code>FreeColServer</code>-object.
*/
public FreeColServer getFreeColServer() {
return freeColServer;
}
/**
* Gets a unique ID for identifying an <code>AIObject</code>.
* @return A unique ID.
*/
public String getNextID() {
String id = "am" + Integer.toString(nextID);
nextID++;
return id;
}
/**
* Checks the integrity of this <code>AIMain</code>
* by checking if there are any
* {@link AIObject#isUninitialized() uninitialized objects}.
*
* Detected problems gets written to the log.
*
* @return <code>true</code> if the <code>Game</code> has
* been loaded properly.
*/
public boolean checkIntegrity() {
boolean ok = true;
for (AIObject ao : aiObjects.values()) {
if (ao.isUninitialized()) {
logger.warning("Uninitialized object: " + ao.getId() + " (" + ao.getClass() + ")");
ok = false;
}
}
Iterator<FreeColGameObject> fit = getGame().getFreeColGameObjectIterator();
while (fit.hasNext()) {
FreeColGameObject f = fit.next();
if ((f instanceof Unit
|| f instanceof Colony
|| (f instanceof Player && !((Player)f).isUnknownEnemy()))
&& !aiObjects.containsKey(f.getId())) {
logger.warning("Missing AIObject for: " + f.getId());
ok = false;
}
}
if (ok) {
logger.info("AIMain integrity ok.");
} else {
logger.warning("AIMain integrity test failed.");
}
return ok;
}
/**
* Returns the game.
* @return The <code>Game</code>.
*/
public Game getGame() {
return freeColServer.getGame();
}
/**
* Gets the random number generator to be used in the AI.
*
* @return The AI random number generator.
*/
public Random getAIRandom() {
return freeColServer.getServerRandom();
}
/**
* Searches for new {@link FreeColGameObject FreeColGameObjects}. An AI-object is
* created for each object.
*
* <br><br>
*
* Note: Any existing <code>AIObject</code>s will be overwritten.
* @see #findNewObjects(boolean)
*/
private void findNewObjects() {
findNewObjects(true);
}
/**
* Searches for new {@link FreeColGameObject FreeColGameObjects}. An AI-object is
* created for each new object.
* @param overwrite Determines wether any old <code>AIObject</code>
* should be overwritten or not.
*/
public void findNewObjects(boolean overwrite) {
Iterator<FreeColGameObject> i = freeColServer.getGame().getFreeColGameObjectIterator();
while (i.hasNext()) {
FreeColGameObject fcgo = i.next();
if (overwrite || getAIObject(fcgo) == null) {
setFreeColGameObject(fcgo.getId(), fcgo);
}
}
}
/**
* Gets the <code>AIObject</code> for the given
* <code>FreeColGameObject</code>.
*
* @param fcgo The <code>FreeColGameObject</code> to find
* the <code>AIObject</code> for.
* @see #getAIObject(String)
* @return The <code>AIObject</code>.
*/
public AIObject getAIObject(FreeColGameObject fcgo) {
return getAIObject(fcgo.getId());
}
/**
* Gets the <code>AIObject</code> identified by the given ID.
*
* @param id The ID of the <code>AIObject</code>.
* @see #getAIObject(FreeColGameObject)
* @return The <code>AIObject</code>.
*/
public AIObject getAIObject(String id) {
return aiObjects.get(id);
}
/**
* Gets the AI colony corresponding to a given colony.
*
* @param colony The <code>Colony</code> to look up.
* @return The corresponding AI colony, or null if not found.
*/
public AIColony getAIColony(Colony colony) {
AIObject aio = getAIObject(colony.getId());
return (aio instanceof AIColony) ? (AIColony) aio : null;
}
/**
* Gets the AI player corresponding to a given player.
*
* @param player The <code>Player</code> to look up.
* @return The corresponding AI player, or null if not found.
*/
public AIPlayer getAIPlayer(Player player) {
AIObject aio = getAIObject(player.getId());
return (aio instanceof AIPlayer) ? (AIPlayer) aio : null;
}
/**
* Gets the AI unit corresponding to a given unit.
*
* @param unit The <code>Unit</code> to look up.
* @return The corresponding AI unit, or null if not found.
*/
public AIUnit getAIUnit(Unit unit) {
AIObject aio = getAIObject(unit.getId());
return (aio instanceof AIUnit) ? (AIUnit) aio : null;
}
/**
* Adds a reference to the given <code>AIObject</code>.
*
* @param id The ID of the <code>AIObject</code>.
* @param aiObject The <code>AIObject</code> to store a reference
* for.
* @exception IllegalStateException if an <code>AIObject</code> with
* the same <code>id</code> has already been created.
*/
public void addAIObject(String id, AIObject aiObject) {
if (aiObjects.containsKey(id)) {
throw new IllegalStateException("AIObject already created: " + id);
}
if (aiObject == null) {
throw new NullPointerException("aiObject == null");
}
aiObjects.put(id, aiObject);
}
/**
* Removes a reference to the given <code>AIObject</code>.
*
* @param id The ID of the <code>AIObject</code>.
*/
public void removeAIObject(String id) {
aiObjects.remove(id);
}
/**
* Gets the <code>FreeColGameObject</code> with the given ID.
* This is just a convenience method for:
* {@link Game#getFreeColGameObject}
*
* @param id The ID of the <code>FreeColGameObject</code> to find.
* @return The <code>FreeColGameObject</code>.
*/
public FreeColGameObject getFreeColGameObject(String id) {
return freeColServer.getGame().getFreeColGameObject(id);
}
public void ownerChanged(FreeColGameObject source, Player oldOwner, Player newOwner) {
AIObject ao = getAIObject(source);
if (ao != null) {
ao.dispose();
setFreeColGameObject(source.getId(), source);
}
}
/**
* Creates a new <code>AIObject</code> for a given
* <code>FreeColGameObject</code>. This method gets called
* whenever a new object gets added to the {@link Game}.
*
* @param id The ID of the <code>FreeColGameObject</code> to add.
* @param freeColGameObject The <code>FreeColGameObject</code> to add.
* @see AIObject
* @see FreeColGameObject
* @see FreeColGameObject#getId
*/
public void setFreeColGameObject(String id, FreeColGameObject freeColGameObject) {
if (aiObjects.containsKey(id)) {
return;
}
if (!id.equals(freeColGameObject.getId())) {
throw new IllegalArgumentException("!id.equals(freeColGameObject.getId())");
}
if (freeColGameObject instanceof Unit) {
new AIUnit(this, (Unit) freeColGameObject);
} else if (freeColGameObject instanceof ServerPlayer) {
if (FreeCol.usesExperimentalAI()) {
ServerPlayer p = (ServerPlayer) freeColGameObject;
if (!p.isREF() && !p.isIndian() && p.isEuropean()) {
logger.info("Using experimental ColonialAIPlayer for "+p.getName());
new ColonialAIPlayer(this, p);
} else {
new StandardAIPlayer(this, p);
}
} else {
new StandardAIPlayer(this, (ServerPlayer) freeColGameObject);
}
} else if (freeColGameObject instanceof Colony) {
new AIColony(this, (Colony) freeColGameObject);
}
}
/**
* Removes the <code>AIObject</code> for the given <code>FreeColGameObject</code>.
* @param id The ID of the <code>FreeColGameObject</code>.
*/
public void removeFreeColGameObject(String id) {
AIObject o = getAIObject(id);
if (o != null) {
o.dispose();
}
removeAIObject(id);
}
/**
* Computes how many objects of each class have been created, to
* track memory leaks over time
*/
public HashMap<String, String> getAIStatistics() {
HashMap<String, String> stats = new HashMap<String, String>();
HashMap<String, Long> objStats = new HashMap<String, Long>();
Iterator<AIObject> iter = aiObjects.values().iterator();
while (iter.hasNext()) {
AIObject obj = iter.next();
String className = obj.getClass().getSimpleName();
if (objStats.containsKey(className)) {
Long count = objStats.get(className);
count++;
objStats.put(className, count);
} else {
Long count = new Long(1);
objStats.put(className, count);
}
}
for (String k : objStats.keySet()) {
stats.put(k, Long.toString(objStats.get(k)));
}
return stats;
}
/**
* Writes all of the <code>AIObject</code>s and other AI-related
* information to an XML-stream.
*
* @param out The target stream.
* @throws XMLStreamException if there are any problems writing
* to the stream.
*/
protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException {
super.toXML(out, getXMLElementTagName());
}
/**
* Write the attributes of this object to a stream.
*
* @param out The target stream.
* @throws XMLStreamException if there are any problems writing
* to the stream.
*/
@Override
protected void writeAttributes(XMLStreamWriter out)
throws XMLStreamException {
super.writeAttributes(out);
out.writeAttribute("nextID", Integer.toString(nextID));
}
/**
* Write the children of this object to a stream.
*
* @param out The target stream.
* @throws XMLStreamException if there are any problems writing
* to the stream.
*/
@Override
protected void writeChildren(XMLStreamWriter out)
throws XMLStreamException {
super.writeChildren(out);
Iterator<AIObject> i = aiObjects.values().iterator();
while (i.hasNext()) {
AIObject aio = i.next();
if ((aio instanceof Wish) && !((Wish) aio).shouldBeStored()) {
continue;
}
try {
if (aio.getId() != null) {
aio.toXML(out);
} else {
logger.warning("aio.getId() == null, for: "
+ aio.getClass().getName());
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning(sw.toString());
}
}
}
/**
* Reads all the <code>AIObject</code>s and other AI-related information
* from XML data.
*
* @param in The input stream with the XML.
* @throws XMLStreamException if an error occured during parsing.
*/
protected void readFromXMLImpl(XMLStreamReader in)
throws XMLStreamException {
aiObjects.clear();
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name, got: " + in.getLocalName());
}
final String nextIDStr = in.getAttributeValue(null, "nextID");
if (nextIDStr != null) {
nextID = Integer.parseInt(nextIDStr);
}
String lastTag = "";
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
final String tagName = in.getLocalName();
+ final String oid = in.getAttributeValue(null, ID_ATTRIBUTE);
try {
- final String oid = in.getAttributeValue(null, ID_ATTRIBUTE);
if (oid != null && aiObjects.containsKey(oid)) {
getAIObject(oid).readFromXML(in);
} else if (tagName.equals(AIUnit.getXMLElementTagName())) {
new AIUnit(this, in);
} else if (tagName.equals(AIPlayer.getXMLElementTagName())) {
new StandardAIPlayer(this, in);
} else if (tagName.equals(ColonialAIPlayer.getXMLElementTagName())) {
new ColonialAIPlayer(this, in);
} else if (tagName.equals(AIColony.getXMLElementTagName())) {
new AIColony(this, in);
} else if (tagName.equals(AIGoods.getXMLElementTagName())) {
new AIGoods(this, in);
} else if (tagName.equals(WorkerWish.getXMLElementTagName())) {
new WorkerWish(this, in);
} else if (tagName.equals(GoodsWish.getXMLElementTagName())) {
new GoodsWish(this, in);
} else if (tagName.equals(TileImprovementPlan.getXMLElementTagName())) {
new TileImprovementPlan(this, in);
} else {
- logger.warning("Unkown AI-object read: " + tagName + "(" + lastTag + ")");
+ logger.warning("Unknown AI-object read: " + tagName + "(" + lastTag + ")");
}
lastTag = in.getLocalName();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
- logger.warning("Exception while reading an AIObject: " + sw.toString());
+ logger.warning("Exception while reading an AIObject(" + tagName
+ + ", " + oid + "): " + sw.toString());
while (!in.getLocalName().equals(tagName) && !in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
}
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name (2), got: " + in.getLocalName());
}
// This should not be necessary - but just in case:
findNewObjects(false);
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "aiMain"
*/
public static String getXMLElementTagName() {
return "aiMain";
}
}
| false | true | protected void readFromXMLImpl(XMLStreamReader in)
throws XMLStreamException {
aiObjects.clear();
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name, got: " + in.getLocalName());
}
final String nextIDStr = in.getAttributeValue(null, "nextID");
if (nextIDStr != null) {
nextID = Integer.parseInt(nextIDStr);
}
String lastTag = "";
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
final String tagName = in.getLocalName();
try {
final String oid = in.getAttributeValue(null, ID_ATTRIBUTE);
if (oid != null && aiObjects.containsKey(oid)) {
getAIObject(oid).readFromXML(in);
} else if (tagName.equals(AIUnit.getXMLElementTagName())) {
new AIUnit(this, in);
} else if (tagName.equals(AIPlayer.getXMLElementTagName())) {
new StandardAIPlayer(this, in);
} else if (tagName.equals(ColonialAIPlayer.getXMLElementTagName())) {
new ColonialAIPlayer(this, in);
} else if (tagName.equals(AIColony.getXMLElementTagName())) {
new AIColony(this, in);
} else if (tagName.equals(AIGoods.getXMLElementTagName())) {
new AIGoods(this, in);
} else if (tagName.equals(WorkerWish.getXMLElementTagName())) {
new WorkerWish(this, in);
} else if (tagName.equals(GoodsWish.getXMLElementTagName())) {
new GoodsWish(this, in);
} else if (tagName.equals(TileImprovementPlan.getXMLElementTagName())) {
new TileImprovementPlan(this, in);
} else {
logger.warning("Unkown AI-object read: " + tagName + "(" + lastTag + ")");
}
lastTag = in.getLocalName();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning("Exception while reading an AIObject: " + sw.toString());
while (!in.getLocalName().equals(tagName) && !in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
}
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name (2), got: " + in.getLocalName());
}
// This should not be necessary - but just in case:
findNewObjects(false);
}
| protected void readFromXMLImpl(XMLStreamReader in)
throws XMLStreamException {
aiObjects.clear();
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name, got: " + in.getLocalName());
}
final String nextIDStr = in.getAttributeValue(null, "nextID");
if (nextIDStr != null) {
nextID = Integer.parseInt(nextIDStr);
}
String lastTag = "";
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
final String tagName = in.getLocalName();
final String oid = in.getAttributeValue(null, ID_ATTRIBUTE);
try {
if (oid != null && aiObjects.containsKey(oid)) {
getAIObject(oid).readFromXML(in);
} else if (tagName.equals(AIUnit.getXMLElementTagName())) {
new AIUnit(this, in);
} else if (tagName.equals(AIPlayer.getXMLElementTagName())) {
new StandardAIPlayer(this, in);
} else if (tagName.equals(ColonialAIPlayer.getXMLElementTagName())) {
new ColonialAIPlayer(this, in);
} else if (tagName.equals(AIColony.getXMLElementTagName())) {
new AIColony(this, in);
} else if (tagName.equals(AIGoods.getXMLElementTagName())) {
new AIGoods(this, in);
} else if (tagName.equals(WorkerWish.getXMLElementTagName())) {
new WorkerWish(this, in);
} else if (tagName.equals(GoodsWish.getXMLElementTagName())) {
new GoodsWish(this, in);
} else if (tagName.equals(TileImprovementPlan.getXMLElementTagName())) {
new TileImprovementPlan(this, in);
} else {
logger.warning("Unknown AI-object read: " + tagName + "(" + lastTag + ")");
}
lastTag = in.getLocalName();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.warning("Exception while reading an AIObject(" + tagName
+ ", " + oid + "): " + sw.toString());
while (!in.getLocalName().equals(tagName) && !in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
in.nextTag();
}
}
}
if (!in.getLocalName().equals(getXMLElementTagName())) {
logger.warning("Expected element name (2), got: " + in.getLocalName());
}
// This should not be necessary - but just in case:
findNewObjects(false);
}
|
diff --git a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBTableWidget.java b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBTableWidget.java
index 6776c24e7..e4d656293 100644
--- a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBTableWidget.java
+++ b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBTableWidget.java
@@ -1,612 +1,613 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.fib.view.widget;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SortOrder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.JXTable;
import org.openflexo.antar.binding.AbstractBinding;
import org.openflexo.fib.controller.FIBController;
import org.openflexo.fib.controller.FIBSelectable;
import org.openflexo.fib.controller.FIBTableDynamicModel;
import org.openflexo.fib.model.FIBTable;
import org.openflexo.fib.model.FIBTableAction;
import org.openflexo.fib.view.FIBWidgetView;
import org.openflexo.fib.view.widget.table.FIBTableActionListener;
import org.openflexo.fib.view.widget.table.FIBTableModel;
import org.openflexo.fib.view.widget.table.FIBTableWidgetFooter;
/**
* Widget allowing to display/edit a list of values
*
* @author sguerin
*/
public class FIBTableWidget extends FIBWidgetView<FIBTable, JTable, List<?>> implements TableModelListener, FIBSelectable,
ListSelectionListener {
private static final Logger logger = Logger.getLogger(FIBTableWidget.class.getPackage().getName());
private JXTable _table;
private final JPanel _dynamicComponent;
private final FIBTable _fibTable;
private FIBTableModel _tableModel;
// private ListSelectionModel _listSelectionModel;
private JScrollPane scrollPane;
private FIBTableWidgetFooter footer;
private Vector<Object> selection;
private Object selectedObject;
public FIBTableWidget(FIBTable fibTable, FIBController controller) {
super(fibTable, controller);
_fibTable = fibTable;
_dynamicComponent = new JPanel();
_dynamicComponent.setOpaque(false);
_dynamicComponent.setLayout(new BorderLayout());
footer = new FIBTableWidgetFooter(this);
buildTable();
}
public FIBTable getTable() {
return _fibTable;
}
public FIBTableWidgetFooter getFooter() {
return footer;
}
public FIBTableModel getTableModel() {
if (_tableModel == null) {
_tableModel = new FIBTableModel(_fibTable, this, getController());
}
return _tableModel;
}
/*public JLabel getLabel()
{
if (_label == null) {
_label = new JLabel(_propertyModel.label + " : ", SwingConstants.CENTER);
_label.setText(FlexoLocalization.localizedForKey(_propertyModel.label, _label));
_label.setBackground(InspectorCst.BACK_COLOR);
_label.setFont(DEFAULT_LABEL_FONT);
if (_propertyModel.help != null && !_propertyModel.help.equals(""))
_label.setToolTipText(_propertyModel.help);
}
return _label;
}*/
@Override
public synchronized boolean updateWidgetFromModel() {
List<?> valuesBeforeUpdating = getTableModel().getValues();
Object wasSelected = getSelectedObject();
boolean returned = false;
// logger.info("----------> updateWidgetFromModel() for " + getTable().getName());
if (_fibTable.getEnable().isSet() && _fibTable.getEnable().isValid()) {
Boolean enabledValue = (Boolean) _fibTable.getEnable().getBindingValue(getController());
_table.setEnabled(enabledValue != null && enabledValue);
}
if (notEquals(getValue(), getTableModel().getValues())) {
returned = true;
// boolean debug = false;
// if (getWidget().getName() != null && getWidget().getName().equals("PatternRoleTable")) debug=true;
// if (debug) System.out.println("valuesBeforeUpdating: "+valuesBeforeUpdating);
// if (debug) System.out.println("wasSelected: "+wasSelected);
if (_table.isEditing()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " - Table is currently editing at col:" + _table.getEditingColumn() + " row:"
+ _table.getEditingRow());
}
_table.getCellEditor().cancelCellEditing();
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " - Table is NOT currently edited ");
}
}
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " updateWidgetFromModel() with " + getValue() + " dataObject=" + getDataObject());
}
if (getValue() == null) {
getTableModel().setValues(Collections.emptyList());
}
if (getValue() instanceof List && !getValue().equals(valuesBeforeUpdating)) {
getTableModel().setValues(getValue());
}
footer.setModel(getDataObject());
}
// We restore value if and only if we represent same table
if (equals(getTableModel().getValues(), valuesBeforeUpdating) && wasSelected != null) {
returned = true;
setSelectedObject(wasSelected);
} else if (areSameValuesOrderIndifferent(getTableModel().getValues(), valuesBeforeUpdating)) {
// Same values, only order differs, in this case, still select right object
returned = true;
setSelectedObject(wasSelected);
} else {
if (getComponent().getSelected().isValid() && getComponent().getSelected().getBindingValue(getController()) != null) {
Object newSelectedObject = getComponent().getSelected().getBindingValue(getController());
if (returned = notEquals(newSelectedObject, getSelectedObject())) {
setSelectedObject(newSelectedObject);
}
}
else if (getComponent().getAutoSelectFirstRow()) {
if (getTableModel().getValues() != null && getTableModel().getValues().size() > 0) {
returned = true;
getListSelectionModel().addSelectionInterval(0, 0);
// addToSelection(getTableModel().getValues().get(0));
}
}
}
return returned;
}
public ListSelectionModel getListSelectionModel() {
return _table.getSelectionModel();
}
public void setSelectedObject(Object object/*, boolean notify*/) {
if (getValue() == null) {
return;
}
if (object == getSelectedObject()) {
logger.fine("FIBTableWidget: ignore setSelectedObject");
return;
}
logger.fine("FIBTable: setSelectedObject with object " + object + " current is " + getSelectedObject());
if (object != null) {
int index = getValue().indexOf(object);
if (index > -1) {
index = _table.convertRowIndexToView(index);
// if (!notify) _table.getSelectionModel().removeListSelectionListener(getTableModel());
getListSelectionModel().setSelectionInterval(index, index);
// if (!notify) _table.getSelectionModel().addListSelectionListener(getTableModel());
}
} else {
clearSelection();
}
}
public void clearSelection() {
getListSelectionModel().clearSelection();
}
@Override
public List<AbstractBinding> getDependencyBindings() {
List<AbstractBinding> returned = super.getDependencyBindings();
appendToDependingObjects(getWidget().getSelected(), returned);
return returned;
}
@Override
public synchronized boolean updateModelFromWidget() {
return false;
}
/**
* Implements
*
* @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent)
* @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent)
*/
@Override
public void tableChanged(TableModelEvent e) {
if (e instanceof FIBTableModel.ModelObjectHasChanged) {
FIBTableModel.ModelObjectHasChanged event = (FIBTableModel.ModelObjectHasChanged) e;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Model has changed from " + event.getOldValues() + " to " + event.getNewValues());
}
} else if (e instanceof FIBTableModel.RowMoveForObjectEvent) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Reselect object, and then the edited cell");
}
FIBTableModel.RowMoveForObjectEvent event = (FIBTableModel.RowMoveForObjectEvent) e;
getListSelectionModel().removeListSelectionListener(this);
getListSelectionModel().addSelectionInterval(event.getNewRow(), event.getNewRow());
getListSelectionModel().addListSelectionListener(this);
_table.setEditingColumn(_table.convertColumnIndexToView(event.getColumn()));
_table.setEditingRow(_table.convertRowIndexToView(event.getNewRow()));
}
}
@Override
public JPanel getJComponent() {
return _dynamicComponent;
}
@Override
public JTable getDynamicJComponent() {
return _table;
}
@Override
public FIBTableDynamicModel createDynamicModel() {
return new FIBTableDynamicModel(null);
}
@Override
public FIBTableDynamicModel getDynamicModel() {
return (FIBTableDynamicModel) super.getDynamicModel();
}
@Override
public void updateLanguage() {
super.updateLanguage();
updateTable();
for (FIBTableAction a : getWidget().getActions()) {
if (getWidget().getLocalize()) {
getLocalized(a.getName());
}
}
}
public void updateTable() {
// logger.info("!!!!!!!! updateTable()");
deleteTable();
if (_tableModel != null) {
_tableModel.removeTableModelListener(this);
_tableModel.delete();
_tableModel = null;
}
buildTable();
/*logger.info("!!!!!!!! getDataObject()="+getDataObject());
logger.info("!!!!!!!! getValue()="+getValue());
logger.info("!!!!!!!! getDynamicModel().data="+getDynamicModel().data);
logger.info("!!!!!!!! getComponent().getData()="+getComponent().getData());*/
updateDataObject(getDataObject());
}
@Override
public synchronized void delete() {
// TODO: re-implement this properly and check that all listeners are properly removed.
getFooter().delete();
deleteTable();
getTableModel().removeTableModelListener(this);
super.delete();
}
private void deleteTable() {
if (_table != null) {
_table.removeFocusListener(this);
}
if (getListSelectionModel() != null) {
getListSelectionModel().removeListSelectionListener(this);
}
if (scrollPane != null && _fibTable.getCreateNewRowOnClick()) {
for (MouseListener l : scrollPane.getMouseListeners()) {
scrollPane.removeMouseListener(l);
}
}
for (MouseListener l : _table.getMouseListeners()) {
_table.removeMouseListener(l);
}
}
private void buildTable() {
getTableModel().addTableModelListener(this);
_table = new JXTable(getTableModel()) {
@Override
protected void resetDefaultTableCellRendererColors(Component renderer, int row, int column) {
}
};
+ _table.setVisibleRowCount(0);
_table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
_table.setAutoCreateRowSorter(true);
_table.setFillsViewportHeight(true);
_table.setShowHorizontalLines(false);
_table.setShowVerticalLines(false);
_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
_table.addFocusListener(this);
for (int i = 0; i < getTableModel().getColumnCount(); i++) {
TableColumn col = _table.getColumnModel().getColumn(i);
// FlexoLocalization.localizedForKey(getController().getLocalizer(),getTableModel().columnAt(i).getTitle());
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setPreferredWidth(getTableModel().getDefaultColumnSize(i));
if (getTableModel().getColumnResizable(i)) {
col.setResizable(true);
} else {
// L'idee, c'est d'etre vraiment sur ;-) !
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setMinWidth(getTableModel().getDefaultColumnSize(i));
col.setMaxWidth(getTableModel().getDefaultColumnSize(i));
col.setResizable(false);
}
if (getTableModel().columnAt(i).requireCellRenderer()) {
col.setCellRenderer(getTableModel().columnAt(i).getCellRenderer());
}
if (getTableModel().columnAt(i).requireCellEditor()) {
col.setCellEditor(getTableModel().columnAt(i).getCellEditor());
}
}
if (_fibTable.getRowHeight() != null) {
_table.setRowHeight(_fibTable.getRowHeight());
}
if (getTable().getVisibleRowCount() != null) {
_table.setVisibleRowCount(getTable().getVisibleRowCount());
if (_table.getRowHeight() == 0) {
_table.setRowHeight(18);
}
}
_table.setSelectionMode(_fibTable.getSelectionMode().getMode());
// _table.getTableHeader().setReorderingAllowed(false);
_table.getSelectionModel().addListSelectionListener(this);
// _listSelectionModel = _table.getSelectionModel();
// _listSelectionModel.addListSelectionListener(this);
scrollPane = new JScrollPane(_table);
if (_fibTable.getCreateNewRowOnClick()) {
_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (_table.getCellEditor() != null) {
_table.getCellEditor().stopCellEditing();
e.consume();
}
if (_fibTable.getCreateNewRowOnClick()) {
if (!e.isConsumed() && e.getClickCount() == 2) {
// System.out.println("OK, on essaie de gerer un new par double click");
Enumeration<FIBTableActionListener> en = getFooter().getAddActionListeners();
while (en.hasMoreElements()) {
FIBTableActionListener action = en.nextElement();
if (action.isAddAction()) {
action.actionPerformed(new ActionEvent(_table, ActionEvent.ACTION_PERFORMED, null, EventQueue
.getMostRecentEventTime(), e.getModifiers()));
break;
}
}
}
}
}
});
}
/*_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
getController().fireMouseClicked(getDynamicModel(),e.getClickCount());
}
});*/
_dynamicComponent.removeAll();
_dynamicComponent.add(scrollPane, BorderLayout.CENTER);
if (_fibTable.getShowFooter()) {
_dynamicComponent.add(getFooter(), BorderLayout.SOUTH);
}
_dynamicComponent.revalidate();
_dynamicComponent.repaint();
}
@Override
public boolean synchronizedWithSelection() {
return getWidget().getBoundToSelectionManager();
}
public boolean isLastFocusedSelectable() {
return getController().getLastFocusedSelectable() == this;
}
@Override
public boolean mayRepresent(Object o) {
if (getValue() != null) {
return getValue().contains(o);
}
return false;
}
@Override
public void valueChanged(ListSelectionEvent e) {
// Ignore extra messages.
if (e.getValueIsAdjusting()) {
return;
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("valueChanged() selected index=" + getListSelectionModel().getMinSelectionIndex());
}
int i = getListSelectionModel().getMinSelectionIndex();
int leadIndex = getListSelectionModel().getLeadSelectionIndex();
if (!getListSelectionModel().isSelectedIndex(leadIndex)) {
leadIndex = getListSelectionModel().getAnchorSelectionIndex();
}
while (!getListSelectionModel().isSelectedIndex(leadIndex) && i <= getListSelectionModel().getMaxSelectionIndex()) {
leadIndex = i;
i++;
}
if (leadIndex > -1) {
leadIndex = _table.convertRowIndexToModel(leadIndex);
}
selectedObject = getTableModel().elementAt(leadIndex);
Vector<Object> oldSelection = selection;
selection = new Vector<Object>();
for (i = getListSelectionModel().getMinSelectionIndex(); i <= getListSelectionModel().getMaxSelectionIndex(); i++) {
if (getListSelectionModel().isSelectedIndex(i)) {
selection.add(getTableModel().elementAt(_table.convertRowIndexToModel(i)));
}
}
getDynamicModel().selected = selectedObject;
getDynamicModel().selection = selection;
notifyDynamicModelChanged();
footer.handleSelectionChanged();
if (getComponent().getSelected().isValid()) {
logger.fine("Sets SELECTED binding with " + selectedObject);
getComponent().getSelected().setBindingValue(selectedObject, getController());
}
updateFont();
if (!ignoreNotifications) {
getController().updateSelection(this, oldSelection, selection);
}
/*SwingUtilities.invokeLater(new Runnable() {
public void run()
{
System.out.println((isFocused() ? "LEADER" : "SECONDARY")+" Le grand vainqueur est "+selectedObject);
System.out.println((isFocused() ? "LEADER" : "SECONDARY")+" La selection est "+selection);
}
});*/
}
private boolean ignoreNotifications = false;
@Override
public Object getSelectedObject() {
return selectedObject;
}
@Override
public Vector<Object> getSelection() {
return selection;
}
@Override
public void objectAddedToSelection(Object o) {
int index = getValue().indexOf(o);
if (index > -1) {
ignoreNotifications = true;
index = _table.convertRowIndexToView(index);
getListSelectionModel().addSelectionInterval(index, index);
ignoreNotifications = false;
}
}
@Override
public void objectRemovedFromSelection(Object o) {
int index = getValue().indexOf(o);
if (index > -1) {
ignoreNotifications = true;
index = _table.convertRowIndexToView(index);
getListSelectionModel().removeSelectionInterval(index, index);
ignoreNotifications = false;
}
}
@Override
public void selectionResetted() {
ignoreNotifications = true;
getListSelectionModel().clearSelection();
ignoreNotifications = false;
}
@Override
public void addToSelection(Object o) {
int index = getValue().indexOf(o);
if (index > -1) {
index = _table.convertRowIndexToView(index);
getListSelectionModel().addSelectionInterval(index, index);
}
}
@Override
public void removeFromSelection(Object o) {
int index = getValue().indexOf(o);
if (index > -1) {
index = _table.convertRowIndexToView(index);
getListSelectionModel().removeSelectionInterval(index, index);
}
}
@Override
public void resetSelection() {
getListSelectionModel().clearSelection();
}
private static boolean areSameValuesOrderIndifferent(List<?> l1, List<?> l2) {
if (l1 == null || l2 == null) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
Comparator<Object> comparator = new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return o1.hashCode() - o2.hashCode();
}
};
List<Object> sortedL1 = new ArrayList<Object>(l1);
Collections.sort(sortedL1, comparator);
List<Object> sortedL2 = new ArrayList<Object>(l2);
Collections.sort(sortedL2, comparator);
for (int i = 0; i < sortedL1.size(); i++) {
if (!sortedL1.get(i).equals(sortedL2.get(i))) {
return false;
}
}
return true;
}
}
| true | true | private void buildTable() {
getTableModel().addTableModelListener(this);
_table = new JXTable(getTableModel()) {
@Override
protected void resetDefaultTableCellRendererColors(Component renderer, int row, int column) {
}
};
_table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
_table.setAutoCreateRowSorter(true);
_table.setFillsViewportHeight(true);
_table.setShowHorizontalLines(false);
_table.setShowVerticalLines(false);
_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
_table.addFocusListener(this);
for (int i = 0; i < getTableModel().getColumnCount(); i++) {
TableColumn col = _table.getColumnModel().getColumn(i);
// FlexoLocalization.localizedForKey(getController().getLocalizer(),getTableModel().columnAt(i).getTitle());
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setPreferredWidth(getTableModel().getDefaultColumnSize(i));
if (getTableModel().getColumnResizable(i)) {
col.setResizable(true);
} else {
// L'idee, c'est d'etre vraiment sur ;-) !
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setMinWidth(getTableModel().getDefaultColumnSize(i));
col.setMaxWidth(getTableModel().getDefaultColumnSize(i));
col.setResizable(false);
}
if (getTableModel().columnAt(i).requireCellRenderer()) {
col.setCellRenderer(getTableModel().columnAt(i).getCellRenderer());
}
if (getTableModel().columnAt(i).requireCellEditor()) {
col.setCellEditor(getTableModel().columnAt(i).getCellEditor());
}
}
if (_fibTable.getRowHeight() != null) {
_table.setRowHeight(_fibTable.getRowHeight());
}
if (getTable().getVisibleRowCount() != null) {
_table.setVisibleRowCount(getTable().getVisibleRowCount());
if (_table.getRowHeight() == 0) {
_table.setRowHeight(18);
}
}
_table.setSelectionMode(_fibTable.getSelectionMode().getMode());
// _table.getTableHeader().setReorderingAllowed(false);
_table.getSelectionModel().addListSelectionListener(this);
// _listSelectionModel = _table.getSelectionModel();
// _listSelectionModel.addListSelectionListener(this);
scrollPane = new JScrollPane(_table);
if (_fibTable.getCreateNewRowOnClick()) {
_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (_table.getCellEditor() != null) {
_table.getCellEditor().stopCellEditing();
e.consume();
}
if (_fibTable.getCreateNewRowOnClick()) {
if (!e.isConsumed() && e.getClickCount() == 2) {
// System.out.println("OK, on essaie de gerer un new par double click");
Enumeration<FIBTableActionListener> en = getFooter().getAddActionListeners();
while (en.hasMoreElements()) {
FIBTableActionListener action = en.nextElement();
if (action.isAddAction()) {
action.actionPerformed(new ActionEvent(_table, ActionEvent.ACTION_PERFORMED, null, EventQueue
.getMostRecentEventTime(), e.getModifiers()));
break;
}
}
}
}
}
});
}
/*_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
getController().fireMouseClicked(getDynamicModel(),e.getClickCount());
}
});*/
| private void buildTable() {
getTableModel().addTableModelListener(this);
_table = new JXTable(getTableModel()) {
@Override
protected void resetDefaultTableCellRendererColors(Component renderer, int row, int column) {
}
};
_table.setVisibleRowCount(0);
_table.setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
_table.setAutoCreateRowSorter(true);
_table.setFillsViewportHeight(true);
_table.setShowHorizontalLines(false);
_table.setShowVerticalLines(false);
_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
_table.addFocusListener(this);
for (int i = 0; i < getTableModel().getColumnCount(); i++) {
TableColumn col = _table.getColumnModel().getColumn(i);
// FlexoLocalization.localizedForKey(getController().getLocalizer(),getTableModel().columnAt(i).getTitle());
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setPreferredWidth(getTableModel().getDefaultColumnSize(i));
if (getTableModel().getColumnResizable(i)) {
col.setResizable(true);
} else {
// L'idee, c'est d'etre vraiment sur ;-) !
col.setWidth(getTableModel().getDefaultColumnSize(i));
col.setMinWidth(getTableModel().getDefaultColumnSize(i));
col.setMaxWidth(getTableModel().getDefaultColumnSize(i));
col.setResizable(false);
}
if (getTableModel().columnAt(i).requireCellRenderer()) {
col.setCellRenderer(getTableModel().columnAt(i).getCellRenderer());
}
if (getTableModel().columnAt(i).requireCellEditor()) {
col.setCellEditor(getTableModel().columnAt(i).getCellEditor());
}
}
if (_fibTable.getRowHeight() != null) {
_table.setRowHeight(_fibTable.getRowHeight());
}
if (getTable().getVisibleRowCount() != null) {
_table.setVisibleRowCount(getTable().getVisibleRowCount());
if (_table.getRowHeight() == 0) {
_table.setRowHeight(18);
}
}
_table.setSelectionMode(_fibTable.getSelectionMode().getMode());
// _table.getTableHeader().setReorderingAllowed(false);
_table.getSelectionModel().addListSelectionListener(this);
// _listSelectionModel = _table.getSelectionModel();
// _listSelectionModel.addListSelectionListener(this);
scrollPane = new JScrollPane(_table);
if (_fibTable.getCreateNewRowOnClick()) {
_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (_table.getCellEditor() != null) {
_table.getCellEditor().stopCellEditing();
e.consume();
}
if (_fibTable.getCreateNewRowOnClick()) {
if (!e.isConsumed() && e.getClickCount() == 2) {
// System.out.println("OK, on essaie de gerer un new par double click");
Enumeration<FIBTableActionListener> en = getFooter().getAddActionListeners();
while (en.hasMoreElements()) {
FIBTableActionListener action = en.nextElement();
if (action.isAddAction()) {
action.actionPerformed(new ActionEvent(_table, ActionEvent.ACTION_PERFORMED, null, EventQueue
.getMostRecentEventTime(), e.getModifiers()));
break;
}
}
}
}
}
});
}
/*_table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
getController().fireMouseClicked(getDynamicModel(),e.getClickCount());
}
});*/
|
diff --git a/src/org/csdgn/fxm/Config.java b/src/org/csdgn/fxm/Config.java
index ecffdf6..dc7054f 100644
--- a/src/org/csdgn/fxm/Config.java
+++ b/src/org/csdgn/fxm/Config.java
@@ -1,72 +1,72 @@
/**
* Copyright (c) 2011-2013 Robert Maupin
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
package org.csdgn.fxm;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.UUID;
/**
* @author Chase
*/
public class Config {
public static String FOLDER_DATABASE = null;
public static String FOLDER_USER = null;
public static String FOLDER_CHARACTER = null;
public static String FOLDER_WORLD = null;
public static String FILE_WELCOME = null;
public static UUID START_ROOM_UUID = null;
public static void loadConfiguration() {
Properties properties = new Properties();
try {
properties.load(new FileReader("config.properties"));
} catch(Exception e) {
System.out.println("Warning: Failed to load configuration file, using defaults.");
}
FOLDER_DATABASE = properties.getProperty("folder.db", "db/").trim();
FOLDER_USER = FOLDER_DATABASE
+ properties.getProperty("folder.user", "user/").trim();
FOLDER_CHARACTER = FOLDER_DATABASE
+ properties.getProperty("folder.character", "characters/")
.trim();
FOLDER_WORLD = FOLDER_DATABASE
+ properties.getProperty("folder.world", "world/").trim();
- FOLDER_WORLD = FOLDER_DATABASE
+ FILE_WELCOME = FOLDER_DATABASE
+ properties.getProperty("file.welcome", "welcome").trim();
START_ROOM_UUID = UUID.fromString(properties.getProperty("start.uuid",
"00000000-0000-0000-0000-000000000000").trim());
}
public static void createMissingFolders() {
new File(FOLDER_DATABASE).mkdir();
new File(FOLDER_USER).mkdir();
new File(FOLDER_CHARACTER).mkdir();
new File(FOLDER_WORLD).mkdir();
}
}
| true | true | public static void loadConfiguration() {
Properties properties = new Properties();
try {
properties.load(new FileReader("config.properties"));
} catch(Exception e) {
System.out.println("Warning: Failed to load configuration file, using defaults.");
}
FOLDER_DATABASE = properties.getProperty("folder.db", "db/").trim();
FOLDER_USER = FOLDER_DATABASE
+ properties.getProperty("folder.user", "user/").trim();
FOLDER_CHARACTER = FOLDER_DATABASE
+ properties.getProperty("folder.character", "characters/")
.trim();
FOLDER_WORLD = FOLDER_DATABASE
+ properties.getProperty("folder.world", "world/").trim();
FOLDER_WORLD = FOLDER_DATABASE
+ properties.getProperty("file.welcome", "welcome").trim();
START_ROOM_UUID = UUID.fromString(properties.getProperty("start.uuid",
"00000000-0000-0000-0000-000000000000").trim());
}
| public static void loadConfiguration() {
Properties properties = new Properties();
try {
properties.load(new FileReader("config.properties"));
} catch(Exception e) {
System.out.println("Warning: Failed to load configuration file, using defaults.");
}
FOLDER_DATABASE = properties.getProperty("folder.db", "db/").trim();
FOLDER_USER = FOLDER_DATABASE
+ properties.getProperty("folder.user", "user/").trim();
FOLDER_CHARACTER = FOLDER_DATABASE
+ properties.getProperty("folder.character", "characters/")
.trim();
FOLDER_WORLD = FOLDER_DATABASE
+ properties.getProperty("folder.world", "world/").trim();
FILE_WELCOME = FOLDER_DATABASE
+ properties.getProperty("file.welcome", "welcome").trim();
START_ROOM_UUID = UUID.fromString(properties.getProperty("start.uuid",
"00000000-0000-0000-0000-000000000000").trim());
}
|
diff --git a/src/atoken/tworealities/eu/New_token.java b/src/atoken/tworealities/eu/New_token.java
index c8d9e10..32dec7d 100644
--- a/src/atoken/tworealities/eu/New_token.java
+++ b/src/atoken/tworealities/eu/New_token.java
@@ -1,128 +1,128 @@
package atoken.tworealities.eu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import atoken.tworealities.eu.classes.EventToken;
import atoken.tworealities.eu.classes.TimeToken;
import atoken.tworealities.eu.classes.Token;
import atoken.tworealities.eu.classes.Utils;
public class New_token extends Activity {
private Token token;
private final int SEED_LENGTH=40;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_token);
//filling spinner with token types
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.new_token_text_token_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
((Spinner) findViewById(R.id.token_type)).setAdapter(adapter);
//listener for radio buttons
findViewById(R.id.event_token).setOnClickListener(this.radio_listener);
findViewById(R.id.time_token).setOnClickListener(this.radio_listener);
//listener for create button
findViewById(R.id.button_create).setOnClickListener(this.button_listener);
Bundle extras = getIntent().getExtras();
if (extras != null) { // Edit mode
token = (Token) extras.getSerializable("token");
((EditText) findViewById(R.id.token_name)).setText(token.getName());
((EditText) findViewById(R.id.token_serial)).setText(token.getSerial());
findViewById(R.id.token_type_radiogroup).setVisibility(View.GONE);
findViewById(R.id.token_layout_seed).setVisibility(View.GONE);
((Button) findViewById(R.id.button_create)).setText(getString(R.string.new_token_button_edit));
setTitle(getString(R.string.new_token_edit_title));
}
}
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
switch(v.getId()){
case R.id.event_token:
findViewById(R.id.time_token_details).setVisibility(View.GONE);
break;
case R.id.time_token:
findViewById(R.id.time_token_details).setVisibility(View.VISIBLE);
break;
}
}
};
private OnClickListener button_listener = new OnClickListener() {
public void onClick(View v) {
String name = ((EditText) findViewById(R.id.token_name)).getText().toString();
String serial = ((EditText) findViewById(R.id.token_serial)).getText().toString();
String seed = ((EditText) findViewById(R.id.token_seed)).getText().toString();
//checks
if(name.length()==0){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_empty_name), Toast.LENGTH_SHORT).show();
return;
}
if (token==null){//new token
//checks
if(seed.length()<SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_short_seed), Toast.LENGTH_SHORT).show();
return;
}
if(seed.length()>SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_long_seed), Toast.LENGTH_SHORT).show();
return;
}
if(!Utils.isHex(seed)){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_seed_not_hex), Toast.LENGTH_SHORT).show();
return;
}
if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
token = new TimeToken(name,serial,seed,0);
}
}else
{
token.setName(name);
token.setSerial(serial);
- token.setSeed(seed);
+ //token.setSeed(seed);
}
/*** Probably an idea for change token types **/
/*if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
token = new TimeToken(name,serial,seed,0);
}*/
Intent i = new Intent();
i.putExtra("token", token);
setResult(RESULT_OK,i);
finish();
}
};
}
| true | true | public void onClick(View v) {
String name = ((EditText) findViewById(R.id.token_name)).getText().toString();
String serial = ((EditText) findViewById(R.id.token_serial)).getText().toString();
String seed = ((EditText) findViewById(R.id.token_seed)).getText().toString();
//checks
if(name.length()==0){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_empty_name), Toast.LENGTH_SHORT).show();
return;
}
if (token==null){//new token
//checks
if(seed.length()<SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_short_seed), Toast.LENGTH_SHORT).show();
return;
}
if(seed.length()>SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_long_seed), Toast.LENGTH_SHORT).show();
return;
}
if(!Utils.isHex(seed)){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_seed_not_hex), Toast.LENGTH_SHORT).show();
return;
}
if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
token = new TimeToken(name,serial,seed,0);
}
}else
{
token.setName(name);
token.setSerial(serial);
token.setSeed(seed);
}
/*** Probably an idea for change token types **/
/*if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
| public void onClick(View v) {
String name = ((EditText) findViewById(R.id.token_name)).getText().toString();
String serial = ((EditText) findViewById(R.id.token_serial)).getText().toString();
String seed = ((EditText) findViewById(R.id.token_seed)).getText().toString();
//checks
if(name.length()==0){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_empty_name), Toast.LENGTH_SHORT).show();
return;
}
if (token==null){//new token
//checks
if(seed.length()<SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_short_seed), Toast.LENGTH_SHORT).show();
return;
}
if(seed.length()>SEED_LENGTH){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_long_seed), Toast.LENGTH_SHORT).show();
return;
}
if(!Utils.isHex(seed)){
Toast.makeText(v.getContext(),getString(R.string.new_token_toast_seed_not_hex), Toast.LENGTH_SHORT).show();
return;
}
if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
token = new TimeToken(name,serial,seed,0);
}
}else
{
token.setName(name);
token.setSerial(serial);
//token.setSeed(seed);
}
/*** Probably an idea for change token types **/
/*if(((RadioButton) findViewById(R.id.event_token)).isChecked()){
token = new EventToken(name,serial,seed);
}else{
|
diff --git a/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java b/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
index 8e01724b..a2f8b671 100644
--- a/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
+++ b/databus-audit/src/main/java/com/inmobi/databus/audit/AuditStats.java
@@ -1,169 +1,169 @@
package com.inmobi.databus.audit;
import com.inmobi.databus.audit.services.AuditRollUpService;
import info.ganglia.gmetric4j.gmetric.GMetric;
import info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ganglia.GangliaReporter;
import com.inmobi.databus.Cluster;
import com.inmobi.databus.DatabusConfig;
import com.inmobi.databus.DatabusConfigParser;
import com.inmobi.databus.audit.services.AuditFeederService;
import com.inmobi.databus.audit.util.AuditDBConstants;
import com.inmobi.messaging.ClientConfig;
import com.inmobi.messaging.consumer.databus.MessagingConsumerConfig;
/*
* This class is responsible for launching multiple AuditStatsFeeder instances one per cluster
*/
public class AuditStats {
private static final Log LOG = LogFactory.getLog(AuditStats.class);
public final static MetricRegistry metrics = new MetricRegistry();
final List<AuditDBService> dbServices = new ArrayList<AuditDBService>();
private final ClientConfig config;
private List<DatabusConfig> databusConfigList;
private Map<String, Cluster> clusterMap;
public AuditStats() throws Exception {
config = ClientConfig.loadFromClasspath(AuditDBConstants.FEEDER_CONF_FILE);
config.set(MessagingConsumerConfig.hadoopConfigFileKey,
"audit-core-site.xml");
String databusConfFolder = config.getString(AuditDBConstants
.DATABUS_CONF_FILE_KEY);
loadConfigFiles(databusConfFolder);
createClusterMap();
for (Entry<String, Cluster> cluster : clusterMap.entrySet()) {
String rootDir = cluster.getValue().getRootDir();
AuditDBService feeder = new AuditFeederService(cluster.getKey(), rootDir,
config);
dbServices.add(feeder);
}
AuditDBService rollup = new AuditRollUpService(config);
dbServices.add(rollup);
}
private void createClusterMap() {
clusterMap = new HashMap<String, Cluster>();
for (DatabusConfig dataBusConfig : databusConfigList) {
clusterMap.putAll(dataBusConfig.getClusters());
}
}
private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
LOG.error("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
- e.printStackTrace();
+ LOG.error("Incorrect config in path:"+fullPath, e);
}
}
}
private synchronized void start() throws Exception {
// start all dbServices
for (AuditDBService service : dbServices) {
LOG.info("Starting service: " + service.getServiceName());
service.start();
}
startMetricsReporter(config);
}
private void join() {
for (AuditDBService service : dbServices) {
service.join();
}
}
private void startMetricsReporter(ClientConfig config) {
String gangliaHost = config.getString(AuditDBConstants.GANGLIA_HOST);
int gangliaPort = config.getInteger(AuditDBConstants.GANGLIA_PORT, 8649);
if (gangliaHost != null) {
GMetric ganglia;
try {
ganglia = new GMetric(gangliaHost, gangliaPort,
UDPAddressingMode.MULTICAST, 1);
GangliaReporter gangliaReporter = GangliaReporter.forRegistry(metrics)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS).build(ganglia);
gangliaReporter.start(1, TimeUnit.MINUTES);
} catch (IOException e) {
LOG.error("Cannot start ganglia reporter", e);
}
}
String csvDir = config.getString(AuditDBConstants.CSV_REPORT_DIR, "/tmp");
CsvReporter csvreporter = CsvReporter.forRegistry(metrics)
.formatFor(Locale.US).convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS).build(new File(csvDir));
csvreporter.start(1, TimeUnit.MINUTES);
}
public synchronized void stop() {
try {
LOG.info("Stopping all services...");
for (AuditDBService service : dbServices) {
LOG.info("Stopping service :" + service.getServiceName());
service.stop();
}
LOG.info("All services signalled to stop");
} catch (Exception e) {
LOG.warn("Error in shutting down feeder and rollup services", e);
}
}
public static void main(String args[]) throws Exception {
final AuditStats stats = new AuditStats();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
stats.stop();
stats.join();
LOG.info("Finishing the shutdown hook");
}
});
// TODO check if current table exist else create it.NOTE:This will be done
// in next version
try {
stats.start();
// wait for all dbServices to finish
stats.join();
} finally {
stats.stop();
}
}
}
| true | true | private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
LOG.error("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| private void loadConfigFiles(String databusConfFolder) {
File folder = new File(databusConfFolder);
File[] xmlFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (file.getName().toLowerCase().endsWith(".xml")) {
return true;
}
return false;
}
});
databusConfigList = new ArrayList<DatabusConfig>();
if (xmlFiles.length == 0) {
LOG.error("No xml files found in the conf folder:"+databusConfFolder);
return;
}
LOG.info("Databus xmls included in the conf folder:");
for (File file : xmlFiles) {
String fullPath = file.getAbsolutePath();
LOG.info("File:"+fullPath);
try {
DatabusConfigParser parser = new DatabusConfigParser(fullPath);
databusConfigList.add(parser.getConfig());
} catch (Exception e) {
LOG.error("Incorrect config in path:"+fullPath, e);
}
}
}
|
diff --git a/client/TestPingers.java b/client/TestPingers.java
index f18c646..5cdec73 100644
--- a/client/TestPingers.java
+++ b/client/TestPingers.java
@@ -1,76 +1,76 @@
import java.io.*;
import java.net.*;
/** This class is disposable code to examplify how to use the various
pingers and the expected format
*/
public class TestPingers {
public static void main(String args[]) throws InterruptedException {
if (args.length != 1) {
- System.err.println("Usage: java TestPinger hostname");
+ System.err.println("Usage: java TestPingers hostname");
System.exit(2);
}
// FIXME: get from applet's cookie
ClientInfo this_client = new ClientInfo(ClientInfo.m_cookie_name+"={user=bobafett;uuid=fatalapouet};path=/;expires=eventually");
if (this_client.getNickname() == null)
this_client.setNickname("bobafett");
InetAddress my_local_addr = this_client.getAddress();
InetAddress my_global_addr = null;
try {
my_global_addr = this_client.getExternalAddress();
}
catch (RuntimeException e) {
System.err.println("Warning: could not get external address.");
}
InetAddress target = null;
try {
// Lookup the target's addr
target = InetAddress.getByName(args[0]);
}
catch (UnknownHostException e) {
System.err.println("Error: could not get address for host '" + args[0] + "'.");
System.exit(1);
}
if (target != null) {
System.out.println("\nStarting pings...");
TcpPinger this_tcp_pinger = new TcpPinger(this_client);
IcmpPinger this_pinger = new IcmpPinger(this_client);
TraceRouter this_router = new TraceRouter(this_client);
String text_local_addr = my_local_addr.toString().split("/")[1];
String text_global_addr;
if (my_global_addr != null)
text_global_addr = my_global_addr.toString().split("/")[1];
else
text_global_addr = "<unknown>";
this_pinger.ping(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_pinger.getLastPings());
this_router.trace(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_router.getLastTrace());
this_tcp_pinger.ping(target,50);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_tcp_pinger.getLastPings());
}
//FIXME: save to applet cookie
System.out.println(this_client.getPreferences());
}
}
| true | true | public static void main(String args[]) throws InterruptedException {
if (args.length != 1) {
System.err.println("Usage: java TestPinger hostname");
System.exit(2);
}
// FIXME: get from applet's cookie
ClientInfo this_client = new ClientInfo(ClientInfo.m_cookie_name+"={user=bobafett;uuid=fatalapouet};path=/;expires=eventually");
if (this_client.getNickname() == null)
this_client.setNickname("bobafett");
InetAddress my_local_addr = this_client.getAddress();
InetAddress my_global_addr = null;
try {
my_global_addr = this_client.getExternalAddress();
}
catch (RuntimeException e) {
System.err.println("Warning: could not get external address.");
}
InetAddress target = null;
try {
// Lookup the target's addr
target = InetAddress.getByName(args[0]);
}
catch (UnknownHostException e) {
System.err.println("Error: could not get address for host '" + args[0] + "'.");
System.exit(1);
}
if (target != null) {
System.out.println("\nStarting pings...");
TcpPinger this_tcp_pinger = new TcpPinger(this_client);
IcmpPinger this_pinger = new IcmpPinger(this_client);
TraceRouter this_router = new TraceRouter(this_client);
String text_local_addr = my_local_addr.toString().split("/")[1];
String text_global_addr;
if (my_global_addr != null)
text_global_addr = my_global_addr.toString().split("/")[1];
else
text_global_addr = "<unknown>";
this_pinger.ping(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_pinger.getLastPings());
this_router.trace(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_router.getLastTrace());
this_tcp_pinger.ping(target,50);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_tcp_pinger.getLastPings());
}
//FIXME: save to applet cookie
System.out.println(this_client.getPreferences());
}
| public static void main(String args[]) throws InterruptedException {
if (args.length != 1) {
System.err.println("Usage: java TestPingers hostname");
System.exit(2);
}
// FIXME: get from applet's cookie
ClientInfo this_client = new ClientInfo(ClientInfo.m_cookie_name+"={user=bobafett;uuid=fatalapouet};path=/;expires=eventually");
if (this_client.getNickname() == null)
this_client.setNickname("bobafett");
InetAddress my_local_addr = this_client.getAddress();
InetAddress my_global_addr = null;
try {
my_global_addr = this_client.getExternalAddress();
}
catch (RuntimeException e) {
System.err.println("Warning: could not get external address.");
}
InetAddress target = null;
try {
// Lookup the target's addr
target = InetAddress.getByName(args[0]);
}
catch (UnknownHostException e) {
System.err.println("Error: could not get address for host '" + args[0] + "'.");
System.exit(1);
}
if (target != null) {
System.out.println("\nStarting pings...");
TcpPinger this_tcp_pinger = new TcpPinger(this_client);
IcmpPinger this_pinger = new IcmpPinger(this_client);
TraceRouter this_router = new TraceRouter(this_client);
String text_local_addr = my_local_addr.toString().split("/")[1];
String text_global_addr;
if (my_global_addr != null)
text_global_addr = my_global_addr.toString().split("/")[1];
else
text_global_addr = "<unknown>";
this_pinger.ping(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_pinger.getLastPings());
this_router.trace(target);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_router.getLastTrace());
this_tcp_pinger.ping(target,50);
System.out.println(text_local_addr + " " +
text_global_addr + " " +
this_tcp_pinger.getLastPings());
}
//FIXME: save to applet cookie
System.out.println(this_client.getPreferences());
}
|
diff --git a/jumble/src/com/reeltwo/jumble/fast/JUnitTestResult.java b/jumble/src/com/reeltwo/jumble/fast/JUnitTestResult.java
index 126fe93..8251e1e 100644
--- a/jumble/src/com/reeltwo/jumble/fast/JUnitTestResult.java
+++ b/jumble/src/com/reeltwo/jumble/fast/JUnitTestResult.java
@@ -1,35 +1,35 @@
package com.reeltwo.jumble.fast;
import java.util.Enumeration;
import junit.framework.TestFailure;
import junit.framework.TestResult;
/**
* <code>JUnitTestResult</code> extends the standard
* <code>TestResult</code> class with a decent <code>toString</code>
* method.
*
* @author <a href="mailto:[email protected]">Len Trigg</a>
* @version $Revision$
*/
public class JUnitTestResult extends TestResult {
private static final String LS = System.getProperty("line.separator");
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
- for (final Enumeration<TestFailure> e = errors(); e.hasMoreElements(); ) {
- final TestFailure f = e.nextElement();
+ for (final Enumeration e = errors(); e.hasMoreElements(); ) {
+ final TestFailure f = (TestFailure) e.nextElement();
sb.append("TEST FINISHED WITH ERROR: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
- for (final Enumeration<TestFailure> e = failures(); e.hasMoreElements(); ) {
- final TestFailure f = e.nextElement();
+ for (final Enumeration e = failures(); e.hasMoreElements(); ) {
+ final TestFailure f = (TestFailure) e.nextElement();
sb.append("TEST FINISHED WITH FAILURE: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
return sb.toString();
}
}
| false | true | public String toString() {
final StringBuffer sb = new StringBuffer();
for (final Enumeration<TestFailure> e = errors(); e.hasMoreElements(); ) {
final TestFailure f = e.nextElement();
sb.append("TEST FINISHED WITH ERROR: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
for (final Enumeration<TestFailure> e = failures(); e.hasMoreElements(); ) {
final TestFailure f = e.nextElement();
sb.append("TEST FINISHED WITH FAILURE: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
return sb.toString();
}
| public String toString() {
final StringBuffer sb = new StringBuffer();
for (final Enumeration e = errors(); e.hasMoreElements(); ) {
final TestFailure f = (TestFailure) e.nextElement();
sb.append("TEST FINISHED WITH ERROR: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
for (final Enumeration e = failures(); e.hasMoreElements(); ) {
final TestFailure f = (TestFailure) e.nextElement();
sb.append("TEST FINISHED WITH FAILURE: ").append(f.toString()).append(LS);
sb.append(f.trace());
}
return sb.toString();
}
|
diff --git a/src/org/zaproxy/zap/extension/saml/SAMLMessage.java b/src/org/zaproxy/zap/extension/saml/SAMLMessage.java
index 6be1cce..3535c91 100644
--- a/src/org/zaproxy/zap/extension/saml/SAMLMessage.java
+++ b/src/org/zaproxy/zap/extension/saml/SAMLMessage.java
@@ -1,477 +1,477 @@
package org.zaproxy.zap.extension.saml;
import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
import org.opensaml.common.SAMLVersion;
import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.core.Response;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallerFactory;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class SAMLMessage {
private String originalMessage;
private Map<String, String> attributeMapping;
private String samlParameter;
private XMLObject unmarshalledObject;
public SAMLMessage(String originalMessage, String samlParameter) {
try {
DefaultBootstrap.bootstrap();
this.originalMessage = originalMessage;
this.samlParameter = samlParameter;
} catch (ConfigurationException e) {
}
}
/**
* Reset the message (which might have changed from original one) back to original message
*/
public void resetMessage() {
unmarshalledObject = null;
}
public String getSamlParameter() {
return samlParameter;
}
/**
* Convert the raw saml xml string to a pretty formatted String
*
* @return The Pretty formatted XML String
* @throws SAMLException If XML parsing failed
*/
public String getPrettyFormattedMessage() throws SAMLException {
try {
Source xmlInput;
if (unmarshalledObject != null) {
MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(unmarshalledObject);
Element element = marshaller.marshall(unmarshalledObject);
xmlInput = new DOMSource(element);
} else {
xmlInput = new StreamSource(new StringReader(originalMessage));
}
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 4);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new SAMLException("Formatting XML failed", e);
}
}
/**
* Get the list of attributes that are interested in
*
* @return Map with key as attribute name and value as attribute value
* @throws SAMLException If attribute extraction failed
*/
public Map<String, String> getAttributeMapping() throws SAMLException {
if (attributeMapping == null || attributeMapping.isEmpty()) {
extractAttributes();
}
return attributeMapping;
}
/**
* Extract the attributes from the SAML string using DOM and unmarshaller
*
* @throws SAMLException
*/
private void extractAttributes() throws SAMLException {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = null;
docBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream is = new ByteArrayInputStream(originalMessage.getBytes("UTF-8"));
Document document = docBuilder.parse(is);
Element element = document.getDocumentElement();
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
unmarshalledObject = unmarshaller.unmarshall(element);
attributeMapping = new LinkedHashMap<>();
attributeMapping = new LinkedHashMap<>();
for (String attribute : getSelectedAttributes()) {
String value = getValueOf(attribute);
if (value != null && !"".equals(value)) {
attributeMapping.put(attribute, value);
}
}
} catch (Exception e) {
throw new SAMLException("Error in extracting the attributes", e);
}
}
/**
* Get the user preferred attributes to be shown in the attribute list
* @return Set o
*/
private Set<String> getSelectedAttributes() {
//Hardcoded to show all attributes (if available) for now. will be taken from a config file later
Set<String> result = new HashSet<>();
result.add("AuthnRequest[ID]");
result.add("AuthnRequest[AssertionConsumerServiceURL]");
result.add("AuthnRequest[AttributeConsumingServiceIndex]");
result.add("AuthnRequest[IssueInstant]");
result.add("AuthnRequest[ProtocolBinding]");
result.add("AuthnRequest[Version]");
result.add("AuthnRequest:Issuer");
result.add("AuthnRequest:NameIDPolicy[Format]");
result.add("AuthnRequest:NameIDPolicy[SPNameQualifier]");
result.add("AuthnRequest:NameIDPolicy[AllowCreate]");
result.add("AuthnRequest:RequestedAuthnContext[Comparison]");
result.add("AuthnRequest:RequestedAuthnContext:AuthnContextClassRef");
result.add("Assertion[ID]");
result.add("Assertion[IssueInstant]");
result.add("Assertion[Version]");
result.add("Assertion:Issuer");
result.add("Assertion:Issuer[Format]");
result.add("Assertion:Subject:NameID");
result.add("Assertion:Subject:SubjectConfirmation[Method]");
result.add("Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[InResponseTo]");
result.add("Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[Recipient]");
result.add("Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[NotOnOrAfter]");
result.add("Assertion:Conditions[NotOnOrAfter]");
result.add("Assertion:Conditions[NotBefore]");
result.add("Assertion:Conditions:AudienceRestriction:Audience");
result.add("Assertion:AuthnStatement[AuthnInstant]");
result.add("Assertion:AuthnStatement[SessionIndex]");
result.add("Assertion:AuthnStatement:AuthnContext:AuthnContextClassRef");
return result;
}
/**
* Get the value of a attribute as given by the key
* @param key The attribute name
* @return Value of the attribute as a string, empty string if attribute not set.
*/
public String getValueOf(String key) {
if (unmarshalledObject == null) {
return "";
}
if (key.startsWith("AuthnRequest")) {
return getAuthnRequestValue(key);
} else if(key.startsWith("Assertion")){
return getResponseValue(key);
}
return "";
}
/**
* Set the value of a given attribute to the value specified
* @param key The attribute name to set the value
* @param value The value of the attribute to be set
* @return <code>true</code> if value is succesfully set,<code>false</code> otherwise
* @throws SAMLException if the given value type is not accepted by the key
*/
public boolean setValueTo(String key, String value) throws SAMLException {
if (unmarshalledObject == null) {
return false;
}
if (key.startsWith("AuthnRequest")) {
return setAuthnRequestValue(key, value);
} else if (key.startsWith("Assertion")){
return setResponseValue(key,value);
}
return false;
}
/**
* Get the attribute value of a AUthRequest
* @param key the name of the attribute
* @return the value of the attribute
*/
private String getAuthnRequestValue(String key) {
if (!(unmarshalledObject instanceof AuthnRequest)) {
return "";
}
AuthnRequest authnRequest = (AuthnRequest) unmarshalledObject;
switch (key) {
case "AuthnRequest[ID]":
return authnRequest.getID();
case "AuthnRequest[AssertionConsumerServiceURL]":
return authnRequest.getAssertionConsumerServiceURL();
case "AuthnRequest[AttributeConsumingServiceIndex]":
return String.valueOf(authnRequest.getAttributeConsumingServiceIndex());
case "AuthnRequest[IssueInstant]":
return authnRequest.getIssueInstant().toString();
case "AuthnRequest[ProtocolBinding]":
return authnRequest.getProtocolBinding();
case "AuthnRequest[Version]":
return authnRequest.getVersion().toString();
case "AuthnRequest:Issuer":
return authnRequest.getIssuer().getValue();
case "AuthnRequest:NameIDPolicy[Format]":
return authnRequest.getNameIDPolicy().getFormat();
case "AuthnRequest:NameIDPolicy[SPNameQualifier]":
return authnRequest.getNameIDPolicy().getSPNameQualifier();
case "AuthnRequest:NameIDPolicy[AllowCreate]":
return authnRequest.getNameIDPolicy().getAllowCreate().toString();
case "AuthnRequest:RequestedAuthnContext[Comparison]":
return authnRequest.getRequestedAuthnContext()
.getComparison().toString();
case "AuthnRequest:RequestedAuthnContext:AuthnContextClassRef":
return authnRequest.getRequestedAuthnContext()
.getAuthnContextClassRefs().get(0).getAuthnContextClassRef();
}
return "";
}
/**
* Set the value of the given attribute in a AuthRequest
* @param key The attribute name
* @param value The attribute value
* @return <code>true</code> if the value is set, false if the key is not a valid one
* @throws SAMLException if value type is not accepted by key
*/
private boolean setAuthnRequestValue(String key, String value) throws SAMLException {
if (!(unmarshalledObject instanceof AuthnRequest)) {
return false;
}
AuthnRequest authnRequest = (AuthnRequest) unmarshalledObject;
switch (key) {
case "AuthnRequest[ID]":
authnRequest.setID(value);
return true;
case "AuthnRequest[AssertionConsumerServiceURL]":
authnRequest.setAssertionConsumerServiceURL(value);
return true;
case "AuthnRequest[AttributeConsumingServiceIndex]":
try {
Integer intValue = Integer.parseInt(value);
authnRequest.setAttributeConsumingServiceIndex(intValue);
return true;
} catch (NumberFormatException e) {
throw new SAMLException("Given: " + value + " \nExpected: Integer");
}
case "AuthnRequest[IssueInstant]":
authnRequest.setIssueInstant(DateTime.parse(value));
return true;
case "AuthnRequest[ProtocolBinding]":
authnRequest.setProtocolBinding(value);
return true;
case "AuthnRequest[Version]":
authnRequest.setVersion(SAMLVersion.valueOf(value));
return true;
case "AuthnRequest:Issuer":
authnRequest.getIssuer().setValue(value);
return true;
case "AuthnRequest:NameIDPolicy[Format]":
authnRequest.getNameIDPolicy().setFormat(value);
return true;
case "AuthnRequest:NameIDPolicy[SPNameQualifier]":
authnRequest.getNameIDPolicy().setSPNameQualifier(value);
return true;
case "AuthnRequest:NameIDPolicy[AllowCreate]":
if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
authnRequest.getNameIDPolicy().setAllowCreate(Boolean.valueOf(value));
return true;
} else {
throw new SAMLException("Given Value :" + value + " \nExpected either 'true' or 'false'");
}
case "AuthnRequest:RequestedAuthnContext[Comparison]":
- AuthnContextComparisonTypeEnumeration type = authnRequest.getRequestedAuthnContext().getComparison();
- switch (value) {
+ AuthnContextComparisonTypeEnumeration type;
+ switch (value.toUpperCase()) {
case "EXACT":
type = AuthnContextComparisonTypeEnumeration.EXACT;
break;
case "BETTER":
type = AuthnContextComparisonTypeEnumeration.BETTER;
break;
case "MAXIMUM":
type = AuthnContextComparisonTypeEnumeration.MAXIMUM;
break;
case "MINIMUM":
type = AuthnContextComparisonTypeEnumeration.MINIMUM;
break;
default:
throw new SAMLException("Invalid value. \nGiven:" + value + " \nExpected:One of 'EXACT'," +
"'BETTER','MAXIMUM','MINIMUM'");
}
authnRequest.getRequestedAuthnContext().setComparison(type);
return true;
case "AuthnRequest:RequestedAuthnContext:AuthnContextClassRef":
try {
authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).setAuthnContextClassRef(value);
return true;
} catch (Exception e) {
throw new SAMLException("Invalid value given or value can't be set because of the unavailability " +
"of a dependent elemet");
}
}
return false;
}
/**
* Get the attribute value of a Response
* @param key the name of the attribute
* @return the value of the attribute
*/
private String getResponseValue(String key) {
if (!(unmarshalledObject instanceof Response)) {
return "";
}
Response response = (Response) unmarshalledObject;
try {
switch (key) {
case "Assertion[ID]":
return response.getAssertions().get(0).getID();
case "Assertion[IssueInstant]":
return response.getAssertions().get(0).getIssueInstant().toString();
case "Assertion[Version]":
return response.getAssertions().get(0).getVersion().toString();
case "Assertion:Issuer":
return response.getAssertions().get(0).getIssuer().getValue();
case "Assertion:Issuer[Format]":
return response.getAssertions().get(0).getIssuer().getFormat();
case "Assertion:Subject:NameID":
return response.getAssertions().get(0).getSubject().getNameID().getValue();
case "Assertion:Subject:SubjectConfirmation[Method]":
return response.getAssertions().get(0).getSubject()
.getSubjectConfirmations().get(0).getMethod();
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[InResponseTo]":
return response.getAssertions().get(0).getSubject()
.getSubjectConfirmations().get(0).getSubjectConfirmationData().getInResponseTo();
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[Recipient]":
return response.getAssertions().get(0).getSubject()
.getSubjectConfirmations().get(0).getSubjectConfirmationData().getRecipient();
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[NotOnOrAfter]":
return response.getAssertions().get(0).getSubject()
.getSubjectConfirmations().get(0).getSubjectConfirmationData().getNotOnOrAfter().toString();
case "Assertion:Conditions[NotOnOrAfter]":
return response.getAssertions().get(0).getConditions()
.getNotOnOrAfter().toString();
case "Assertion:Conditions[NotBefore]":
return response.getAssertions().get(0).getConditions()
.getNotBefore().toString();
case "Assertion:Conditions:AudienceRestriction:Audience":
return response.getAssertions().get(0)
.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0).getAudienceURI();
case "Assertion:AuthnStatement[AuthnInstant]":
return response.getAssertions().get(0).getAuthnStatements
().get(0).getAuthnInstant().toString();
case "Assertion:AuthnStatement[SessionIndex]":
return response.getAssertions().get(0).getAuthnStatements
().get(0).getSessionIndex();
case "Assertion:AuthnStatement:AuthnContext:AuthnContextClassRef":
return response.getAssertions().get(0).getAuthnStatements
().get(0).getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef();
}
} catch (Exception e) {
return "";
}
return "";
}
/**
* Set the value of the given attribute in a Response
* @param key The attribute name
* @param value The attribute value
* @return <code>true</code> if the value is set, false if the key is not a valid one
* @throws SAMLException if value type is not accepted by key
*/
private boolean setResponseValue(String key, String value) throws SAMLException {
if (!(unmarshalledObject instanceof AuthnRequest)) {
return false;
}
Response response = (Response) unmarshalledObject;
try {
switch (key) {
case "Assertion[ID]":
response.getAssertions().get(0).setID(value);
return true;
case "Assertion[IssueInstant]":
response.getAssertions().get(0).setIssueInstant(DateTime.parse(value));
return true;
case "Assertion[Version]":
response.getAssertions().get(0).setVersion(SAMLVersion.valueOf(value));
return true;
case "Assertion:Issuer":
response.getAssertions().get(0).getIssuer().setValue(value);
return true;
case "Assertion:Issuer[Format]":
response.getAssertions().get(0).getIssuer().setFormat(value);
return true;
case "Assertion:Subject:NameID":
response.getAssertions().get(0).getSubject().getNameID().setValue(value);
case "Assertion:Subject:SubjectConfirmation[Method]":
response.getAssertions().get(0).getSubject().getSubjectConfirmations().get(0).setMethod(value);
return true;
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[InResponseTo]":
response.getAssertions().get(0).getSubject().getSubjectConfirmations().get(0)
.getSubjectConfirmationData().setInResponseTo(value);
return true;
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[Recipient]":
response.getAssertions().get(0).getSubject().getSubjectConfirmations().get(0)
.getSubjectConfirmationData().setRecipient(value);
return true;
case "Assertion:Subject:SubjectConfirmation:SubjectConfirmationData[NotOnOrAfter]":
response.getAssertions().get(0).getSubject().getSubjectConfirmations().get(0)
.getSubjectConfirmationData().setNotOnOrAfter(DateTime.parse(value));
return true;
case "Assertion:Conditions[NotOnOrAfter]":
response.getAssertions().get(0).getConditions().setNotOnOrAfter(DateTime.parse(value));
return true;
case "Assertion:Conditions[NotBefore]":
response.getAssertions().get(0).getConditions().setNotBefore(DateTime.parse(value));
case "Assertion:Conditions:AudienceRestriction:Audience":
response.getAssertions().get(0).getConditions().getAudienceRestrictions().get(0).getAudiences()
.get(0).setAudienceURI(value);
return true;
case "Assertion:AuthnStatement[AuthnInstant]":
response.getAssertions().get(0).getAuthnStatements().get(0).setAuthnInstant(DateTime.parse(value));
return true;
case "Assertion:AuthnStatement[SessionIndex]":
response.getAssertions().get(0).getAuthnStatements().get(0).setSessionIndex(value);
return true;
case "Assertion:AuthnStatement:AuthnContext:AuthnContextClassRef":
response.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext()
.getAuthnContextClassRef().setAuthnContextClassRef(value);
return true;
}
} catch (Exception e) {
throw new SAMLException("Can't set the value: '"+value+"' to the key: '"+key+"'");
}
return false;
}
}
| true | true | private boolean setAuthnRequestValue(String key, String value) throws SAMLException {
if (!(unmarshalledObject instanceof AuthnRequest)) {
return false;
}
AuthnRequest authnRequest = (AuthnRequest) unmarshalledObject;
switch (key) {
case "AuthnRequest[ID]":
authnRequest.setID(value);
return true;
case "AuthnRequest[AssertionConsumerServiceURL]":
authnRequest.setAssertionConsumerServiceURL(value);
return true;
case "AuthnRequest[AttributeConsumingServiceIndex]":
try {
Integer intValue = Integer.parseInt(value);
authnRequest.setAttributeConsumingServiceIndex(intValue);
return true;
} catch (NumberFormatException e) {
throw new SAMLException("Given: " + value + " \nExpected: Integer");
}
case "AuthnRequest[IssueInstant]":
authnRequest.setIssueInstant(DateTime.parse(value));
return true;
case "AuthnRequest[ProtocolBinding]":
authnRequest.setProtocolBinding(value);
return true;
case "AuthnRequest[Version]":
authnRequest.setVersion(SAMLVersion.valueOf(value));
return true;
case "AuthnRequest:Issuer":
authnRequest.getIssuer().setValue(value);
return true;
case "AuthnRequest:NameIDPolicy[Format]":
authnRequest.getNameIDPolicy().setFormat(value);
return true;
case "AuthnRequest:NameIDPolicy[SPNameQualifier]":
authnRequest.getNameIDPolicy().setSPNameQualifier(value);
return true;
case "AuthnRequest:NameIDPolicy[AllowCreate]":
if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
authnRequest.getNameIDPolicy().setAllowCreate(Boolean.valueOf(value));
return true;
} else {
throw new SAMLException("Given Value :" + value + " \nExpected either 'true' or 'false'");
}
case "AuthnRequest:RequestedAuthnContext[Comparison]":
AuthnContextComparisonTypeEnumeration type = authnRequest.getRequestedAuthnContext().getComparison();
switch (value) {
case "EXACT":
type = AuthnContextComparisonTypeEnumeration.EXACT;
break;
case "BETTER":
type = AuthnContextComparisonTypeEnumeration.BETTER;
break;
case "MAXIMUM":
type = AuthnContextComparisonTypeEnumeration.MAXIMUM;
break;
case "MINIMUM":
type = AuthnContextComparisonTypeEnumeration.MINIMUM;
break;
default:
throw new SAMLException("Invalid value. \nGiven:" + value + " \nExpected:One of 'EXACT'," +
"'BETTER','MAXIMUM','MINIMUM'");
}
authnRequest.getRequestedAuthnContext().setComparison(type);
return true;
case "AuthnRequest:RequestedAuthnContext:AuthnContextClassRef":
try {
authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).setAuthnContextClassRef(value);
return true;
} catch (Exception e) {
throw new SAMLException("Invalid value given or value can't be set because of the unavailability " +
"of a dependent elemet");
}
}
return false;
}
| private boolean setAuthnRequestValue(String key, String value) throws SAMLException {
if (!(unmarshalledObject instanceof AuthnRequest)) {
return false;
}
AuthnRequest authnRequest = (AuthnRequest) unmarshalledObject;
switch (key) {
case "AuthnRequest[ID]":
authnRequest.setID(value);
return true;
case "AuthnRequest[AssertionConsumerServiceURL]":
authnRequest.setAssertionConsumerServiceURL(value);
return true;
case "AuthnRequest[AttributeConsumingServiceIndex]":
try {
Integer intValue = Integer.parseInt(value);
authnRequest.setAttributeConsumingServiceIndex(intValue);
return true;
} catch (NumberFormatException e) {
throw new SAMLException("Given: " + value + " \nExpected: Integer");
}
case "AuthnRequest[IssueInstant]":
authnRequest.setIssueInstant(DateTime.parse(value));
return true;
case "AuthnRequest[ProtocolBinding]":
authnRequest.setProtocolBinding(value);
return true;
case "AuthnRequest[Version]":
authnRequest.setVersion(SAMLVersion.valueOf(value));
return true;
case "AuthnRequest:Issuer":
authnRequest.getIssuer().setValue(value);
return true;
case "AuthnRequest:NameIDPolicy[Format]":
authnRequest.getNameIDPolicy().setFormat(value);
return true;
case "AuthnRequest:NameIDPolicy[SPNameQualifier]":
authnRequest.getNameIDPolicy().setSPNameQualifier(value);
return true;
case "AuthnRequest:NameIDPolicy[AllowCreate]":
if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
authnRequest.getNameIDPolicy().setAllowCreate(Boolean.valueOf(value));
return true;
} else {
throw new SAMLException("Given Value :" + value + " \nExpected either 'true' or 'false'");
}
case "AuthnRequest:RequestedAuthnContext[Comparison]":
AuthnContextComparisonTypeEnumeration type;
switch (value.toUpperCase()) {
case "EXACT":
type = AuthnContextComparisonTypeEnumeration.EXACT;
break;
case "BETTER":
type = AuthnContextComparisonTypeEnumeration.BETTER;
break;
case "MAXIMUM":
type = AuthnContextComparisonTypeEnumeration.MAXIMUM;
break;
case "MINIMUM":
type = AuthnContextComparisonTypeEnumeration.MINIMUM;
break;
default:
throw new SAMLException("Invalid value. \nGiven:" + value + " \nExpected:One of 'EXACT'," +
"'BETTER','MAXIMUM','MINIMUM'");
}
authnRequest.getRequestedAuthnContext().setComparison(type);
return true;
case "AuthnRequest:RequestedAuthnContext:AuthnContextClassRef":
try {
authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).setAuthnContextClassRef(value);
return true;
} catch (Exception e) {
throw new SAMLException("Invalid value given or value can't be set because of the unavailability " +
"of a dependent elemet");
}
}
return false;
}
|
diff --git a/src/ly/jamie/fontawesomebrowser/ChangeFontAdapter.java b/src/ly/jamie/fontawesomebrowser/ChangeFontAdapter.java
index b593afa..b71eb44 100644
--- a/src/ly/jamie/fontawesomebrowser/ChangeFontAdapter.java
+++ b/src/ly/jamie/fontawesomebrowser/ChangeFontAdapter.java
@@ -1,72 +1,72 @@
package ly.jamie.fontawesomebrowser;
import java.util.Arrays;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ChangeFontAdapter extends BaseAdapter {
private Map<String, String> _strings;
private String[] _keys;
private Context _context;
private Typeface _typeface;
public ChangeFontAdapter(Context context, Map<String,String> strings, Typeface typeface) {
_strings = strings;
_context = context;
_typeface = typeface;
_keys = strings.keySet().toArray(new String[_strings.size()]);
Arrays.sort(_keys);
}
public int getCount() {
return _keys.length;
}
public Object getItem(int position) {
return _strings.get(getKey(position));
}
public long getItemId(int position) {
return position;
}
public String getKey(int position) {
return _keys[position];
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView textViewIconName, textViewIcon;
boolean firstInitialization = false;
if(convertView != null && convertView.getClass() == TextView.class) {
// do nothing
}
else {
firstInitialization = true;
LayoutInflater vi = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.icon_row, null);
}
- textViewIconName = (TextView) convertView.findViewById(R.id.textViewIcon);
+ textViewIconName = (TextView) convertView.findViewById(R.id.textViewIconName);
textViewIconName.setText(getKey(position));
- textViewIcon = (TextView) convertView.findViewById(R.id.textViewIconName);
+ textViewIcon = (TextView) convertView.findViewById(R.id.textViewIcon);
if(firstInitialization) {
textViewIcon.setTypeface(_typeface);
textViewIcon.setTextSize(30);
}
textViewIcon.setText((String) getItem(position));
return convertView;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
TextView textViewIconName, textViewIcon;
boolean firstInitialization = false;
if(convertView != null && convertView.getClass() == TextView.class) {
// do nothing
}
else {
firstInitialization = true;
LayoutInflater vi = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.icon_row, null);
}
textViewIconName = (TextView) convertView.findViewById(R.id.textViewIcon);
textViewIconName.setText(getKey(position));
textViewIcon = (TextView) convertView.findViewById(R.id.textViewIconName);
if(firstInitialization) {
textViewIcon.setTypeface(_typeface);
textViewIcon.setTextSize(30);
}
textViewIcon.setText((String) getItem(position));
return convertView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
TextView textViewIconName, textViewIcon;
boolean firstInitialization = false;
if(convertView != null && convertView.getClass() == TextView.class) {
// do nothing
}
else {
firstInitialization = true;
LayoutInflater vi = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.icon_row, null);
}
textViewIconName = (TextView) convertView.findViewById(R.id.textViewIconName);
textViewIconName.setText(getKey(position));
textViewIcon = (TextView) convertView.findViewById(R.id.textViewIcon);
if(firstInitialization) {
textViewIcon.setTypeface(_typeface);
textViewIcon.setTextSize(30);
}
textViewIcon.setText((String) getItem(position));
return convertView;
}
|
diff --git a/src/Engine/Module.java b/src/Engine/Module.java
index f2c5316..a6437e8 100644
--- a/src/Engine/Module.java
+++ b/src/Engine/Module.java
@@ -1,196 +1,208 @@
/**
*
*/
package Engine;
import Modules.Container;
/*
* @author orpheon
* This class is the baseline Module class. It contains everything which every module should have, and cannot be instanciated.
*/
public abstract class Module
{
// Constants that hold the number of in and out pipes
public int NUM_INPUT_PIPES;
public int NUM_OUTPUT_PIPES;
// The actual pipe arrays that hold those pipes
protected Pipe[] input_pipes;
protected Pipe[] output_pipes;
// Arrays that contain the names of each pipe
public String[] input_pipe_names;
public String[] output_pipe_names;
// ID system to provide each module with an identifier
protected static int counter;
protected int index;
// Constant holding what type of module it actually is
protected int module_type;
// A string doing the same as the above constant, but in a human-readable form
public String MODULE_NAME;
// A variable that tracks whether this module is in stereo or in mono mode
protected int audio_mode;
// Variable for denoting the preferred source of activation time if a module has one
protected int activation_source;
// This makes a module actually do whatever it's supposed to do on it's inputs and write to it's outputs
public abstract void run(Engine.EngineMaster engine, int channel);
public Module()
{
index = counter++;
MODULE_NAME = "Default Module";
audio_mode = Engine.Constants.DEFAULT_AUDIO_MODE;
activation_source = -1;
}
public void run(Engine.EngineMaster engine)
{
// We check every channel, and if there's an input pipe that's active on that channel we execute the run(channel) method to calculate the output
for (int channel=0; channel<Constants.NUM_CHANNELS; channel++)
{
int source = -1;
if (activation_source >= 0)
{
// This module has specified an input source for the activation timers
// Indulge it
if (input_pipes[activation_source] != null)
{
if (input_pipes[activation_source].activation_times[channel] >= 0)
{
source = activation_source;
}
}
}
else
{
double activation_time = -1;
for (int j=0; j<NUM_INPUT_PIPES; j++)
{
if (input_pipes[j] != null)
{
if (input_pipes[j].activation_times[channel] > activation_time)
{
activation_time = input_pipes[j].activation_times[channel];
source = channel;
}
}
}
}
if (source >= 0)
{
+ // Run the module, and then update the activation times
this.run(engine, channel);
+ for (int k=0; k<NUM_OUTPUT_PIPES; k++)
+ {
+ if (output_pipes[k] != null)
+ {
+ output_pipes[k].activation_times[channel] = input_pipes[source].activation_times[channel];
+ }
+ }
}
- for (int k=0; k<NUM_OUTPUT_PIPES; k++)
+ else
{
- if (output_pipes[k] != null)
+ // Make sure the "off" gets propagated
+ for (int k=0; k<NUM_OUTPUT_PIPES; k++)
{
- output_pipes[k].activation_times[channel] = input_pipes[source].activation_times[channel];
+ if (output_pipes[k] != null)
+ {
+ output_pipes[k].activation_times[channel] = -1;
+ }
}
}
}
}
public boolean connect_input(Pipe pipe, int position)
{
if (position >= NUM_INPUT_PIPES)
{
// Trying to connect a cable to an invalid port.
// Don't allow this
System.out.println("ERROR: Tried to connect pipe "+pipe.get_index()+" to an invalid input port "+position+" to Module number "+index+" of type "+module_type+".");
// Just return false
return false;
}
if (pipe.get_type() != audio_mode)
{
// Trying to connect a cable to a module of a different audio mode
// Bad idea, refuse connection and let the gui deal with the problem (ask whether to change mode, etc...)
// FIXME: Find better way to do this
System.out.println("ERROR: Tried to connect pipe "+pipe.get_index()+" to an invalid input port "+position+" to Module number "+index+" of type "+module_type+"; incompatible audio modes.");
// Uhm...return false...I guess? Probably do some callback or so first, then handle, but ugh... | FIXME
return false;
}
pipe.set_output(this);
input_pipes[position] = pipe;
return true;
}
public void disconnect_input(int position)
{
input_pipes[position].set_output(null);
input_pipes[position] = null;
}
public boolean connect_output(Pipe pipe, int position)
{
if (position >= NUM_OUTPUT_PIPES)
{
// Trying to connect a cable to an invalid port.
// Don't allow this
System.out.println("ERROR: Tried to connect pipe "+pipe.get_index()+" to an invalid output port "+position+" to Module number "+index+" of type "+MODULE_NAME+".");
// Just return false
return false;
}
if (output_pipes[position] != null)
{
// There's already a pipe there, we need to disconnect it first
disconnect_output(position);
}
pipe.set_input(this);
output_pipes[position] = pipe;
return true;
}
public void disconnect_output(int position)
{
output_pipes[position].set_input(null);
output_pipes[position] = null;
}
public int get_index()
{
return index;
}
public int get_moduletype()
{
return module_type;
}
public Pipe get_input_pipe(int i)
{
return input_pipes[i];
}
public Pipe get_output_pipe(int i)
{
return output_pipes[i];
}
public int get_audio_mode()
{
return audio_mode;
}
public void set_audio_mode(int new_mode)
{
audio_mode = new_mode;
}
public void close(Container container)
{
// Clean everything up
for (int i=0; i<NUM_INPUT_PIPES; i++)
{
disconnect_input(i);
}
for (int i=0; i<NUM_OUTPUT_PIPES; i++)
{
disconnect_output(i);
}
container.remove_module(this);
}
}
| false | true | public void run(Engine.EngineMaster engine)
{
// We check every channel, and if there's an input pipe that's active on that channel we execute the run(channel) method to calculate the output
for (int channel=0; channel<Constants.NUM_CHANNELS; channel++)
{
int source = -1;
if (activation_source >= 0)
{
// This module has specified an input source for the activation timers
// Indulge it
if (input_pipes[activation_source] != null)
{
if (input_pipes[activation_source].activation_times[channel] >= 0)
{
source = activation_source;
}
}
}
else
{
double activation_time = -1;
for (int j=0; j<NUM_INPUT_PIPES; j++)
{
if (input_pipes[j] != null)
{
if (input_pipes[j].activation_times[channel] > activation_time)
{
activation_time = input_pipes[j].activation_times[channel];
source = channel;
}
}
}
}
if (source >= 0)
{
this.run(engine, channel);
}
for (int k=0; k<NUM_OUTPUT_PIPES; k++)
{
if (output_pipes[k] != null)
{
output_pipes[k].activation_times[channel] = input_pipes[source].activation_times[channel];
}
}
}
}
| public void run(Engine.EngineMaster engine)
{
// We check every channel, and if there's an input pipe that's active on that channel we execute the run(channel) method to calculate the output
for (int channel=0; channel<Constants.NUM_CHANNELS; channel++)
{
int source = -1;
if (activation_source >= 0)
{
// This module has specified an input source for the activation timers
// Indulge it
if (input_pipes[activation_source] != null)
{
if (input_pipes[activation_source].activation_times[channel] >= 0)
{
source = activation_source;
}
}
}
else
{
double activation_time = -1;
for (int j=0; j<NUM_INPUT_PIPES; j++)
{
if (input_pipes[j] != null)
{
if (input_pipes[j].activation_times[channel] > activation_time)
{
activation_time = input_pipes[j].activation_times[channel];
source = channel;
}
}
}
}
if (source >= 0)
{
// Run the module, and then update the activation times
this.run(engine, channel);
for (int k=0; k<NUM_OUTPUT_PIPES; k++)
{
if (output_pipes[k] != null)
{
output_pipes[k].activation_times[channel] = input_pipes[source].activation_times[channel];
}
}
}
else
{
// Make sure the "off" gets propagated
for (int k=0; k<NUM_OUTPUT_PIPES; k++)
{
if (output_pipes[k] != null)
{
output_pipes[k].activation_times[channel] = -1;
}
}
}
}
}
|
diff --git a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
index cc5986f28..368291a29 100644
--- a/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
+++ b/src/test/com/jogamp/opengl/test/junit/util/UITestCase.java
@@ -1,115 +1,115 @@
/**
* Copyright 2010 JogAmp Community. 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.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package com.jogamp.opengl.test.junit.util;
import com.jogamp.common.os.Platform;
import com.jogamp.common.util.locks.SingletonInstance;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.runner.manipulation.NoTestsRemainException;
public abstract class UITestCase {
@Rule public TestName _unitTestName = new TestName();
public static final String SINGLE_INSTANCE_LOCK_FILE = "UITestCase.lock";
public static final int SINGLE_INSTANCE_LOCK_PORT = 59999;
public static final long SINGLE_INSTANCE_LOCK_TO = 3*60*1000; // wait up to 3 min
public static final long SINGLE_INSTANCE_LOCK_POLL = 1000; // poll every 1s
static volatile SingletonInstance singletonInstance;
static volatile boolean testSupported = true;
private static final synchronized void initSingletonInstance() {
if( null == singletonInstance ) {
// singletonInstance = SingletonInstance.createFileLock(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_FILE);
singletonInstance = SingletonInstance.createServerSocket(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_PORT);
if(!singletonInstance.tryLock(SINGLE_INSTANCE_LOCK_TO)) {
- throw new RuntimeException("Fatal: Could lock single instance: "+singletonInstance.getName());
+ throw new RuntimeException("Fatal: Could not lock single instance: "+singletonInstance.getName());
}
}
}
public static void setTestSupported(boolean v) {
System.err.println("setTestSupported: "+v);
testSupported = v;
}
public final String getTestMethodName() {
return _unitTestName.getMethodName();
}
public final String getSimpleTestName(String separator) {
return getClass().getSimpleName()+separator+getTestMethodName();
}
public final String getFullTestName(String separator) {
return getClass().getName()+separator+getTestMethodName();
}
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
initSingletonInstance();
}
@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
System.gc(); // force cleanup
singletonInstance.unlock();
}
@Before
public void setUp() {
System.err.print("++++ UITestCase.setUp: "+getFullTestName(" - "));
if(!testSupported) {
System.err.println(" - "+unsupportedTestMsg);
Assume.assumeTrue(testSupported);
}
System.err.println();
}
@After
public void tearDown() {
System.err.println("++++ UITestCase.tearDown: "+getFullTestName(" - "));
}
static final String unsupportedTestMsg = "Test not supported on this platform.";
}
| true | true | private static final synchronized void initSingletonInstance() {
if( null == singletonInstance ) {
// singletonInstance = SingletonInstance.createFileLock(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_FILE);
singletonInstance = SingletonInstance.createServerSocket(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_PORT);
if(!singletonInstance.tryLock(SINGLE_INSTANCE_LOCK_TO)) {
throw new RuntimeException("Fatal: Could lock single instance: "+singletonInstance.getName());
}
}
}
| private static final synchronized void initSingletonInstance() {
if( null == singletonInstance ) {
// singletonInstance = SingletonInstance.createFileLock(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_FILE);
singletonInstance = SingletonInstance.createServerSocket(SINGLE_INSTANCE_LOCK_POLL, SINGLE_INSTANCE_LOCK_PORT);
if(!singletonInstance.tryLock(SINGLE_INSTANCE_LOCK_TO)) {
throw new RuntimeException("Fatal: Could not lock single instance: "+singletonInstance.getName());
}
}
}
|
diff --git a/src/main/java/com/hmsonline/storm/cassandra/client/AstyanaxColumn.java b/src/main/java/com/hmsonline/storm/cassandra/client/AstyanaxColumn.java
index b630ae1..822245b 100644
--- a/src/main/java/com/hmsonline/storm/cassandra/client/AstyanaxColumn.java
+++ b/src/main/java/com/hmsonline/storm/cassandra/client/AstyanaxColumn.java
@@ -1,23 +1,24 @@
package com.hmsonline.storm.cassandra.client;
import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.Column;
public class AstyanaxColumn<K, V> implements com.hmsonline.storm.cassandra.bolt.mapper.Column<K, V> {
private Column<K> column = null;
private Serializer<V> serializer = null;
public AstyanaxColumn(Column<K> column, Serializer<V> serializer) {
this.column = column;
+ this.serializer = serializer;
}
@Override
public K getKey() {
return column.getName();
}
@Override
public V getValue() {
return column.getValue(serializer);
}
}
| true | true | public AstyanaxColumn(Column<K> column, Serializer<V> serializer) {
this.column = column;
}
| public AstyanaxColumn(Column<K> column, Serializer<V> serializer) {
this.column = column;
this.serializer = serializer;
}
|
diff --git a/src/main/java/hudson/plugins/kagemai/KagemaiPublisher.java b/src/main/java/hudson/plugins/kagemai/KagemaiPublisher.java
index 9140c05..219ddbe 100644
--- a/src/main/java/hudson/plugins/kagemai/KagemaiPublisher.java
+++ b/src/main/java/hudson/plugins/kagemai/KagemaiPublisher.java
@@ -1,101 +1,101 @@
package hudson.plugins.kagemai;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Result;
import hudson.plugins.kagemai.model.KagemaiIssue;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.Publisher;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.kohsuke.stapler.StaplerRequest;
/**
* @author yamkazu
*
*/
public class KagemaiPublisher extends Publisher {
KagemaiPublisher() {
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
KagemaiSite site = KagemaiSite.get(build.getProject());
if (site == null) {
build.setResult(Result.FAILURE);
return true;
}
HashSet<Integer> bugIds = new HashSet<Integer>();
KagemaiProjectProperty mpp = build.getParent().getProperty(
KagemaiProjectProperty.class);
if (mpp != null && mpp.getSite() != null) {
String regex = mpp.getRegex();
Pattern pattern = Pattern.compile(regex);
for (Entry entry : build.getChangeSet()) {
Matcher matcher = pattern.matcher(entry.getMsg());
while (matcher.find()) {
try {
bugIds.add(Integer.valueOf(matcher.group(matcher
.groupCount())));
} catch (NumberFormatException e) {
continue;
}
}
}
} else {
build.setResult(Result.FAILURE);
return true;
}
KagemaiSession kagemaiSession = mpp.getKagemaiSession();
List<KagemaiIssue> issues = null;
if ((!bugIds.isEmpty()) && kagemaiSession != null) {
issues = kagemaiSession.getIssuesMap(bugIds);
}
- if (issues.size() > 0) {
+ if (issues != null && issues.size() > 0) {
Collections.sort(issues);
}
KagemaiBuildAction action = new KagemaiBuildAction(build, issues, mpp
.getSiteName(), mpp.getProjectId());
build.addAction(action);
return true;
}
public Descriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Publisher> {
DescriptorImpl() {
super(KagemaiPublisher.class);
}
@Override
public String getDisplayName() {
return Messages.publisher_dispname();
}
@Override
public KagemaiPublisher newInstance(StaplerRequest req)
throws FormException {
return new KagemaiPublisher();
}
}
}
| true | true | public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
KagemaiSite site = KagemaiSite.get(build.getProject());
if (site == null) {
build.setResult(Result.FAILURE);
return true;
}
HashSet<Integer> bugIds = new HashSet<Integer>();
KagemaiProjectProperty mpp = build.getParent().getProperty(
KagemaiProjectProperty.class);
if (mpp != null && mpp.getSite() != null) {
String regex = mpp.getRegex();
Pattern pattern = Pattern.compile(regex);
for (Entry entry : build.getChangeSet()) {
Matcher matcher = pattern.matcher(entry.getMsg());
while (matcher.find()) {
try {
bugIds.add(Integer.valueOf(matcher.group(matcher
.groupCount())));
} catch (NumberFormatException e) {
continue;
}
}
}
} else {
build.setResult(Result.FAILURE);
return true;
}
KagemaiSession kagemaiSession = mpp.getKagemaiSession();
List<KagemaiIssue> issues = null;
if ((!bugIds.isEmpty()) && kagemaiSession != null) {
issues = kagemaiSession.getIssuesMap(bugIds);
}
if (issues.size() > 0) {
Collections.sort(issues);
}
KagemaiBuildAction action = new KagemaiBuildAction(build, issues, mpp
.getSiteName(), mpp.getProjectId());
build.addAction(action);
return true;
}
| public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
KagemaiSite site = KagemaiSite.get(build.getProject());
if (site == null) {
build.setResult(Result.FAILURE);
return true;
}
HashSet<Integer> bugIds = new HashSet<Integer>();
KagemaiProjectProperty mpp = build.getParent().getProperty(
KagemaiProjectProperty.class);
if (mpp != null && mpp.getSite() != null) {
String regex = mpp.getRegex();
Pattern pattern = Pattern.compile(regex);
for (Entry entry : build.getChangeSet()) {
Matcher matcher = pattern.matcher(entry.getMsg());
while (matcher.find()) {
try {
bugIds.add(Integer.valueOf(matcher.group(matcher
.groupCount())));
} catch (NumberFormatException e) {
continue;
}
}
}
} else {
build.setResult(Result.FAILURE);
return true;
}
KagemaiSession kagemaiSession = mpp.getKagemaiSession();
List<KagemaiIssue> issues = null;
if ((!bugIds.isEmpty()) && kagemaiSession != null) {
issues = kagemaiSession.getIssuesMap(bugIds);
}
if (issues != null && issues.size() > 0) {
Collections.sort(issues);
}
KagemaiBuildAction action = new KagemaiBuildAction(build, issues, mpp
.getSiteName(), mpp.getProjectId());
build.addAction(action);
return true;
}
|
diff --git a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java
index b986b5b4c..439c5c33d 100644
--- a/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java
+++ b/restcomm.rcml/src/main/java/org/mobicents/servlet/sip/restcomm/interpreter/tagstrategy/ConferenceSubStrategy.java
@@ -1,275 +1,275 @@
package org.mobicents.servlet.sip.restcomm.interpreter.tagstrategy;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.mobicents.servlet.sip.restcomm.ServiceLocator;
import org.mobicents.servlet.sip.restcomm.Sid;
import org.mobicents.servlet.sip.restcomm.entities.Notification;
import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreter;
import org.mobicents.servlet.sip.restcomm.interpreter.RcmlInterpreterContext;
import org.mobicents.servlet.sip.restcomm.interpreter.TagStrategyException;
import org.mobicents.servlet.sip.restcomm.media.api.Call;
import org.mobicents.servlet.sip.restcomm.media.api.CallObserver;
import org.mobicents.servlet.sip.restcomm.media.api.Conference;
import org.mobicents.servlet.sip.restcomm.media.api.ConferenceCenter;
import org.mobicents.servlet.sip.restcomm.media.api.ConferenceObserver;
import org.mobicents.servlet.sip.restcomm.util.StringUtils;
import org.mobicents.servlet.sip.restcomm.util.TimeUtils;
import org.mobicents.servlet.sip.restcomm.xml.Attribute;
import org.mobicents.servlet.sip.restcomm.xml.Tag;
import org.mobicents.servlet.sip.restcomm.xml.rcml.RcmlTag;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.Beep;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.EndConferenceOnExit;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.MaxParticipants;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.Muted;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.StartConferenceOnEnter;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.WaitMethod;
import org.mobicents.servlet.sip.restcomm.xml.rcml.attributes.WaitUrl;
public final class ConferenceSubStrategy extends RcmlTagStrategy implements CallObserver, ConferenceObserver {
private final ConferenceCenter conferenceCenter;
private final URI action;
private final String method;
private final int timeLimit;
private final boolean record;
private Sid recordingSid;
private String name;
private boolean muted;
private boolean beep;
private boolean startConferenceOnEnter;
private boolean endConferenceOnExit;
private URI waitUrl;
private String waitMethod;
private int maxParticipants;
private URI alertOnEnterAudioFile;
private URI alertOnExitAudioFile;
public ConferenceSubStrategy(final URI action, final String method, final int timeLimit, final boolean record) {
super();
final ServiceLocator services = ServiceLocator.getInstance();
this.conferenceCenter = services.get(ConferenceCenter.class);
this.action = action;
this.method = method;
this.timeLimit = timeLimit;
this.record = record;
if(record) { recordingSid = Sid.generate(Sid.Type.RECORDING); }
waitUrl = URI.create("file://" + configuration.getString("conference-music-file"));
alertOnEnterAudioFile = URI.create("file://" + configuration.getString("alert-on-enter-file"));
alertOnExitAudioFile = URI.create("file://" + configuration.getString("alert-on-exit-file"));
}
@Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Call call = context.getCall();
final StringBuilder buffer = new StringBuilder();
buffer.append(context.getAccountSid().toString()).append(":").append(name);
final String room = buffer.toString();
final DateTime start = DateTime.now();
final Conference conference = conferenceCenter.getConference(room);
if(!startConferenceOnEnter) {
if(Call.Status.IN_PROGRESS == call.getStatus() && !call.isMuted()) {
call.mute();
}
if(conference.getNumberOfParticipants() == 0) {
if(waitUrl != null) {
final List<URI> music = new ArrayList<URI>();
music.add(waitUrl);
conference.setBackgroundMusic(music);
conference.playBackgroundMusic();
}
}
} else {
conference.stopBackgroundMusic();
if(beep) { conference.play(alertOnEnterAudioFile); }
if(Call.Status.IN_PROGRESS == call.getStatus() && muted) { call.mute(); }
}
if(Call.Status.IN_PROGRESS == call.getStatus()) {
call.addObserver(this);
conference.addObserver(this);
conference.addParticipant(call);
try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); }
catch(final InterruptedException ignored) { }
conference.removeObserver(this);
call.removeObserver(this);
}
- if(endConferenceOnExit) {
+ if(endConferenceOnExit || (conference.getNumberOfParticipants() == 0)) {
conferenceCenter.removeConference(room);
} else {
if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) {
conference.removeParticipant(call);
}
if(beep) { conference.play(alertOnExitAudioFile); }
}
final DateTime finish = DateTime.now();
if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("DialCallStatus", "completed"));
parameters.add(new BasicNameValuePair("DialCallDuration",
Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS)));
if(record) {
parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString()));
}
interpreter.load(action, method, parameters);
interpreter.redirect();
}
}
private boolean getBeep(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(Beep.NAME);
if(attribute == null) {
return true;
}
final String value = attribute.getValue();
if("true".equalsIgnoreCase(value)) {
return true;
} else if("false".equalsIgnoreCase(value)) {
return false;
} else {
return true;
}
}
private Tag getConferenceTag(final List<Tag> tags) {
final String name = org.mobicents.servlet.sip.restcomm.xml.rcml.Conference.NAME;
for(final Tag tag : tags) {
if(name.equals(tag.getName())) {
return tag;
}
}
return null;
}
private boolean getEndConferenceOnExit(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(EndConferenceOnExit.NAME);
if(attribute == null) {
return false;
}
final String value = attribute.getValue();
if("true".equalsIgnoreCase(value)) {
return true;
} else if("false".equalsIgnoreCase(value)) {
return false;
} else {
interpreter.notify(context, Notification.WARNING, 13231);
return false;
}
}
private int getMaxParticipants(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(MaxParticipants.NAME);
if(attribute == null) {
return 40;
}
final String value = attribute.getValue();
if(StringUtils.isPositiveInteger(value)) {
final int result = Integer.parseInt(value);
if(result > 0) {
return result;
}
}
return 40;
}
private boolean getMuted(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(Muted.NAME);
if(attribute == null) {
return false;
}
final String value = attribute.getValue();
if("true".equalsIgnoreCase(value)) {
return true;
} else if("false".equalsIgnoreCase(value)) {
return false;
} else {
interpreter.notify(context, Notification.WARNING, 13230);
return false;
}
}
private boolean getStartConferenceOnEnter(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(StartConferenceOnEnter.NAME);
if(attribute == null) {
return true;
}
final String value = attribute.getValue();
if("true".equalsIgnoreCase(value)) {
return true;
} else if("false".equalsIgnoreCase(value)) {
return false;
} else {
interpreter.notify(context, Notification.WARNING, 13232);
return true;
}
}
private URI getWaitUrl(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(WaitUrl.NAME);
if(attribute != null) {
try {
final URI base = interpreter.getCurrentResourceUri();
return resolveIfNotAbsolute(base, attribute.getValue());
} catch(final IllegalArgumentException exception) {
interpreter.notify(context, Notification.ERROR, 13233);
throw new TagStrategyException(exception);
}
}
return null;
}
private String getWaitMethod(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Attribute attribute = tag.getAttribute(WaitMethod.NAME);
if(attribute == null) {
return "POST";
}
final String value = attribute.getValue();
if("GET".equalsIgnoreCase(value)) {
return "GET";
} else if("POST".equalsIgnoreCase(value)) {
return "POST";
} else {
interpreter.notify(context, Notification.WARNING, 13234);
return "POST";
}
}
@Override public synchronized void initialize(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final RcmlTag conference = (RcmlTag)getConferenceTag(tag.getChildren());
name = conference.getText();
muted = getMuted(interpreter, context, conference);
beep = getBeep(interpreter, context, conference);
startConferenceOnEnter = getStartConferenceOnEnter(interpreter, context, conference);
endConferenceOnExit = getEndConferenceOnExit(interpreter, context, conference);
waitUrl = getWaitUrl(interpreter, context, conference);
waitMethod = getWaitMethod(interpreter, context, conference);
maxParticipants = getMaxParticipants(interpreter, context, conference);
}
@Override public synchronized void onStatusChanged(final Call call) {
final Call.Status status = call.getStatus();
if(Call.Status.CANCELLED == status || Call.Status.COMPLETED == status || Call.Status.FAILED == status) {
notify();
}
}
@Override public synchronized void onStatusChanged(final Conference conference) {
final Conference.Status status = conference.getStatus();
if(Conference.Status.COMPLETED == status || Conference.Status.FAILED == status) {
notify();
}
}
}
| true | true | @Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Call call = context.getCall();
final StringBuilder buffer = new StringBuilder();
buffer.append(context.getAccountSid().toString()).append(":").append(name);
final String room = buffer.toString();
final DateTime start = DateTime.now();
final Conference conference = conferenceCenter.getConference(room);
if(!startConferenceOnEnter) {
if(Call.Status.IN_PROGRESS == call.getStatus() && !call.isMuted()) {
call.mute();
}
if(conference.getNumberOfParticipants() == 0) {
if(waitUrl != null) {
final List<URI> music = new ArrayList<URI>();
music.add(waitUrl);
conference.setBackgroundMusic(music);
conference.playBackgroundMusic();
}
}
} else {
conference.stopBackgroundMusic();
if(beep) { conference.play(alertOnEnterAudioFile); }
if(Call.Status.IN_PROGRESS == call.getStatus() && muted) { call.mute(); }
}
if(Call.Status.IN_PROGRESS == call.getStatus()) {
call.addObserver(this);
conference.addObserver(this);
conference.addParticipant(call);
try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); }
catch(final InterruptedException ignored) { }
conference.removeObserver(this);
call.removeObserver(this);
}
if(endConferenceOnExit) {
conferenceCenter.removeConference(room);
} else {
if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) {
conference.removeParticipant(call);
}
if(beep) { conference.play(alertOnExitAudioFile); }
}
final DateTime finish = DateTime.now();
if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("DialCallStatus", "completed"));
parameters.add(new BasicNameValuePair("DialCallDuration",
Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS)));
if(record) {
parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString()));
}
interpreter.load(action, method, parameters);
interpreter.redirect();
}
}
| @Override public synchronized void execute(final RcmlInterpreter interpreter, final RcmlInterpreterContext context,
final RcmlTag tag) throws TagStrategyException {
final Call call = context.getCall();
final StringBuilder buffer = new StringBuilder();
buffer.append(context.getAccountSid().toString()).append(":").append(name);
final String room = buffer.toString();
final DateTime start = DateTime.now();
final Conference conference = conferenceCenter.getConference(room);
if(!startConferenceOnEnter) {
if(Call.Status.IN_PROGRESS == call.getStatus() && !call.isMuted()) {
call.mute();
}
if(conference.getNumberOfParticipants() == 0) {
if(waitUrl != null) {
final List<URI> music = new ArrayList<URI>();
music.add(waitUrl);
conference.setBackgroundMusic(music);
conference.playBackgroundMusic();
}
}
} else {
conference.stopBackgroundMusic();
if(beep) { conference.play(alertOnEnterAudioFile); }
if(Call.Status.IN_PROGRESS == call.getStatus() && muted) { call.mute(); }
}
if(Call.Status.IN_PROGRESS == call.getStatus()) {
call.addObserver(this);
conference.addObserver(this);
conference.addParticipant(call);
try { wait(TimeUtils.SECOND_IN_MILLIS * timeLimit); }
catch(final InterruptedException ignored) { }
conference.removeObserver(this);
call.removeObserver(this);
}
if(endConferenceOnExit || (conference.getNumberOfParticipants() == 0)) {
conferenceCenter.removeConference(room);
} else {
if(Call.Status.IN_PROGRESS == call.getStatus() && Conference.Status.IN_PROGRESS == conference.getStatus()) {
conference.removeParticipant(call);
}
if(beep) { conference.play(alertOnExitAudioFile); }
}
final DateTime finish = DateTime.now();
if(Call.Status.IN_PROGRESS == call.getStatus() && action != null) {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("DialCallStatus", "completed"));
parameters.add(new BasicNameValuePair("DialCallDuration",
Long.toString(finish.minus(start.getMillis()).getMillis() / TimeUtils.SECOND_IN_MILLIS)));
if(record) {
parameters.add(new BasicNameValuePair("RecordingUrl", toRecordingPath(recordingSid).toString()));
}
interpreter.load(action, method, parameters);
interpreter.redirect();
}
}
|
diff --git a/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/AComponent.java b/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/AComponent.java
index 01f7a2f..54ea494 100644
--- a/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/AComponent.java
+++ b/trunk/src/Cubee/src/com/eagerlogic/cubee/client/components/AComponent.java
@@ -1,1037 +1,1038 @@
package com.eagerlogic.cubee.client.components;
import com.eagerlogic.cubee.client.EventQueue;
import com.eagerlogic.cubee.client.events.ClickEventArgs;
import com.eagerlogic.cubee.client.events.Event;
import com.eagerlogic.cubee.client.events.EventArgs;
import com.eagerlogic.cubee.client.events.KeyEventArgs;
import com.eagerlogic.cubee.client.events.MouseDownEventArgs;
import com.eagerlogic.cubee.client.events.MouseEventTypes;
import com.eagerlogic.cubee.client.events.MouseDragEventArgs;
import com.eagerlogic.cubee.client.events.MouseMoveEventArgs;
import com.eagerlogic.cubee.client.events.MouseWheelEventArgs;
import com.eagerlogic.cubee.client.events.MouseUpEventArgs;
import com.eagerlogic.cubee.client.properties.BooleanProperty;
import com.eagerlogic.cubee.client.styles.Padding;
import com.eagerlogic.cubee.client.properties.BorderProperty;
import com.eagerlogic.cubee.client.styles.Border;
import com.eagerlogic.cubee.client.properties.PaddingProperty;
import com.eagerlogic.cubee.client.properties.DoubleProperty;
import com.eagerlogic.cubee.client.styles.ECursor;
import com.eagerlogic.cubee.client.properties.IChangeListener;
import com.eagerlogic.cubee.client.properties.IntegerProperty;
import com.eagerlogic.cubee.client.properties.Property;
import com.eagerlogic.cubee.client.utils.Point2D;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.EventListener;
import java.util.LinkedList;
/**
* This class is the base class of all the components in Cubee. This class wraps a html element. You can inherite from
* this class if you want to wrap a HTML element into a Cubee component.
*
* @author dipacs
*/
public abstract class AComponent {
private static final LinkedList<MouseDownEventLog> pointerDownEvents = new LinkedList<MouseDownEventLog>();
private static void logPointerDownEvent(MouseDownEventLog item) {
pointerDownEvents.add(item);
}
private static void fireDragEvents(int screenX, int screenY, boolean altPressed, boolean ctrlPressed,
boolean shiftPressed, boolean metaPressed) {
for (MouseDownEventLog log : pointerDownEvents) {
MouseDragEventArgs args = new MouseDragEventArgs(screenX, screenY, screenX - log.getScreenX(),
screenY - log.getScreenY(), altPressed, ctrlPressed, shiftPressed, metaPressed, log.getComponent());
log.getComponent().onMouseDrag.fireEvent(args);
}
}
private static void fireUpEvents(int screenX, int screenY, boolean altPressed, boolean ctrlPressed,
boolean shiftPressed, boolean metaPressed) {
long stamp = System.currentTimeMillis();
for (MouseDownEventLog log : pointerDownEvents) {
MouseUpEventArgs args = new MouseUpEventArgs(screenX, screenY, screenX - log.getScreenX(),
screenY - log.getScreenY(), altPressed, ctrlPressed, shiftPressed, metaPressed, log.getComponent());
log.getComponent().onMouseUp.fireEvent(args);
if (stamp - log.getTimeStamp() < 500) {
log.getComponent().onClick.fireEvent(new ClickEventArgs(screenX, screenY, log.getX(), log.getY(),
altPressed, ctrlPressed, shiftPressed, metaPressed, log.getComponent()));
}
}
pointerDownEvents.clear();
}
private final EventListener nativeEventListener = new EventListener() {
@Override
public void onBrowserEvent(com.google.gwt.user.client.Event event) {
if (AComponent.this instanceof TextBox) {
if ((event.getTypeInt() & com.google.gwt.user.client.Event.ONKEYUP) > 0) {
EventQueue.getInstance().invokePrior(new Runnable() {
@Override
public void run() {
((TextBox)AComponent.this).textProperty().set(getElement().getPropertyString("value"));
}
});
}
}
int x = event.getClientX();
int y = event.getClientY();
int wheelVelocity = event.getMouseWheelVelocityY();
AComponent parent;
KeyEventArgs keyArgs;
switch (event.getTypeInt()) {
case com.google.gwt.user.client.Event.ONMOUSEDOWN:
case com.google.gwt.user.client.Event.ONMOUSEWHEEL:
event.stopPropagation();
CubeePanel.getInstance().doPointerEventClimbingUp(x, y, x, y, wheelVelocity,
event.getAltKey(), event.getCtrlKey(), event.getShiftKey(), event.getMetaKey(),
event.getTypeInt());
break;
case com.google.gwt.user.client.Event.ONMOUSEMOVE:
event.stopPropagation();
if (pointerDownEvents.size() > 0) {
fireDragEvents(event.getClientX(), event.getClientY(), event.getAltKey(), event.getCtrlKey(), event.getShiftKey(), event.getMetaKey());
}else {
CubeePanel.getInstance().doPointerEventClimbingUp(x, y, x, y, wheelVelocity,
event.getAltKey(), event.getCtrlKey(), event.getShiftKey(), event.getMetaKey(),
event.getTypeInt());
}
break;
case com.google.gwt.user.client.Event.ONMOUSEUP:
event.stopPropagation();
fireUpEvents(event.getClientX(), event.getClientY(), event.getAltKey(), event.getCtrlKey(), event.getShiftKey(), event.getMetaKey());
break;
case com.google.gwt.user.client.Event.ONMOUSEOVER:
if (pointerTransparent.get()) {
return;
}
// check handle pointer
parent = AComponent.this;
while (parent != null) {
if (!parent.handlePointer.get()) {
return;
}
parent = parent.getParent();
}
onMouseEnter.fireEvent(new EventArgs(AComponent.this));
break;
case com.google.gwt.user.client.Event.ONMOUSEOUT:
if (pointerTransparent.get()) {
return;
}
// check handle pointer
parent = AComponent.this;
while (parent != null) {
if (!parent.handlePointer.get()) {
return;
}
parent = parent.getParent();
}
onMouseLeave.fireEvent(new EventArgs(AComponent.this));
break;
case com.google.gwt.user.client.Event.ONKEYDOWN:
event.stopPropagation();
keyArgs = new KeyEventArgs((char)event.getKeyCode(), event.getAltKey(), event.getCtrlKey(),
event.getShiftKey(), event.getMetaKey(), AComponent.this);
onKeyDown.fireEvent(keyArgs);
break;
case com.google.gwt.user.client.Event.ONKEYPRESS:
event.stopPropagation();
keyArgs = new KeyEventArgs((char)event.getKeyCode(), event.getAltKey(), event.getCtrlKey(),
event.getShiftKey(), event.getMetaKey(), AComponent.this);
onKeyPress.fireEvent(keyArgs);
break;
case com.google.gwt.user.client.Event.ONKEYUP:
event.stopPropagation();
keyArgs = new KeyEventArgs((char)event.getKeyCode(), event.getAltKey(), event.getCtrlKey(),
event.getShiftKey(), event.getMetaKey(), AComponent.this);
onKeyUp.fireEvent(keyArgs);
break;
}
}
};
private final IntegerProperty translateX = new IntegerProperty(0, false, false);
private final IntegerProperty translateY = new IntegerProperty(0, false, false);
private final DoubleProperty rotate = new DoubleProperty(0.0, false, false);
private final DoubleProperty scaleX = new DoubleProperty(1.0, false, false);
private final DoubleProperty scaleY = new DoubleProperty(1.0, false, false);
private final DoubleProperty transformCenterX = new DoubleProperty(0.5, false, false);
private final DoubleProperty transformCenterY = new DoubleProperty(0.5, false, false);
private final PaddingProperty padding = new PaddingProperty(null, true, false);
private final BorderProperty border = new BorderProperty(null, true, false);
private final IntegerProperty measuredWidth = new IntegerProperty(0, false, true);
private final IntegerProperty measuredHeight = new IntegerProperty(0, false, true);
private final IntegerProperty clientWidth = new IntegerProperty(0, false, true);
private final IntegerProperty clientHeight = new IntegerProperty(0, false, true);
private final IntegerProperty boundsWidth = new IntegerProperty(0, false, true);
private final IntegerProperty boundsHeight = new IntegerProperty(0, false, true);
private final IntegerProperty boundsLeft = new IntegerProperty(0, false, true);
private final IntegerProperty boundsTop = new IntegerProperty(0, false, true);
private final IntegerProperty measuredWidthSetter = new IntegerProperty(0, false, false);
private final IntegerProperty measuredHeightSetter = new IntegerProperty(0, false, false);
private final IntegerProperty clientWidthSetter = new IntegerProperty(0, false, false);
private final IntegerProperty clientHeightSetter = new IntegerProperty(0, false, false);
private final IntegerProperty boundsWidthSetter = new IntegerProperty(0, false, false);
private final IntegerProperty boundsHeightSetter = new IntegerProperty(0, false, false);
private final IntegerProperty boundsLeftSetter = new IntegerProperty(0, false, false);
private final IntegerProperty boundsTopSetter = new IntegerProperty(0, false, false);
private final Property<ECursor> cursor = new Property<ECursor>(ECursor.AUTO, false, false);
private final BooleanProperty pointerTransparent = new BooleanProperty(false, false, false);
private final BooleanProperty handlePointer = new BooleanProperty(true, false, false);
private final BooleanProperty visible = new BooleanProperty(true, false, false);
private final BooleanProperty enabled = new BooleanProperty(true, false, false);
private final DoubleProperty alpha = new DoubleProperty(1.0, false, false);
private final BooleanProperty selectable = new BooleanProperty(false, false, false);
private final IntegerProperty minWidth = new IntegerProperty(null, true, false);
private final IntegerProperty minHeight = new IntegerProperty(null, true, false);
private final IntegerProperty maxWidth = new IntegerProperty(null, true, false);
private final IntegerProperty maxHeight = new IntegerProperty(null, true, false);
private final Event<ClickEventArgs> onClick = new Event<ClickEventArgs>();
private final Event<MouseDownEventArgs> onMouseDown = new Event<MouseDownEventArgs>();
private final Event<MouseDragEventArgs> onMouseDrag = new Event<MouseDragEventArgs>();
private final Event<MouseMoveEventArgs> onMouseMove = new Event<MouseMoveEventArgs>();
private final Event<MouseUpEventArgs> onMouseUp = new Event<MouseUpEventArgs>();
private final Event<EventArgs> onMouseEnter = new Event<EventArgs>();
private final Event<EventArgs> onMouseLeave = new Event<EventArgs>();
private final Event<MouseWheelEventArgs> onMouseWheel = new Event<MouseWheelEventArgs>();
private final Event<KeyEventArgs> onKeyDown = new Event<KeyEventArgs>();
private final Event<KeyEventArgs> onKeyPress = new Event<KeyEventArgs>();
private final Event<KeyEventArgs> onKeyUp = new Event<KeyEventArgs>();
private int left = 0;
private int top = 0;
private final Element element;
private ALayout parent;
boolean needsLayout = true;
private IChangeListener transformChangedListener = new IChangeListener() {
@Override
public void onChanged(Object sender) {
updateTransform();
requestLayout();
}
};
/**
* Creates a new instance of AComponet.
*
* @param rootElement
* The underlaying HTML element which this component wraps.
*/
public AComponent(Element rootElement) {
this.element = rootElement;
this.element.setAttribute("draggabe", "false");
this.element.getStyle().setPosition(Style.Position.ABSOLUTE);
//this.element.getStyle().setProperty("pointerEvents", "none");
this.element.getStyle().setProperty("pointerEvents", "all");
translateX.addChangeListener(transformChangedListener);
translateY.addChangeListener(transformChangedListener);
rotate.addChangeListener(transformChangedListener);
scaleX.addChangeListener(transformChangedListener);
scaleY.addChangeListener(transformChangedListener);
transformCenterX.addChangeListener(transformChangedListener);
transformCenterY.addChangeListener(transformChangedListener);
padding.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Padding p = padding.get();
if (p == null) {
getElement().getStyle().setPadding(0.0, Style.Unit.PX);
} else {
p.apply(getElement());
}
requestLayout();
}
});
border.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Border b = border.get();
if (b == null) {
getElement().getStyle().clearBorderStyle();
getElement().getStyle().clearBorderColor();
getElement().getStyle().clearBorderWidth();
+ getElement().getStyle().clearProperty("borderRadius");
} else {
b.apply(getElement());
}
requestLayout();
}
});
cursor.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setProperty("cursor", cursor.get().getCssValue());
}
});
visible.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (visible.get()) {
getElement().getStyle().setVisibility(Style.Visibility.VISIBLE);
} else {
getElement().getStyle().setVisibility(Style.Visibility.HIDDEN);
}
}
});
enabled.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (!enabled.get()) {
getElement().setAttribute("disabled", "true");
} else {
getElement().removeAttribute("disabled");
}
}
});
alpha.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setOpacity(alpha.get());
}
});
selectable.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (selectable.get()) {
getElement().getStyle().clearProperty("mozUserSelect");
getElement().getStyle().clearProperty("khtmlUserSelect");
getElement().getStyle().clearProperty("webkitUserSelect");
getElement().getStyle().clearProperty("msUserSelect");
getElement().getStyle().clearProperty("userSelect");
} else {
getElement().getStyle().setProperty("mozUserSelect", "none");
getElement().getStyle().setProperty("khtmlUserSelect", "none");
getElement().getStyle().setProperty("webkitUserSelect", "none");
getElement().getStyle().setProperty("msUserSelect", "none");
getElement().getStyle().setProperty("userSelect", "none");
}
}
});
selectable.invalidate();
minWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minWidth.get() == null) {
element.getStyle().clearProperty("minWidth");
} else {
element.getStyle().setProperty("minWidth", minWidth.get() + "px");
}
requestLayout();
}
});
minHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minHeight.get() == null) {
element.getStyle().clearProperty("minHeight");
} else {
element.getStyle().setProperty("minHeight", minHeight.get() + "px");
}
requestLayout();
}
});
maxWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxWidth.get() == null) {
element.getStyle().clearProperty("maxWidth");
} else {
element.getStyle().setProperty("maxWidth", maxWidth.get() + "px");
}
requestLayout();
}
});
maxHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxHeight.get() == null) {
element.getStyle().clearProperty("maxHeight");
} else {
element.getStyle().setProperty("maxHeight", maxHeight.get() + "px");
}
requestLayout();
}
});
measuredWidth.initReadonlyBind(measuredWidthSetter);
measuredHeight.initReadonlyBind(measuredHeightSetter);
clientWidth.initReadonlyBind(clientWidthSetter);
clientHeight.initReadonlyBind(clientHeightSetter);
boundsWidth.initReadonlyBind(boundsWidthSetter);
boundsHeight.initReadonlyBind(boundsHeightSetter);
boundsLeft.initReadonlyBind(boundsLeftSetter);
boundsTop.initReadonlyBind(boundsTopSetter);
DOM.setEventListener((com.google.gwt.user.client.Element) getElement(), nativeEventListener);
// sinking all the events
DOM.sinkEvents((com.google.gwt.user.client.Element) getElement(), -1);
}
private void updateTransform() {
double angle = rotate.get();
angle = angle - ((int) angle);
angle = angle * 360;
String angleStr = angle + "deg";
String centerX = (transformCenterX.get() * 100) + "%";
String centerY = (transformCenterY.get() * 100) + "%";
String sX = scaleX.get().toString();
String sY = scaleY.get().toString();
element.getStyle().setProperty("transformOrigin", centerX + " " + centerY);
element.getStyle().setProperty("transform", "translate(" + translateX.get() + "px, " + translateY.get() + "px) rotate(" + angleStr + ") scaleX( " + sX + ") scaleY(" + sY + ")");
element.getStyle().setProperty("msTransformOrigin", centerX + " " + centerY);
element.getStyle().setProperty("msTransform", "translate(" + translateX.get() + "px, " + translateY.get() + "px) rotate(" + angleStr + ") scaleX( " + sX + ") scaleY(" + sY + ")");
element.getStyle().setProperty("webkitTransformOrigin", centerX + " " + centerY);
element.getStyle().setProperty("webkitTransform", "translate(" + translateX.get() + "px, " + translateY.get() + "px) rotate(" + angleStr + ") scaleX( " + sX + ") scaleY(" + sY + ")");
}
/**
* Notifies the layout engine that this component may changed it's size, and the UI needs to re-layout.
*/
public void requestLayout() {
if (!this.needsLayout) {
this.needsLayout = true;
if (this.parent != null) {
this.parent.requestLayout();
}
}
}
/**
* Measures the dimensions of this component.
*/
public final void measure() {
onMeasure();
}
private void onMeasure() {
// calculating client bounds
int cw = element.getClientWidth();
int ch = element.getClientHeight();
Padding p = padding.get();
if (p != null) {
cw = cw - p.getLeftPadding() - p.getRightPadding();
ch = ch - p.getTopPadding() - p.getBottomPadding();
}
clientWidthSetter.set(cw);
clientHeightSetter.set(ch);
// calculating measured bounds
int mw = element.getOffsetWidth();
int mh = element.getOffsetHeight();
measuredWidthSetter.set(mw);
measuredHeightSetter.set(mh);
// calculating parent bounds
double tcx = transformCenterX.get();
double tcy = transformCenterY.get();
double sx = scaleX.get();
double sy = scaleY.get();
int bw = (int) (mw * sx);
int bh = (int) (mh * sy);
int bx = (int) (0 - ((bw - mw) * tcx));
int by = (int) (0 - ((bh - mh) * tcy));
double rot = rotate.get();
if (rot != 0.0) {
rot = rot * 360;
Point2D tr = rotatePoint(bw, 0, rot);
Point2D br = rotatePoint(bw, bh, rot);
Point2D bl = rotatePoint(0, bh, rot);
int minX = Math.min(Math.min(0, tr.getX()), Math.min(br.getX(), bl.getX()));
int minY = Math.min(Math.min(0, tr.getY()), Math.min(br.getY(), bl.getY()));
int maxX = Math.max(Math.max(0, tr.getX()), Math.max(br.getX(), bl.getX()));
int maxY = Math.max(Math.max(0, tr.getY()), Math.max(br.getY(), bl.getY()));
bw = maxX - minX;
bh = maxY - minY;
bx = minX;
by = minY;
}
boundsLeftSetter.set(bx);
boundsTopSetter.set(by);
boundsWidthSetter.set(bw);
boundsHeightSetter.set(bh);
}
private Point2D rotatePoint(int x, int y, double angle) {
angle = ((angle / 180) * Math.PI);
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
int resX = (int) ((x * cosAngle) - (y * sinAngle));
int resY = (int) ((x * sinAngle) + (y * cosAngle));
return new Point2D(resX, resY);
}
/**
* Returns the HTML element which is wrapped by this component.
*
* @return
* The HTML element which is wrapped by this component.
*/
public final Element getElement() {
return this.element;
}
/**
* Returns the parent layout of this component, or null if this components hasn't got any parent yet.
*
* @return
* The parent layout of this component.
*/
public final ALayout getParent() {
return parent;
}
final void setParent(ALayout parent) {
this.parent = parent;
}
/**
* Lays out this component. You can override this method to implement your own layout logic.
*/
public void layout() {
this.needsLayout = false;
measure();
}
/**
* Indicates if this component needs layout.
*
* @return
* True if this component needs layout, otherwise false.
*/
public final boolean isNeedsLayout() {
return needsLayout;
}
/**
* Returns the translateX property, which can be used to translate this component throught the x axis.
*
* @return
* The translateX property instance.
*/
public final IntegerProperty translateXProperty() {
return translateX;
}
/**
* Returns the translateY property, which can be used to translate this component throught the y axis.
*
* @return
* The translateY property instance.
*/
public final IntegerProperty translateYProperty() {
return translateY;
}
// public final DoubleProperty rotateProperty() {
// return rotate;
// }
//
// public final DoubleProperty scaleXProperty() {
// return scaleX;
// }
//
// public final DoubleProperty scaleYProperty() {
// return scaleY;
// }
//
// public final DoubleProperty transformCenterXProperty() {
// return transformCenterX;
// }
//
// public final DoubleProperty transformCenterYProperty() {
// return transformCenterY;
// }
/**
* Returns the padding property instance which can be used to control the padding of this component.
*
* @return
* The padding property instance.
*/
protected PaddingProperty paddingProperty() {
return padding;
}
/**
* Returns the border property instance which can be used to control the border of this component.
*
* @return
* The border property instance.
*/
protected BorderProperty borderProperty() {
return border;
}
/**
* Returns the read-only measured width property instance. The measured width property stores the untransformed width
* of this component, including padding and border.
*
* @return
* The read-only measured width property instance.
*/
public final IntegerProperty measuredWidthProperty() {
return measuredWidth;
}
/**
* Returns the read-only measured height property instance. The measured height property stores the untransformed height
* of this component, including padding and border.
*
* @return
* The read-only measured height property instance.
*/
public final IntegerProperty measuredHeightProperty() {
return measuredHeight;
}
/**
* Returns the read-only client width property instance. The client width property stores the untransformed width
* of this component, excluding padding and border..
*
* @return
* The read-only client width property instance.
*/
public final IntegerProperty clientWidthProperty() {
return clientWidth;
}
/**
* Returns the read-only client height property instance. The client height property stores the untransformed height
* of this component, excluding padding and border.
*
* @return
* The read-only client height property instance.
*/
public final IntegerProperty clientHeightProperty() {
return clientHeight;
}
/**
* Returns the read-only bounds width property instance. The nounds width property stores the width of this component's
* transformed bounding box.
*
* @return
* The read-only bounds width property instance.
*/
public final IntegerProperty boundsWidthProperty() {
return boundsWidth;
}
/**
* Returns the read-only bounds height property instance. The bounds height property stores the height of this component's
* transformed bounding box.
*
* @return
* The read-only bounds height property instance.
*/
public final IntegerProperty boundsHeightProperty() {
return boundsHeight;
}
public final IntegerProperty boundsLeftProperty() {
return boundsLeft;
}
public final IntegerProperty boundsTopProperty() {
return boundsTop;
}
/**
* Returns the minWidth property instance which can be used to control this component's minimum width.
*
* @return
* The minWidth property instance.
*/
protected IntegerProperty minWidthProperty() {
return minWidth;
}
/**
* Returns the minHeight property instance which can be used to control this component's minimum height.
*
* @return
* The minHeight property instance.
*/
protected IntegerProperty minHeightProperty() {
return minHeight;
}
/**
* Returns the maxWidth property instance which can be used to control this component's maximum width.
*
* @return
* The maxWidth property instance.
*/
protected IntegerProperty maxWidthProperty() {
return maxWidth;
}
/**
* Returns the maxHeight property instance which can be used to control this component's maximum height.
*
* @return
* The MaxHeight property instance.
*/
protected IntegerProperty maxHeightProperty() {
return maxHeight;
}
/**
* Sets the base position of this component relative to the parent's top-left corner.
* This method is called from a layout's onLayout method to set the base position
* of this component.
*
* @param left
* The left base position of this component relative to the parents top-left corner.
* @param top
* The top base position of this component relative to the parents top-left corner.
*/
protected final void setPosition(int left, int top) {
getElement().getStyle().setLeft(left, Style.Unit.PX);
getElement().getStyle().setTop(top, Style.Unit.PX);
this.left = left;
this.top = top;
}
/**
* Sets the base left position of this component relative to the parent's top-left corner.
* This method is called from a layout's onLayout method to set the base left position
* of this component.
*
* @param left
* The left base position of this component relative to the parents top-left corner.
*/
protected final void setLeft(int left) {
getElement().getStyle().setLeft(left, Style.Unit.PX);
this.left = left;
}
/**
* Sets the base top position of this component relative to the parent's top-left corner.
* This method is called from a layout's onLayout method to set the base top position
* of this component.
*
* @param top
* The top base position of this component relative to the parents top-left corner.
*/
protected final void setTop(int top) {
getElement().getStyle().setTop(top, Style.Unit.PX);
this.top = top;
}
/**
* Sets the size of this component. This method can be called when a dynamically sized component's size is calculated.
* Typically from the onLayout method.
*
* @param width
* The width of this component.
* @param height
* The height of this component.
*/
protected final void setSize(int width, int height) {
getElement().getStyle().setWidth(width, Style.Unit.PX);
getElement().getStyle().setHeight(height, Style.Unit.PX);
}
public final Property<ECursor> cursorProperty() {
return cursor;
}
public final BooleanProperty pointerTransparentProperty() {
return pointerTransparent;
}
public final BooleanProperty visibleProperty() {
return visible;
}
public final Event<ClickEventArgs> onClickEvent() {
return onClick;
}
public final Event<MouseDownEventArgs> onMouseDownEvent() {
return onMouseDown;
}
public final Event<MouseDragEventArgs> onMouseDragEvent() {
return onMouseDrag;
}
public final Event<MouseMoveEventArgs> onMouseMoveEvent() {
return onMouseMove;
}
public final Event<MouseUpEventArgs> onMouseUpEvent() {
return onMouseUp;
}
public final Event<EventArgs> onMouseEnterEvent() {
return onMouseEnter;
}
public final Event<EventArgs> onMouseLeaveEvent() {
return onMouseLeave;
}
public final Event<MouseWheelEventArgs> onMouseWheelEvent() {
return onMouseWheel;
}
public final Event<KeyEventArgs> onKeyDownEvent() {
return onKeyDown;
}
public final Event<KeyEventArgs> onKeyPressEvent() {
return onKeyPress;
}
public final Event<KeyEventArgs> onKeyUpEvent() {
return onKeyUp;
}
public final DoubleProperty alphaProperty() {
return alpha;
}
public final BooleanProperty handlePointerProperty() {
return handlePointer;
}
public final BooleanProperty enabledProperty() {
return enabled;
}
public final int getLeft() {
return left;
}
public final int getTop() {
return top;
}
protected BooleanProperty selectableProperty() {
return selectable;
}
/**
* This method is called by the parent of this component when a pointer event is occured. The goal of this method is
* to decide if this component wants to handle the event or not, and delegate the event to child components if
* needed.
*
* @param screenX The x coordinate of the pointer relative to the screen's top-left corner.
* @param screenY The y coordinate of the pointer relative to the screen's top-left corner.
* @param parentScreenX The x coordinate of the pointer relative to the parent's top-left corner.
* @param parentScreenY The y coordinate of the pointer relative to the parent's top-left corner.
* @param x The x coordinate of the pointer relative to this component's top-left corner.
* @param y The y coordinate of the pointer relative to this component's top-left corner.
* @param wheelVelocity The mouse wheel velocity value.
* @param type The type of the event. Valid values are listed in PointerEventArgs class.
* @param altPressed Indicates if the alt key is pressed when the event occured or not.
* @param ctrlPressed Indicates if the ctrl key is pressed when the event occured or not.
* @param shiftPressed Indicates if the shift key is pressed when the event occured or not.
* @param metaPressed Indicates if the meta key is pressed when the event occured or not.
*
* @return True if the event is fully handled and underlaying components can't handle this event, otherwise false if
* underlaying components can handle this event.
*/
boolean doPointerEventClimbingUp(int screenX, int screenY, int x, int y, int wheelVelocity,
boolean altPressed, boolean ctrlPressed, boolean shiftPressed, boolean metaPressed, int type) {
if (!handlePointer.get()) {
return false;
}
if (pointerTransparent.get()) {
return false;
}
if (!enabled.get()) {
return true;
}
if (!visible.get()) {
return false;
}
onPointerEventClimbingUp(screenX, screenY, x, y, wheelVelocity, altPressed,
ctrlPressed, shiftPressed, metaPressed, type);
return onPointerEventFallingDown(screenX, screenY, x, y, wheelVelocity, altPressed,
ctrlPressed, shiftPressed, metaPressed, type);
}
// boolean doPointerEventFallingDown(int screenX, int screenY, int parentScreenX, int parentScreenY,
// int x, int y, int wheelVelocity, boolean altPressed, boolean ctrlPressed, boolean shiftPressed,
// boolean metaPressed, int type) {
// return onPointerEventFallingDown(screenX, screenY, parentScreenX, parentScreenY, x, y, wheelVelocity, altPressed,
// ctrlPressed, shiftPressed, metaPressed, type);
// }
/**
* This method is called when a pointer event is climbing up on the component hierarchy. The goal of this method is
* to decide if the event can reach child components or not. In the most of the cases you don't need to overwrite
* this method. The default implementation is returns true.
*
* @param screenX The x coordinate of the pointer relative to the screen's top-left corner.
* @param screenY The y coordinate of the pointer relative to the screen's top-left corner.
* @param parentScreenX The x coordinate of the pointer relative to the parent's top-left corner.
* @param parentScreenY The y coordinate of the pointer relative to the parent's top-left corner.
* @param x The x coordinate of the pointer relative to this component's top-left corner.
* @param y The y coordinate of the pointer relative to this component's top-left corner.
* @param wheelVelocity The mouse wheel velocity value.
* @param type The type of the event. Valid values are listed in PointerEventArgs class.
* @param altPressed Indicates if the alt key is pressed when the event occured or not.
* @param ctrlPressed Indicates if the ctrl key is pressed when the event occured or not.
* @param shiftPressed Indicates if the shift key is pressed when the event occured or not.
* @param metaPressed Indicates if the meta key is pressed when the event occured or not.
*
* @return False if this event can't reach overlaying components, or true if overlaying components can also get the
* climbing up event.
*/
protected boolean onPointerEventClimbingUp(int screenX, int screenY, int x, int y, int wheelVelocity,
boolean altPressed, boolean ctrlPressed, boolean shiftPressed, boolean metaPressed, int type) {
return true;
}
/**
* This method is called when a pointer event is falling down on the component hierarchy. The goal of this method is
* to fire events if needed, and in the result type define if the underlaying components can process this event too.
* The default implementation is fires the associated event, and returns true.
*
* @param screenX The x coordinate of the pointer relative to the screen's top-left corner.
* @param screenY The y coordinate of the pointer relative to the screen's top-left corner.
* @param parentScreenX The x coordinate of the pointer relative to the parent's top-left corner.
* @param parentScreenY The y coordinate of the pointer relative to the parent's top-left corner.
* @param x The x coordinate of the pointer relative to this component's top-left corner.
* @param y The y coordinate of the pointer relative to this component's top-left corner.
* @param wheelVelocity The mouse wheel velocity value.
* @param type The type of the event. Valid values are listed in PointerEventArgs class.
* @param altPressed Indicates if the alt key is pressed when the event occured or not.
* @param ctrlPressed Indicates if the ctrl key is pressed when the event occured or not.
* @param shiftPressed Indicates if the shift key is pressed when the event occured or not.
* @param metaPressed Indicates if the meta key is pressed when the event occured or not.
*
* @return True if this event is fully processed, and underlaying components can't process this event, or false if
* underlaying components can also get the falling down event.
*/
protected boolean onPointerEventFallingDown(int screenX, int screenY, int x, int y, int wheelVelocity,
boolean altPressed, boolean ctrlPressed, boolean shiftPressed, boolean metaPressed, int type) {
switch (type) {
case MouseEventTypes.TYPE_MOUSE_DOWN:
MouseDownEventArgs mdea = new MouseDownEventArgs(screenX, screenY, x, y, altPressed, ctrlPressed, shiftPressed, metaPressed, this);
registerDownEvent(screenX, screenY, x, y, altPressed, ctrlPressed, shiftPressed, metaPressed);
onMouseDown.fireEvent(mdea);
break;
case MouseEventTypes.TYPE_MOUSE_MOVE:
MouseMoveEventArgs mmea = new MouseMoveEventArgs(screenX, screenY, x, y, altPressed, ctrlPressed, shiftPressed, metaPressed, this);
onMouseMove.fireEvent(mmea);
break;
case MouseEventTypes.TYPE_MOUSE_ENTER:
onMouseEnter.fireEvent(new EventArgs(this));
break;
case MouseEventTypes.TYPE_MOUSE_LEAVE:
onMouseLeave.fireEvent(new EventArgs(this));
break;
case MouseEventTypes.TYPE_MOUSE_WHEEL:
onMouseWheel.fireEvent(new MouseWheelEventArgs(wheelVelocity, altPressed, ctrlPressed, shiftPressed, metaPressed, this));
break;
}
return true;
}
protected final void registerDownEvent(int screenX, int screenY, int x, int y, boolean altPressed, boolean ctrlPressed,
boolean shiftPressed, boolean metaPressed) {
logPointerDownEvent(new MouseDownEventLog(this, x, y, screenX, screenY));
}
/**
* Indicates if this component is intersects the given point. The x and y coordinate is relative to the parent's
* top-left coordinate.
*
* @param x The x coordinate of the point.
* @param y The y coordinate of the point.
*
* @return True if this component is intersects the given point, otherwise false.
*/
boolean isIntersectsPoint(int x, int y) {
// measured positions
int x1 = left + translateX.get();
int y1 = top + translateY.get();
int x2 = x1 + measuredWidth.get();
int y2 = y1;
int x3 = x2;
int y3 = y2 + measuredHeight.get();
int x4 = x1;
int y4 = y3;
// scale points
if (scaleX.get() != 1.0) {
x1 = (int) (x1 - ((x2 - x1) * transformCenterX.get() * scaleX.get()));
x2 = (int) (x1 + ((x2 - x1) * (1 - transformCenterX.get()) * scaleX.get()));
x3 = x2;
x4 = x1;
}
if (scaleY.get() != 1.0) {
y1 = (int) (y1 - ((y2 - y1) * transformCenterY.get() * scaleY.get()));
y4 = (int) (y4 + ((y4 - y1) * (1 - transformCenterY.get()) * scaleY.get()));
y2 = y1;
y3 = y4;
}
// rotatePoints
if (rotate.get() != 1.0) {
int rpx = (int) ((x2 - x1) * transformCenterX.get());
int rpy = (int) ((y4 - y1) * transformCenterX.get());
Point2D tl = rotatePoint(x1 - rpx, y1 - rpy, rotate.get());
Point2D tr = rotatePoint(x2 - rpx, y2 - rpy, rotate.get());
Point2D br = rotatePoint(x3 - rpx, y3 - rpy, rotate.get());
Point2D bl = rotatePoint(x4 - rpx, y4 - rpy, rotate.get());
x1 = tl.getX() + rpx;
y1 = tl.getY() + rpy;
x2 = tr.getX() + rpx;
y2 = tr.getY() + rpy;
x3 = br.getX() + rpx;
y3 = br.getY() + rpy;
x4 = bl.getX() + rpx;
y4 = bl.getY() + rpy;
}
int cnt = 0;
if (isPointIntersectsLine(x, y, x1, y1, x2, y2)) {
cnt++;
}
if (isPointIntersectsLine(x, y, x2, y2, x3, y3)) {
cnt++;
}
if (isPointIntersectsLine(x, y, x3, y3, x4, y4)) {
cnt++;
}
if (isPointIntersectsLine(x, y, x4, y4, x1, y1)) {
cnt++;
}
return cnt == 1 || cnt == 3;
}
private boolean isPointIntersectsLine(int px, int py, int lx1, int ly1, int lx2, int ly2) {
/* ((poly[i][1] > y) != (poly[j][1] > y)) and \
(x < (poly[j][0] - poly[i][0]) * (y - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
*/
return ((ly1 > py) != (ly2 > py)) && (px < (lx2 - lx1) * ((double) (py - ly1)) / (ly2 - ly1) + lx1);
}
}
| true | true | public AComponent(Element rootElement) {
this.element = rootElement;
this.element.setAttribute("draggabe", "false");
this.element.getStyle().setPosition(Style.Position.ABSOLUTE);
//this.element.getStyle().setProperty("pointerEvents", "none");
this.element.getStyle().setProperty("pointerEvents", "all");
translateX.addChangeListener(transformChangedListener);
translateY.addChangeListener(transformChangedListener);
rotate.addChangeListener(transformChangedListener);
scaleX.addChangeListener(transformChangedListener);
scaleY.addChangeListener(transformChangedListener);
transformCenterX.addChangeListener(transformChangedListener);
transformCenterY.addChangeListener(transformChangedListener);
padding.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Padding p = padding.get();
if (p == null) {
getElement().getStyle().setPadding(0.0, Style.Unit.PX);
} else {
p.apply(getElement());
}
requestLayout();
}
});
border.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Border b = border.get();
if (b == null) {
getElement().getStyle().clearBorderStyle();
getElement().getStyle().clearBorderColor();
getElement().getStyle().clearBorderWidth();
} else {
b.apply(getElement());
}
requestLayout();
}
});
cursor.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setProperty("cursor", cursor.get().getCssValue());
}
});
visible.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (visible.get()) {
getElement().getStyle().setVisibility(Style.Visibility.VISIBLE);
} else {
getElement().getStyle().setVisibility(Style.Visibility.HIDDEN);
}
}
});
enabled.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (!enabled.get()) {
getElement().setAttribute("disabled", "true");
} else {
getElement().removeAttribute("disabled");
}
}
});
alpha.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setOpacity(alpha.get());
}
});
selectable.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (selectable.get()) {
getElement().getStyle().clearProperty("mozUserSelect");
getElement().getStyle().clearProperty("khtmlUserSelect");
getElement().getStyle().clearProperty("webkitUserSelect");
getElement().getStyle().clearProperty("msUserSelect");
getElement().getStyle().clearProperty("userSelect");
} else {
getElement().getStyle().setProperty("mozUserSelect", "none");
getElement().getStyle().setProperty("khtmlUserSelect", "none");
getElement().getStyle().setProperty("webkitUserSelect", "none");
getElement().getStyle().setProperty("msUserSelect", "none");
getElement().getStyle().setProperty("userSelect", "none");
}
}
});
selectable.invalidate();
minWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minWidth.get() == null) {
element.getStyle().clearProperty("minWidth");
} else {
element.getStyle().setProperty("minWidth", minWidth.get() + "px");
}
requestLayout();
}
});
minHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minHeight.get() == null) {
element.getStyle().clearProperty("minHeight");
} else {
element.getStyle().setProperty("minHeight", minHeight.get() + "px");
}
requestLayout();
}
});
maxWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxWidth.get() == null) {
element.getStyle().clearProperty("maxWidth");
} else {
element.getStyle().setProperty("maxWidth", maxWidth.get() + "px");
}
requestLayout();
}
});
maxHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxHeight.get() == null) {
element.getStyle().clearProperty("maxHeight");
} else {
element.getStyle().setProperty("maxHeight", maxHeight.get() + "px");
}
requestLayout();
}
});
measuredWidth.initReadonlyBind(measuredWidthSetter);
measuredHeight.initReadonlyBind(measuredHeightSetter);
clientWidth.initReadonlyBind(clientWidthSetter);
clientHeight.initReadonlyBind(clientHeightSetter);
boundsWidth.initReadonlyBind(boundsWidthSetter);
boundsHeight.initReadonlyBind(boundsHeightSetter);
boundsLeft.initReadonlyBind(boundsLeftSetter);
boundsTop.initReadonlyBind(boundsTopSetter);
DOM.setEventListener((com.google.gwt.user.client.Element) getElement(), nativeEventListener);
// sinking all the events
DOM.sinkEvents((com.google.gwt.user.client.Element) getElement(), -1);
}
| public AComponent(Element rootElement) {
this.element = rootElement;
this.element.setAttribute("draggabe", "false");
this.element.getStyle().setPosition(Style.Position.ABSOLUTE);
//this.element.getStyle().setProperty("pointerEvents", "none");
this.element.getStyle().setProperty("pointerEvents", "all");
translateX.addChangeListener(transformChangedListener);
translateY.addChangeListener(transformChangedListener);
rotate.addChangeListener(transformChangedListener);
scaleX.addChangeListener(transformChangedListener);
scaleY.addChangeListener(transformChangedListener);
transformCenterX.addChangeListener(transformChangedListener);
transformCenterY.addChangeListener(transformChangedListener);
padding.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Padding p = padding.get();
if (p == null) {
getElement().getStyle().setPadding(0.0, Style.Unit.PX);
} else {
p.apply(getElement());
}
requestLayout();
}
});
border.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
Border b = border.get();
if (b == null) {
getElement().getStyle().clearBorderStyle();
getElement().getStyle().clearBorderColor();
getElement().getStyle().clearBorderWidth();
getElement().getStyle().clearProperty("borderRadius");
} else {
b.apply(getElement());
}
requestLayout();
}
});
cursor.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setProperty("cursor", cursor.get().getCssValue());
}
});
visible.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (visible.get()) {
getElement().getStyle().setVisibility(Style.Visibility.VISIBLE);
} else {
getElement().getStyle().setVisibility(Style.Visibility.HIDDEN);
}
}
});
enabled.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (!enabled.get()) {
getElement().setAttribute("disabled", "true");
} else {
getElement().removeAttribute("disabled");
}
}
});
alpha.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
getElement().getStyle().setOpacity(alpha.get());
}
});
selectable.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (selectable.get()) {
getElement().getStyle().clearProperty("mozUserSelect");
getElement().getStyle().clearProperty("khtmlUserSelect");
getElement().getStyle().clearProperty("webkitUserSelect");
getElement().getStyle().clearProperty("msUserSelect");
getElement().getStyle().clearProperty("userSelect");
} else {
getElement().getStyle().setProperty("mozUserSelect", "none");
getElement().getStyle().setProperty("khtmlUserSelect", "none");
getElement().getStyle().setProperty("webkitUserSelect", "none");
getElement().getStyle().setProperty("msUserSelect", "none");
getElement().getStyle().setProperty("userSelect", "none");
}
}
});
selectable.invalidate();
minWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minWidth.get() == null) {
element.getStyle().clearProperty("minWidth");
} else {
element.getStyle().setProperty("minWidth", minWidth.get() + "px");
}
requestLayout();
}
});
minHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (minHeight.get() == null) {
element.getStyle().clearProperty("minHeight");
} else {
element.getStyle().setProperty("minHeight", minHeight.get() + "px");
}
requestLayout();
}
});
maxWidth.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxWidth.get() == null) {
element.getStyle().clearProperty("maxWidth");
} else {
element.getStyle().setProperty("maxWidth", maxWidth.get() + "px");
}
requestLayout();
}
});
maxHeight.addChangeListener(new IChangeListener() {
@Override
public void onChanged(Object sender) {
if (maxHeight.get() == null) {
element.getStyle().clearProperty("maxHeight");
} else {
element.getStyle().setProperty("maxHeight", maxHeight.get() + "px");
}
requestLayout();
}
});
measuredWidth.initReadonlyBind(measuredWidthSetter);
measuredHeight.initReadonlyBind(measuredHeightSetter);
clientWidth.initReadonlyBind(clientWidthSetter);
clientHeight.initReadonlyBind(clientHeightSetter);
boundsWidth.initReadonlyBind(boundsWidthSetter);
boundsHeight.initReadonlyBind(boundsHeightSetter);
boundsLeft.initReadonlyBind(boundsLeftSetter);
boundsTop.initReadonlyBind(boundsTopSetter);
DOM.setEventListener((com.google.gwt.user.client.Element) getElement(), nativeEventListener);
// sinking all the events
DOM.sinkEvents((com.google.gwt.user.client.Element) getElement(), -1);
}
|
diff --git a/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java b/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
index 29c64a8..dc206a9 100644
--- a/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
+++ b/src/com/android/bluetooth/pbap/BluetoothPbapVcardManager.java
@@ -1,585 +1,586 @@
/*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* 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 Motorola, Inc. nor the names of its 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 HOLDER 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 com.android.bluetooth.pbap;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.Log;
import com.android.bluetooth.R;
import com.android.vcard.VCardComposer;
import com.android.vcard.VCardConfig;
import com.android.vcard.VCardComposer.OneEntryHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.obex.ServerOperation;
import javax.obex.Operation;
import javax.obex.ResponseCodes;
public class BluetoothPbapVcardManager {
private static final String TAG = "BluetoothPbapVcardManager";
private static final boolean V = BluetoothPbapService.VERBOSE;
private ContentResolver mResolver;
private Context mContext;
private StringBuilder mVcardResults = null;
static final String[] PHONES_PROJECTION = new String[] {
Data._ID, // 0
CommonDataKinds.Phone.TYPE, // 1
CommonDataKinds.Phone.LABEL, // 2
CommonDataKinds.Phone.NUMBER, // 3
Contacts.DISPLAY_NAME, // 4
};
private static final int ID_COLUMN_INDEX = 0;
private static final int PHONE_TYPE_COLUMN_INDEX = 1;
private static final int PHONE_LABEL_COLUMN_INDEX = 2;
private static final int PHONE_NUMBER_COLUMN_INDEX = 3;
private static final int CONTACTS_DISPLAY_NAME_COLUMN_INDEX = 4;
static final String SORT_ORDER_PHONE_NUMBER = CommonDataKinds.Phone.NUMBER + " ASC";
static final String[] CONTACTS_PROJECTION = new String[] {
Contacts._ID, // 0
Contacts.DISPLAY_NAME, // 1
};
static final int CONTACTS_ID_COLUMN_INDEX = 0;
static final int CONTACTS_NAME_COLUMN_INDEX = 1;
// call histories use dynamic handles, and handles should order by date; the
// most recently one should be the first handle. In table "calls", _id and
// date are consistent in ordering, to implement simply, we sort by _id
// here.
static final String CALLLOG_SORT_ORDER = Calls._ID + " DESC";
private static final String CLAUSE_ONLY_VISIBLE = Contacts.IN_VISIBLE_GROUP + "=1";
public BluetoothPbapVcardManager(final Context context) {
mContext = context;
mResolver = mContext.getContentResolver();
}
public final String getOwnerPhoneNumberVcard(final boolean vcardType21) {
BluetoothPbapCallLogComposer composer = new BluetoothPbapCallLogComposer(mContext, false);
String name = BluetoothPbapService.getLocalPhoneName();
String number = BluetoothPbapService.getLocalPhoneNum();
String vcard = composer.composeVCardForPhoneOwnNumber(Phone.TYPE_MOBILE, name, number,
vcardType21);
return vcard;
}
public final int getPhonebookSize(final int type) {
int size;
switch (type) {
case BluetoothPbapObexServer.ContentType.PHONEBOOK:
size = getContactsSize();
break;
default:
size = getCallHistorySize(type);
break;
}
if (V) Log.v(TAG, "getPhonebookSzie size = " + size + " type = " + type);
return size;
}
public final int getContactsSize() {
final Uri myUri = Contacts.CONTENT_URI;
int size = 0;
Cursor contactCursor = null;
try {
contactCursor = mResolver.query(myUri, null, CLAUSE_ONLY_VISIBLE, null, null);
if (contactCursor != null) {
size = contactCursor.getCount() + 1; // always has the 0.vcf
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
return size;
}
public final int getCallHistorySize(final int type) {
final Uri myUri = CallLog.Calls.CONTENT_URI;
String selection = BluetoothPbapObexServer.createSelectionPara(type);
int size = 0;
Cursor callCursor = null;
try {
callCursor = mResolver.query(myUri, null, selection, null,
CallLog.Calls.DEFAULT_SORT_ORDER);
if (callCursor != null) {
size = callCursor.getCount();
}
} finally {
if (callCursor != null) {
callCursor.close();
}
}
return size;
}
public final ArrayList<String> loadCallHistoryList(final int type) {
final Uri myUri = CallLog.Calls.CONTENT_URI;
String selection = BluetoothPbapObexServer.createSelectionPara(type);
String[] projection = new String[] {
Calls.NUMBER, Calls.CACHED_NAME
};
final int CALLS_NUMBER_COLUMN_INDEX = 0;
final int CALLS_NAME_COLUMN_INDEX = 1;
Cursor callCursor = null;
ArrayList<String> list = new ArrayList<String>();
try {
callCursor = mResolver.query(myUri, projection, selection, null,
CALLLOG_SORT_ORDER);
if (callCursor != null) {
for (callCursor.moveToFirst(); !callCursor.isAfterLast();
callCursor.moveToNext()) {
String name = callCursor.getString(CALLS_NAME_COLUMN_INDEX);
if (TextUtils.isEmpty(name)) {
// name not found,use number instead
name = callCursor.getString(CALLS_NUMBER_COLUMN_INDEX);
}
list.add(name);
}
}
} finally {
if (callCursor != null) {
callCursor.close();
}
}
return list;
}
public final ArrayList<String> getPhonebookNameList(final int orderByWhat) {
ArrayList<String> nameList = new ArrayList<String>();
nameList.add(BluetoothPbapService.getLocalPhoneName());
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
try {
if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_INDEXED) {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts._ID);
} else if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL) {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts.DISPLAY_NAME);
}
if (contactCursor != null) {
for (contactCursor.moveToFirst(); !contactCursor.isAfterLast(); contactCursor
.moveToNext()) {
String name = contactCursor.getString(CONTACTS_NAME_COLUMN_INDEX);
if (TextUtils.isEmpty(name)) {
name = mContext.getString(android.R.string.unknownName);
}
nameList.add(name);
}
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
return nameList;
}
public final ArrayList<String> getPhonebookNumberList() {
ArrayList<String> numberList = new ArrayList<String>();
numberList.add(BluetoothPbapService.getLocalPhoneNum());
final Uri myUri = Phone.CONTENT_URI;
Cursor phoneCursor = null;
try {
phoneCursor = mResolver.query(myUri, PHONES_PROJECTION, CLAUSE_ONLY_VISIBLE, null,
SORT_ORDER_PHONE_NUMBER);
if (phoneCursor != null) {
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor
.moveToNext()) {
String number = phoneCursor.getString(PHONE_NUMBER_COLUMN_INDEX);
if (TextUtils.isEmpty(number)) {
number = mContext.getString(R.string.defaultnumber);
}
numberList.add(number);
}
}
} finally {
if (phoneCursor != null) {
phoneCursor.close();
}
}
return numberList;
}
public final int composeAndSendCallLogVcards(final int type, Operation op,
final int startPoint, final int endPoint, final boolean vcardType21) {
if (startPoint < 1 || startPoint > endPoint) {
Log.e(TAG, "internal error: startPoint or endPoint is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
String typeSelection = BluetoothPbapObexServer.createSelectionPara(type);
final Uri myUri = CallLog.Calls.CONTENT_URI;
final String[] CALLLOG_PROJECTION = new String[] {
CallLog.Calls._ID, // 0
};
final int ID_COLUMN_INDEX = 0;
Cursor callsCursor = null;
long startPointId = 0;
long endPointId = 0;
try {
// Need test to see if order by _ID is ok here, or by date?
callsCursor = mResolver.query(myUri, CALLLOG_PROJECTION, typeSelection, null,
CALLLOG_SORT_ORDER);
if (callsCursor != null) {
callsCursor.moveToPosition(startPoint - 1);
startPointId = callsCursor.getLong(ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Call Log query startPointId = " + startPointId);
if (startPoint == endPoint) {
endPointId = startPointId;
} else {
callsCursor.moveToPosition(endPoint - 1);
endPointId = callsCursor.getLong(ID_COLUMN_INDEX);
}
if (V) Log.v(TAG, "Call log query endPointId = " + endPointId);
}
} finally {
if (callsCursor != null) {
callsCursor.close();
}
}
String recordSelection;
if (startPoint == endPoint) {
recordSelection = Calls._ID + "=" + startPointId;
} else {
// The query to call table is by "_id DESC" order, so change
// correspondingly.
recordSelection = Calls._ID + ">=" + endPointId + " AND " + Calls._ID + "<="
+ startPointId;
}
String selection;
if (typeSelection == null) {
selection = recordSelection;
} else {
selection = "(" + typeSelection + ") AND (" + recordSelection + ")";
}
if (V) Log.v(TAG, "Call log query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, null, false);
}
public final int composeAndSendPhonebookVcards(Operation op, final int startPoint,
final int endPoint, final boolean vcardType21, String ownerVCard) {
if (startPoint < 1 || startPoint > endPoint) {
Log.e(TAG, "internal error: startPoint or endPoint is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
long startPointId = 0;
long endPointId = 0;
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE, null,
Contacts._ID);
if (contactCursor != null) {
contactCursor.moveToPosition(startPoint - 1);
startPointId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + startPointId);
if (startPoint == endPoint) {
endPointId = startPointId;
} else {
contactCursor.moveToPosition(endPoint - 1);
endPointId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
}
if (V) Log.v(TAG, "Query endPointId = " + endPointId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
final String selection;
if (startPoint == endPoint) {
selection = Contacts._ID + "=" + startPointId + " AND " + CLAUSE_ONLY_VISIBLE;
} else {
selection = Contacts._ID + ">=" + startPointId + " AND " + Contacts._ID + "<="
+ endPointId + " AND " + CLAUSE_ONLY_VISIBLE;
}
if (V) Log.v(TAG, "Query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, ownerVCard, true);
}
public final int composeAndSendPhonebookOneVcard(Operation op, final int offset,
final boolean vcardType21, String ownerVCard, int orderByWhat) {
if (offset < 1) {
Log.e(TAG, "Internal error: offset is not correct.");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
final Uri myUri = Contacts.CONTENT_URI;
Cursor contactCursor = null;
String selection = null;
long contactId = 0;
if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_INDEXED) {
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts._ID);
if (contactCursor != null) {
contactCursor.moveToPosition(offset - 1);
contactId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + contactId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
} else if (orderByWhat == BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL) {
try {
contactCursor = mResolver.query(myUri, CONTACTS_PROJECTION, CLAUSE_ONLY_VISIBLE,
null, Contacts.DISPLAY_NAME);
if (contactCursor != null) {
contactCursor.moveToPosition(offset - 1);
contactId = contactCursor.getLong(CONTACTS_ID_COLUMN_INDEX);
if (V) Log.v(TAG, "Query startPointId = " + contactId);
}
} finally {
if (contactCursor != null) {
contactCursor.close();
}
}
} else {
Log.e(TAG, "Parameter orderByWhat is not supported!");
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
selection = Contacts._ID + "=" + contactId;
if (V) Log.v(TAG, "Query selection is: " + selection);
return composeAndSendVCards(op, selection, vcardType21, ownerVCard, true);
}
public final int composeAndSendVCards(Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC;
}
+ vcardType |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT;
vcardType |= VCardConfig.FLAG_REFRAIN_PHONE_NUMBER_FORMATTING;
composer = new VCardComposer(mContext, vcardType, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
/**
* Handler to emit VCard String to PCE once size grow to maxPacketSize.
*/
public class HandlerForStringBuffer implements OneEntryHandler {
@SuppressWarnings("hiding")
private Operation operation;
private OutputStream outputStream;
private int maxPacketSize;
private String phoneOwnVCard = null;
public HandlerForStringBuffer(Operation op, String ownerVCard) {
operation = op;
maxPacketSize = operation.getMaxPacketSize();
if (V) Log.v(TAG, "getMaxPacketSize() = " + maxPacketSize);
if (ownerVCard != null) {
phoneOwnVCard = ownerVCard;
if (V) Log.v(TAG, "phone own number vcard:");
if (V) Log.v(TAG, phoneOwnVCard);
}
}
public boolean onInit(Context context) {
try {
outputStream = operation.openOutputStream();
mVcardResults = new StringBuilder();
if (phoneOwnVCard != null) {
mVcardResults.append(phoneOwnVCard);
}
} catch (IOException e) {
Log.e(TAG, "open outputstrem failed" + e.toString());
return false;
}
if (V) Log.v(TAG, "openOutputStream() ok.");
return true;
}
public boolean onEntryCreated(String vcard) {
int vcardLen = vcard.length();
if (V) Log.v(TAG, "The length of this vcard is: " + vcardLen);
mVcardResults.append(vcard);
int vcardByteLen = mVcardResults.toString().getBytes().length;
if (V) Log.v(TAG, "The byte length of this vcardResults is: " + vcardByteLen);
if (vcardByteLen >= maxPacketSize) {
long timestamp = 0;
int position = 0;
// Need while loop to handle the big vcard case
while (!BluetoothPbapObexServer.sIsAborted
&& position < (vcardByteLen - maxPacketSize)) {
if (V) timestamp = System.currentTimeMillis();
String subStr = mVcardResults.toString().substring(position,
position + maxPacketSize);
try {
outputStream.write(subStr.getBytes(), 0, maxPacketSize);
} catch (IOException e) {
Log.e(TAG, "write outputstrem failed" + e.toString());
return false;
}
if (V) Log.v(TAG, "Sending vcard String " + maxPacketSize + " bytes took "
+ (System.currentTimeMillis() - timestamp) + " ms");
position += maxPacketSize;
}
mVcardResults.delete(0, position);
}
return true;
}
public void onTerminate() {
// Send out last packet
byte[] lastBytes = mVcardResults.toString().getBytes();
try {
outputStream.write(lastBytes, 0, lastBytes.length);
} catch (IOException e) {
Log.e(TAG, "write outputstrem failed" + e.toString());
}
if (V) Log.v(TAG, "Last packet sent out, sending process complete!");
if (!BluetoothPbapObexServer.closeStream(outputStream, operation)) {
if (V) Log.v(TAG, "CloseStream failed!");
} else {
if (V) Log.v(TAG, "CloseStream ok!");
}
}
}
}
| true | true | public final int composeAndSendVCards(Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC;
}
vcardType |= VCardConfig.FLAG_REFRAIN_PHONE_NUMBER_FORMATTING;
composer = new VCardComposer(mContext, vcardType, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
| public final int composeAndSendVCards(Operation op, final String selection,
final boolean vcardType21, String ownerVCard, boolean isContacts) {
long timestamp = 0;
if (V) timestamp = System.currentTimeMillis();
if (isContacts) {
VCardComposer composer = null;
try {
// Currently only support Generic Vcard 2.1 and 3.0
int vcardType;
if (vcardType21) {
vcardType = VCardConfig.VCARD_TYPE_V21_GENERIC;
} else {
vcardType = VCardConfig.VCARD_TYPE_V30_GENERIC;
}
vcardType |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT;
vcardType |= VCardConfig.FLAG_REFRAIN_PHONE_NUMBER_FORMATTING;
composer = new VCardComposer(mContext, vcardType, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(Contacts.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
} else { // CallLog
BluetoothPbapCallLogComposer composer = null;
try {
composer = new BluetoothPbapCallLogComposer(mContext, true);
composer.addHandler(new HandlerForStringBuffer(op, ownerVCard));
if (!composer.init(CallLog.Calls.CONTENT_URI, selection, null, null)) {
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
while (!composer.isAfterLast()) {
if (BluetoothPbapObexServer.sIsAborted) {
((ServerOperation)op).isAborted = true;
BluetoothPbapObexServer.sIsAborted = false;
break;
}
if (!composer.createOneEntry()) {
Log.e(TAG, "Failed to read a contact. Error reason: "
+ composer.getErrorReason());
return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
} finally {
if (composer != null) {
composer.terminate();
}
}
}
if (V) Log.v(TAG, "Total vcard composing and sending out takes "
+ (System.currentTimeMillis() - timestamp) + " ms");
return ResponseCodes.OBEX_HTTP_OK;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/JavaVariableCellModifier.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/JavaVariableCellModifier.java
index 87013bbef..de7ffdbc9 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/JavaVariableCellModifier.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/variables/JavaVariableCellModifier.java
@@ -1,113 +1,121 @@
/*******************************************************************************
* Copyright (c) 2006 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.internal.debug.ui.variables;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.internal.ui.elements.adapters.DefaultVariableCellModifier;
import org.eclipse.debug.internal.ui.elements.adapters.VariableColumnPresentation;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.core.IJavaVariable;
/**
* @since 3.2
*
*/
public class JavaVariableCellModifier extends DefaultVariableCellModifier {
/*
* (non-Javadoc)
*
* @see org.eclipse.debug.internal.ui.elements.adapters.DefaultVariableCellModifier#canModify(java.lang.Object,
* java.lang.String)
*/
public boolean canModify(Object element, String property) {
if (VariableColumnPresentation.COLUMN_VARIABLE_VALUE.equals(property)) {
if (element instanceof IJavaVariable) {
IJavaVariable var = (IJavaVariable) element;
try {
String signature = var.getSignature();
if (signature != null) {
if (signature.length() == 1) {
// primitive
return true;
}
return signature.equals("Ljava/lang/String;"); //$NON-NLS-1$
}
} catch (DebugException e) {
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.debug.internal.ui.elements.adapters.DefaultVariableCellModifier#getValue(java.lang.Object,
* java.lang.String)
*/
public Object getValue(Object element, String property) {
if (VariableColumnPresentation.COLUMN_VARIABLE_VALUE.equals(property)) {
if (element instanceof IJavaVariable) {
IJavaVariable var = (IJavaVariable) element;
if (isBoolean(var)) {
try {
if (var.getValue().getValueString().equals(Boolean.toString(true))) {
return new Integer(0);
} else {
return new Integer(1);
}
} catch (DebugException e) {
}
}
}
}
return super.getValue(element, property);
}
public void modify(Object element, String property, Object value) {
Object oldValue = getValue(element, property);
if (!value.equals(oldValue)) {
if (VariableColumnPresentation.COLUMN_VARIABLE_VALUE.equals(property)) {
if (element instanceof IJavaVariable) {
IJavaVariable var = (IJavaVariable) element;
if (isBoolean(var)) {
- switch (((Integer) value).intValue()) {
- case 0:
- super.modify(element, property, Boolean.toString(true));
- return;
- case 1:
- super.modify(element, property, Boolean.toString(false));
- return;
- }
+ if (value instanceof Integer) {
+ switch (((Integer) value).intValue()) {
+ case 0:
+ super.modify(element, property, Boolean.toString(true));
+ return;
+ case 1:
+ super.modify(element, property, Boolean.toString(false));
+ return;
+ default:
+ // invalid value
+ return;
+ }
+ } else {
+ // invalid value
+ return;
+ }
}
}
}
super.modify(element, property, value);
}
}
/**
* Returns whether the given variable is a boolean.
*
* @param variable
* @return
*/
public static boolean isBoolean(IJavaVariable variable) {
try {
String signature = variable.getSignature();
return (signature.length() == 1 && signature.charAt(0) == Signature.C_BOOLEAN);
} catch (DebugException e) {
}
return false;
}
}
| true | true | public void modify(Object element, String property, Object value) {
Object oldValue = getValue(element, property);
if (!value.equals(oldValue)) {
if (VariableColumnPresentation.COLUMN_VARIABLE_VALUE.equals(property)) {
if (element instanceof IJavaVariable) {
IJavaVariable var = (IJavaVariable) element;
if (isBoolean(var)) {
switch (((Integer) value).intValue()) {
case 0:
super.modify(element, property, Boolean.toString(true));
return;
case 1:
super.modify(element, property, Boolean.toString(false));
return;
}
}
}
}
super.modify(element, property, value);
}
}
| public void modify(Object element, String property, Object value) {
Object oldValue = getValue(element, property);
if (!value.equals(oldValue)) {
if (VariableColumnPresentation.COLUMN_VARIABLE_VALUE.equals(property)) {
if (element instanceof IJavaVariable) {
IJavaVariable var = (IJavaVariable) element;
if (isBoolean(var)) {
if (value instanceof Integer) {
switch (((Integer) value).intValue()) {
case 0:
super.modify(element, property, Boolean.toString(true));
return;
case 1:
super.modify(element, property, Boolean.toString(false));
return;
default:
// invalid value
return;
}
} else {
// invalid value
return;
}
}
}
}
super.modify(element, property, value);
}
}
|
diff --git a/src/main/java/org/apache/ws/security/message/WSSecEncryptedKey.java b/src/main/java/org/apache/ws/security/message/WSSecEncryptedKey.java
index 5979a13da..30b9964ba 100644
--- a/src/main/java/org/apache/ws/security/message/WSSecEncryptedKey.java
+++ b/src/main/java/org/apache/ws/security/message/WSSecEncryptedKey.java
@@ -1,655 +1,655 @@
/**
* 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.ws.security.message;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSSConfig;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoType;
import org.apache.ws.security.message.token.BinarySecurity;
import org.apache.ws.security.message.token.DOMX509Data;
import org.apache.ws.security.message.token.DOMX509IssuerSerial;
import org.apache.ws.security.message.token.Reference;
import org.apache.ws.security.message.token.SecurityTokenReference;
import org.apache.ws.security.message.token.X509Security;
import org.apache.ws.security.util.UUIDGenerator;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.algorithms.JCEMapper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Builder class to build an EncryptedKey.
*
* This is especially useful in the case where the same
* <code>EncryptedKey</code> has to be used to sign and encrypt the message In
* such a situation this builder will add the <code>EncryptedKey</code> to the
* security header and we can use the information form the builder to provide to
* other builders to reference to the token
*/
public class WSSecEncryptedKey extends WSSecBase {
private static org.apache.commons.logging.Log log =
org.apache.commons.logging.LogFactory.getLog(WSSecEncryptedKey.class);
protected Document document;
/**
* soap:Envelope element
*/
protected Element envelope = null;
/**
* Session key used as the secret in key derivation
*/
protected byte[] ephemeralKey;
/**
* Symmetric key used in the EncryptedKey.
*/
protected SecretKey symmetricKey = null;
/**
* Encrypted bytes of the ephemeral key
*/
protected byte[] encryptedEphemeralKey;
/**
* Remote user's alias to obtain the cert to encrypt the ephemeral key
*/
protected String encrUser = null;
/**
* Algorithm used to encrypt the ephemeral key
*/
protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
/**
* Algorithm to be used with the ephemeral key
*/
protected String symEncAlgo = WSConstants.AES_128;
/**
* xenc:EncryptedKey element
*/
protected Element encryptedKeyElement = null;
/**
* The Token identifier of the token that the <code>DerivedKeyToken</code>
* is (or to be) derived from.
*/
protected String encKeyId = null;
/**
* Custom token value
*/
protected String customEKTokenValueType;
/**
* Custom token id
*/
protected String customEKTokenId;
/**
* BinarySecurityToken to be included in the case where BST_DIRECT_REFERENCE
* is used to refer to the asymmetric encryption cert
*/
protected BinarySecurity bstToken = null;
protected X509Certificate useThisCert = null;
public WSSecEncryptedKey() {
super();
}
public WSSecEncryptedKey(WSSConfig config) {
super(config);
}
/**
* Set the user name to get the encryption certificate.
*
* The public key of this certificate is used, thus no password necessary.
* The user name is a keystore alias usually.
*
* @param user
*/
public void setUserInfo(String user) {
this.user = user;
}
/**
* Get the id generated during <code>prepare()</code>.
*
* Returns the the value of wsu:Id attribute of the EncryptedKey element.
*
* @return Return the wsu:Id of this token or null if <code>prepare()</code>
* was not called before.
*/
public String getId() {
return encKeyId;
}
/**
* Prepare the ephemeralKey and the tokens required to be added to the
* security header
*
* @param doc The SOAP envelope as <code>Document</code>
* @param crypto An instance of the Crypto API to handle keystore and certificates
* @throws WSSecurityException
*/
public void prepare(Document doc, Crypto crypto) throws WSSecurityException {
document = doc;
//
// Set up the ephemeral key
//
if (ephemeralKey == null) {
if (symmetricKey == null) {
KeyGenerator keyGen = getKeyGenerator();
symmetricKey = keyGen.generateKey();
}
ephemeralKey = symmetricKey.getEncoded();
}
if (symmetricKey == null) {
symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, ephemeralKey);
}
//
// Get the certificate that contains the public key for the public key
// algorithm that will encrypt the generated symmetric (session) key.
//
X509Certificate remoteCert = useThisCert;
if (remoteCert == null) {
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(user);
X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
if (certs == null || certs.length <= 0) {
throw new WSSecurityException(
WSSecurityException.FAILURE,
"noUserCertsFound",
new Object[] {user, "encryption"}
);
}
remoteCert = certs[0];
}
prepareInternal(symmetricKey, remoteCert, crypto);
}
/**
* Encrypt the symmetric key data and prepare the EncryptedKey element
*
* This method does the most work for to prepare the EncryptedKey element.
* It is also used by the WSSecEncrypt sub-class.
*
* @param secretKey The symmetric key
* @param remoteCert The certificate that contains the public key to encrypt the
* symmetric key data
* @param crypto An instance of the Crypto API to handle keystore and certificates
* @throws WSSecurityException
*/
protected void prepareInternal(
SecretKey secretKey,
X509Certificate remoteCert,
Crypto crypto
) throws WSSecurityException {
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.WRAP_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, e
);
}
int blockSize = cipher.getBlockSize();
if (doDebug) {
log.debug(
"cipher blksize: " + blockSize + ", symm key: " + secretKey.toString()
);
}
try {
encryptedEphemeralKey = cipher.wrap(secretKey);
} catch (IllegalStateException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (IllegalBlockSizeException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (InvalidKeyException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
Text keyText =
WSSecurityUtil.createBase64EncodedTextNode(document, encryptedEphemeralKey);
//
// Now we need to setup the EncryptedKey header block 1) create a
// EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
// element, this wraps the wsse:SecurityTokenReference 3) Create and set
// up the SecurityTokenReference according to the keyIdentifier parameter
// 4) Create the CipherValue element structure and insert the encrypted
// session key
//
encryptedKeyElement = createEncryptedKey(document, keyEncAlgo);
if (encKeyId == null || "".equals(encKeyId)) {
encKeyId = "EK-" + UUIDGenerator.getUUID();
}
encryptedKeyElement.setAttributeNS(null, "Id", encKeyId);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
//
// This identifier is not applicable for this case, so fall back to
// ThumbprintRSA.
//
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
- String issuer = remoteCert.getIssuerDN().getName();
+ String issuer = remoteCert.getIssuerX500Principal().getName();
java.math.BigInteger serialNumber = remoteCert.getSerialNumber();
DOMX509IssuerSerial domIssuerSerial =
new DOMX509IssuerSerial(
document, issuer, serialNumber
);
DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
secToken.setX509Data(domX509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
String certUri = UUIDGenerator.getUUID();
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
case WSConstants.CUSTOM_SYMM_SIGNING :
Reference refCust = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCust.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCust.setValueType(customEKTokenValueType);
} else {
refCust.setValueType(customEKTokenValueType);
}
refCust.setURI("#" + customEKTokenId);
secToken.setReference(refCust);
break;
case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT :
Reference refCustd = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else {
refCustd.setValueType(customEKTokenValueType);
}
refCustd.setURI(customEKTokenId);
secToken.setReference(refCustd);
break;
case WSConstants.CUSTOM_KEY_IDENTIFIER:
secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
} else if (SecurityTokenReference.ENC_KEY_SHA1_URI.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
}
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
}
Element keyInfoElement =
document.createElementNS(
WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN
);
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
keyInfoElement.appendChild(secToken.getElement());
encryptedKeyElement.appendChild(keyInfoElement);
Element xencCipherValue = createCipherValue(document, encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
}
protected KeyGenerator getKeyGenerator() throws WSSecurityException {
try {
//
// Assume AES as default, so initialize it
//
String keyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(symEncAlgo);
if (keyAlgorithm == null || "".equals(keyAlgorithm)) {
keyAlgorithm = JCEMapper.translateURItoJCEID(symEncAlgo);
}
KeyGenerator keyGen = KeyGenerator.getInstance(keyAlgorithm);
if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) {
keyGen.init(128);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) {
keyGen.init(192);
} else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) {
keyGen.init(256);
}
return keyGen;
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(
WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e
);
}
}
/**
* Create DOM subtree for <code>xenc:EncryptedKey</code>
*
* @param doc the SOAP envelope parent document
* @param keyTransportAlgo specifies which algorithm to use to encrypt the symmetric key
* @return an <code>xenc:EncryptedKey</code> element
*/
protected Element createEncryptedKey(Document doc, String keyTransportAlgo) {
Element encryptedKey =
doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptedKey");
WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS, WSConstants.ENC_PREFIX);
Element encryptionMethod =
doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptionMethod");
encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo);
encryptedKey.appendChild(encryptionMethod);
return encryptedKey;
}
protected Element createCipherValue(Document doc, Element encryptedKey) {
Element cipherData =
doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherData");
Element cipherValue =
doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherValue");
cipherData.appendChild(cipherValue);
encryptedKey.appendChild(cipherData);
return cipherValue;
}
/**
* Prepend the EncryptedKey element to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the EncryptedKey element at any position in the Security
* header.
*
* @param secHeader The security header that holds the Signature element.
*/
public void prependToHeader(WSSecHeader secHeader) {
WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), encryptedKeyElement);
}
/**
* Append the EncryptedKey element to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the EncryptedKey element at any position in the Security
* header.
*
* @param secHeader The security header that holds the Signature element.
*/
public void appendToHeader(WSSecHeader secHeader) {
Element secHeaderElement = secHeader.getSecurityHeader();
secHeaderElement.appendChild(encryptedKeyElement);
}
/**
* Prepend the BinarySecurityToken to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the BST element at any position in the Security header.
*
* @param secHeader The security header that holds the BST element.
*/
public void prependBSTElementToHeader(WSSecHeader secHeader) {
if (bstToken != null) {
WSSecurityUtil.prependChildElement(
secHeader.getSecurityHeader(), bstToken.getElement()
);
}
bstToken = null;
}
/**
* Append the BinarySecurityToken to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the BST element at any position in the Security header.
*
* @param secHeader The security header that holds the BST element.
*/
public void appendBSTElementToHeader(WSSecHeader secHeader) {
if (bstToken != null) {
Element secHeaderElement = secHeader.getSecurityHeader();
secHeaderElement.appendChild(bstToken.getElement());
}
bstToken = null;
}
/**
* @return Returns the ephemeralKey.
*/
public byte[] getEphemeralKey() {
return ephemeralKey;
}
/**
* Set the X509 Certificate to use for encryption.
*
* If this is set <b>and</b> the key identifier is set to
* <code>DirectReference</code> then use this certificate to get the
* public key for encryption.
*
* @param cert is the X509 certificate to use for encryption
*/
public void setUseThisCert(X509Certificate cert) {
useThisCert = cert;
}
/**
* @return Returns the encryptedKeyElement.
*/
public Element getEncryptedKeyElement() {
return encryptedKeyElement;
}
/**
* Set the encrypted key element when a pre prepared encrypted key is used
* @param encryptedKeyElement EncryptedKey element of the encrypted key used
*/
public void setEncryptedKeyElement(Element encryptedKeyElement) {
this.encryptedKeyElement = encryptedKeyElement;
}
/**
* @return Returns the BinarySecurityToken element.
*/
public Element getBinarySecurityTokenElement() {
if (bstToken != null) {
return bstToken.getElement();
}
return null;
}
public void setKeyEncAlgo(String keyEncAlgo) {
this.keyEncAlgo = keyEncAlgo;
}
/**
* @param ephemeralKey The ephemeralKey to set.
*/
public void setEphemeralKey(byte[] ephemeralKey) {
this.ephemeralKey = ephemeralKey;
}
/**
* Get the id of the BSt generated during <code>prepare()</code>.
*
* @return Returns the the value of wsu:Id attribute of the
* BinaruSecurityToken element.
*/
public String getBSTTokenId() {
if (bstToken == null) {
return null;
}
return bstToken.getID();
}
/**
* @param document The document to set.
*/
public void setDocument(Document document) {
this.document = document;
}
/**
* @param encKeyId The encKeyId to set.
*/
public void setEncKeyId(String encKeyId) {
this.encKeyId = encKeyId;
}
public boolean isCertSet() {
return (useThisCert == null ? true : false) ;
}
public byte[] getEncryptedEphemeralKey() {
return encryptedEphemeralKey;
}
public void setCustomEKTokenValueType(String customEKTokenValueType) {
this.customEKTokenValueType = customEKTokenValueType;
}
public void setCustomEKTokenId(String customEKTokenId) {
this.customEKTokenId = customEKTokenId;
}
/**
* Set the name of the symmetric encryption algorithm to use.
*
* This encryption algorithm is used to encrypt the data. If the algorithm
* is not set then AES128 is used. Refer to WSConstants which algorithms are
* supported.
*
* @param algo Is the name of the encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public void setSymmetricEncAlgorithm(String algo) {
symEncAlgo = algo;
}
/**
* Get the name of symmetric encryption algorithm to use.
*
* The name of the encryption algorithm to encrypt the data, i.e. the SOAP
* Body. Refer to WSConstants which algorithms are supported.
*
* @return the name of the currently selected symmetric encryption algorithm
* @see WSConstants#TRIPLE_DES
* @see WSConstants#AES_128
* @see WSConstants#AES_192
* @see WSConstants#AES_256
*/
public String getSymmetricEncAlgorithm() {
return symEncAlgo;
}
/**
* @return The symmetric key
*/
public SecretKey getSymmetricKey() {
return symmetricKey;
}
/**
* Set the symmetric key to be used for encryption
*
* @param key
*/
public void setSymmetricKey(SecretKey key) {
this.symmetricKey = key;
}
}
| true | true | protected void prepareInternal(
SecretKey secretKey,
X509Certificate remoteCert,
Crypto crypto
) throws WSSecurityException {
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.WRAP_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, e
);
}
int blockSize = cipher.getBlockSize();
if (doDebug) {
log.debug(
"cipher blksize: " + blockSize + ", symm key: " + secretKey.toString()
);
}
try {
encryptedEphemeralKey = cipher.wrap(secretKey);
} catch (IllegalStateException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (IllegalBlockSizeException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (InvalidKeyException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
Text keyText =
WSSecurityUtil.createBase64EncodedTextNode(document, encryptedEphemeralKey);
//
// Now we need to setup the EncryptedKey header block 1) create a
// EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
// element, this wraps the wsse:SecurityTokenReference 3) Create and set
// up the SecurityTokenReference according to the keyIdentifier parameter
// 4) Create the CipherValue element structure and insert the encrypted
// session key
//
encryptedKeyElement = createEncryptedKey(document, keyEncAlgo);
if (encKeyId == null || "".equals(encKeyId)) {
encKeyId = "EK-" + UUIDGenerator.getUUID();
}
encryptedKeyElement.setAttributeNS(null, "Id", encKeyId);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
//
// This identifier is not applicable for this case, so fall back to
// ThumbprintRSA.
//
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
String issuer = remoteCert.getIssuerDN().getName();
java.math.BigInteger serialNumber = remoteCert.getSerialNumber();
DOMX509IssuerSerial domIssuerSerial =
new DOMX509IssuerSerial(
document, issuer, serialNumber
);
DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
secToken.setX509Data(domX509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
String certUri = UUIDGenerator.getUUID();
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
case WSConstants.CUSTOM_SYMM_SIGNING :
Reference refCust = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCust.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCust.setValueType(customEKTokenValueType);
} else {
refCust.setValueType(customEKTokenValueType);
}
refCust.setURI("#" + customEKTokenId);
secToken.setReference(refCust);
break;
case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT :
Reference refCustd = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else {
refCustd.setValueType(customEKTokenValueType);
}
refCustd.setURI(customEKTokenId);
secToken.setReference(refCustd);
break;
case WSConstants.CUSTOM_KEY_IDENTIFIER:
secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
} else if (SecurityTokenReference.ENC_KEY_SHA1_URI.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
}
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
}
Element keyInfoElement =
document.createElementNS(
WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN
);
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
keyInfoElement.appendChild(secToken.getElement());
encryptedKeyElement.appendChild(keyInfoElement);
Element xencCipherValue = createCipherValue(document, encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
}
| protected void prepareInternal(
SecretKey secretKey,
X509Certificate remoteCert,
Crypto crypto
) throws WSSecurityException {
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.WRAP_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, e
);
}
int blockSize = cipher.getBlockSize();
if (doDebug) {
log.debug(
"cipher blksize: " + blockSize + ", symm key: " + secretKey.toString()
);
}
try {
encryptedEphemeralKey = cipher.wrap(secretKey);
} catch (IllegalStateException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (IllegalBlockSizeException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
} catch (InvalidKeyException ex) {
throw new WSSecurityException(
WSSecurityException.FAILED_ENCRYPTION, null, null, ex
);
}
Text keyText =
WSSecurityUtil.createBase64EncodedTextNode(document, encryptedEphemeralKey);
//
// Now we need to setup the EncryptedKey header block 1) create a
// EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
// element, this wraps the wsse:SecurityTokenReference 3) Create and set
// up the SecurityTokenReference according to the keyIdentifier parameter
// 4) Create the CipherValue element structure and insert the encrypted
// session key
//
encryptedKeyElement = createEncryptedKey(document, keyEncAlgo);
if (encKeyId == null || "".equals(encKeyId)) {
encKeyId = "EK-" + UUIDGenerator.getUUID();
}
encryptedKeyElement.setAttributeNS(null, "Id", encKeyId);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
//
// This identifier is not applicable for this case, so fall back to
// ThumbprintRSA.
//
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
String issuer = remoteCert.getIssuerX500Principal().getName();
java.math.BigInteger serialNumber = remoteCert.getSerialNumber();
DOMX509IssuerSerial domIssuerSerial =
new DOMX509IssuerSerial(
document, issuer, serialNumber
);
DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial);
secToken.setX509Data(domX509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
String certUri = UUIDGenerator.getUUID();
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
case WSConstants.CUSTOM_SYMM_SIGNING :
Reference refCust = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCust.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCust.setValueType(customEKTokenValueType);
} else {
refCust.setValueType(customEKTokenValueType);
}
refCust.setURI("#" + customEKTokenId);
secToken.setReference(refCust);
break;
case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT :
Reference refCustd = new Reference(document);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
refCustd.setValueType(customEKTokenValueType);
} else {
refCustd.setValueType(customEKTokenValueType);
}
refCustd.setURI(customEKTokenId);
secToken.setReference(refCustd);
break;
case WSConstants.CUSTOM_KEY_IDENTIFIER:
secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId);
if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
} else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
} else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
} else if (SecurityTokenReference.ENC_KEY_SHA1_URI.equals(customEKTokenValueType)) {
secToken.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
}
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
}
Element keyInfoElement =
document.createElementNS(
WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN
);
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
keyInfoElement.appendChild(secToken.getElement());
encryptedKeyElement.appendChild(keyInfoElement);
Element xencCipherValue = createCipherValue(document, encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
index 145dd9a375..a31eed3318 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/E2EInitiateRnR.java
@@ -1,225 +1,227 @@
/*
* Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.*;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class E2EInitiateRnR extends TestCaseHelper {
@BeforeMethod(groups = {"smoke"})
public void setUp() throws Exception {
super.setup();
}
@DataProvider(name = "envData")
public Object[][] getEnvData() {
return new Object[][]{};
}
@Test(groups = {"smoke"}, dataProvider = "Data-Provider-Function-Positive")
public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
+ initiateRnRPage.closeCommentPopUp();
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
+ approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.approveRequisition();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
orderPageOrdersPending.convertToOrder();
}
private void createRole(HomePage homePage) throws IOException {
RolesPage rolesPage = homePage.navigateRoleAssignments();
List<String> userRoleListStoreincharge = new ArrayList<String>();
userRoleListStoreincharge.add("Create Requisition");
userRoleListStoreincharge.add("Authorize Requisition");
userRoleListStoreincharge.add("Approve Requisition");
rolesPage.createRole("Store-in-charge", "Store-in-charge", userRoleListStoreincharge, true);
RolesPage rolesPagelmu = homePage.navigateRoleAssignments();
List<String> userRoleListlmu = new ArrayList<String>();
userRoleListlmu.add("Convert To Order Requisition");
rolesPagelmu.createRole("lmu", "lmu", userRoleListlmu, false);
List<String> userRoleListMedicalofficer = new ArrayList<String>();
userRoleListMedicalofficer.add("Approve Requisition");
rolesPage.createRole("Medical-officer", "Medical-officer", userRoleListMedicalofficer, true);
}
@AfterMethod(groups = {"smoke"})
public void tearDown() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"HIV", "storeincharge", "medicalofficer", "lmu", "Admin123", new String[]{"Admin123", "Admin123"}}
};
}
}
| false | true | public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.approveRequisition();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
orderPageOrdersPending.convertToOrder();
}
| public void testE2EInitiateRnR(String program, String userSIC, String userMO, String userlmu, String password, String[] credentials) throws Exception {
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility();
String geoZone = "Ngorongoro";
String parentgeoZone = "Dodoma";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String date_time = createFacilityPage.enterValuesInFacility(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy);
createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
String facility_code = "FCcode" + date_time;
dbWrapper.insertFacilities("F10", "F11");
createRole(homePage);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertSupervisoryNodeSecond("F11", "N2", "Node 2", "N1");
String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPageSIC = homePage.navigateToUser();
String userSICEmail = "[email protected]";
String userSICFirstName = "Fatima";
String userSICLastName = "Doe";
String userSICUserName = "storeincharge";
String userIDSIC = userPageSIC.enterAndverifyUserDetails(userSICUserName, userSICEmail, userSICFirstName, userSICLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userSICEmail);
userPageSIC.enterMyFacilityAndMySupervisedFacilityData(userSICFirstName, userSICLastName, "F10", "HIV", "Node 1", "Store-in-charge", false);
String passwordUserslmu = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
UserPage userPagelmu = homePage.navigateToUser();
String userlmuEmail = "[email protected]";
String userlmuFirstName = "Lmu";
String userlmuLastName = "Doe";
String userlmuUserName = "lmu";
userPagelmu.enterAndverifyUserDetails(userlmuUserName, userlmuEmail, userlmuFirstName, userlmuLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUserslmu, userlmuEmail);
userPagelmu.enterMyFacilityAndMySupervisedFacilityData(userlmuFirstName, userlmuLastName, "F10", "HIV", "Node 1", "lmu", true);
UserPage userPageMO = homePage.navigateToUser();
String userMOEmail = "[email protected]";
String userMOFirstName = "Jane";
String userMOLastName = "Doe";
String userMOUserName = "medicalofficer";
userPageMO.enterAndverifyUserDetails(userMOUserName, userMOEmail, userMOFirstName, userMOLastName, baseUrlGlobal, dburlGlobal);
dbWrapper.updateUser(passwordUsers, userMOEmail);
userPageMO.enterMyFacilityAndMySupervisedFacilityData(userMOFirstName, userMOLastName, "F11", "HIV", "Node 2", "Medical-Officer", false);
dbWrapper.updateRoleGroupMember(facility_code);
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertRequisitionGroups("RG1", "RG2", "N1", "N2");
dbWrapper.insertRequisitionGroupMembers("F10", facility_code);
ManageSchedulePage manageSchedulePage = homePage.navigateToSchedule();
manageSchedulePage.createAndVerifySchedule();
manageSchedulePage.editAndVerifySchedule();
PeriodsPage periodsPage = manageSchedulePage.navigatePeriods();
periodsPage.createAndVerifyPeriods();
periodsPage.deleteAndVerifyPeriods();
dbWrapper.insertRequisitionGroupProgramSchedule();
dbWrapper.allocateFacilityToUser(userIDSIC, facility_code);
TemplateConfigPage templateConfigPage = homePage.selectProgramToConfigTemplate(program);
templateConfigPage.configureTemplate();
dbWrapper.insertSupplyLines("N1", "HIV", "FCcode" + date_time);
LoginPage loginPageSecond = homePage.logout(baseUrlGlobal);
HomePage homePageUser = loginPageSecond.loginAs(userSIC, password);
String periodDetails = homePageUser.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePageUser.clickProceed();
initiateRnRPage.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
initiateRnRPage.submitRnR();
initiateRnRPage.verifySubmitRnrErrorMsg();
initiateRnRPage.calculateAndVerifyStockOnHand(10, 10, 10, 1);
initiateRnRPage.submitRnR();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.typeCommentsInCommentsTextArea("Test comment.");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.clickCommentsButton();
initiateRnRPage.verifyValueInCommentsTextArea("");
initiateRnRPage.closeCommentPopUp();
initiateRnRPage.addComments("Dummy Comments.");
initiateRnRPage.verifyComment("Dummy Comments.", userSICUserName, 1);
initiateRnRPage.enterValuesAndVerifyCalculatedOrderQuantity(10, 10, 101, 51, 153, 142);
initiateRnRPage.verifyPacksToShip(15);
initiateRnRPage.enterAndVerifyRequestedQuantityExplanation(10);
initiateRnRPage.verifyPacksToShip(1);
initiateRnRPage.calculateAndVerifyTotalCost();
initiateRnRPage.saveRnR();
initiateRnRPage.addNonFullSupplyLineItems("99", "Due to unforeseen event", "antibiotic", "P11", "Antibiotics", baseUrlGlobal, dburlGlobal);
initiateRnRPage.calculateAndVerifyTotalCostNonFullSupply();
initiateRnRPage.verifyCostOnFooter();
initiateRnRPage.authorizeRnR();
initiateRnRPage.verifyAuthorizeRnrSuccessMsg();
initiateRnRPage.verifyApproveButtonNotPresent();
ApprovePage approvePage = homePageUser.navigateToApprove();
approvePage.verifyNoRequisitionPendingMessage();
LoginPage loginPagethird = homePageUser.logout(baseUrlGlobal);
HomePage homePageLowerSNUser = loginPagethird.loginAs(userMO, password);
ApprovePage approvePageLowerSNUser = homePageLowerSNUser.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageLowerSNUser.verifyApprovedQuantity();
approvePageLowerSNUser.editApproveQuantityAndVerifyTotalCost("290");
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.typeCommentsInCommentsTextArea("Test comment.");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.clickCommentsButton();
approvePageLowerSNUser.verifyValueInCommentsTextArea("");
approvePageLowerSNUser.closeCommentPopUp();
approvePageLowerSNUser.addComments("This is urgent");
approvePageLowerSNUser.verifyComment("This is urgent", userMO, 2);
approvePageLowerSNUser.approveRequisition();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPageTopSNUser = homePageLowerSNUser.logout(baseUrlGlobal);
HomePage homePageTopSNUser = loginPageTopSNUser.loginAs(userSIC, password);
ApprovePage approvePageTopSNUser = homePageTopSNUser.navigateToApprove();
String periodTopSNUser = approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.verifyRnRHeader("FCcode", "FCname", date_time, program, periodDetails, geoZone, parentgeoZone, operatedBy, facilityType);
approvePageTopSNUser.verifyApprovedQuantityApprovedFromLowerHierarchy("290");
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCost("100");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
LoginPage loginPagelmu = homePageTopSNUser.logout(baseUrlGlobal);
HomePage homePagelmu = loginPagelmu.loginAs(userlmu, password);
OrderPage orderPageOrdersPending = homePagelmu.navigateConvertToOrder();
String[] periods = periodTopSNUser.split("-");
String supplyFacilityName = dbWrapper.getSupplyFacilityName("N1", "HIV");
orderPageOrdersPending.verifyOrderListElements(program, "FCcode" + date_time, "FCname" + date_time, periods[0].trim(), periods[1].trim(), supplyFacilityName);
orderPageOrdersPending.convertToOrder();
}
|
diff --git a/src/edu/unc/genomics/WigAnalysisTool.java b/src/edu/unc/genomics/WigAnalysisTool.java
index 6d924e6..a0b8eb5 100644
--- a/src/edu/unc/genomics/WigAnalysisTool.java
+++ b/src/edu/unc/genomics/WigAnalysisTool.java
@@ -1,253 +1,256 @@
package edu.unc.genomics;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.beust.jcommander.Parameter;
import edu.unc.genomics.Interval;
import edu.unc.genomics.io.WigFileReader;
import edu.unc.genomics.io.WigFileException;
/**
* Abstract base class for writing programs to do analysis on Wig files
*
* WigAnalysisTool takes all input Wig files, finds the intersecting set of
* chromosomes with data, and then iterates through the inputs in a
* chunk-by-chunk fashion, calling compute() on each chunk
*
* prepare() is called before the computation loop shutdown() is called after
* the computation loop
*
* @author timpalpant
*
*/
public abstract class WigAnalysisTool extends CommandLineTool {
private static final Logger log = Logger.getLogger(WigAnalysisTool.class);
@Parameter(names = { "-c", "--chunk" }, description = "Maximum number of data values to load per thread (bp)")
public int chunkSize = DEFAULT_CHUNK_SIZE;
@Parameter(names = { "-p", "--threads" }, description = "Number of threads to use")
public int nThreads = 1;
private ExecutorService pool;
/**
* Process the union of the extents of all input files rather than the
* intersection
*/
protected boolean unionExtents = false;
/**
* Holds all of the input Wig files for this compute job. Used to find the
* intersecting set of chromosomes to process
*/
protected List<WigFileReader> inputs = new ArrayList<WigFileReader>();
protected void addInputFile(WigFileReader wig) {
inputs.add(wig);
}
/**
* Setup the computation. Should add all input Wig files with addInputFile()
* during setup
*/
protected abstract void prepare();
/**
* Optional shutdown the computation, do any cleanup, final processing
*
* @throws IOException
*/
protected void shutdown() throws IOException {
}
/**
* Close the input files
*
* @throws IOException
*/
private void close() throws IOException {
for (WigFileReader wig : inputs) {
wig.close();
}
}
/**
* Do the computation on a chunk and return the results Must return
* chunk.length() values (one for every base pair in chunk)
*
* @param chunk
* the interval to process
* @return the results of the computation for this chunk
* @throws IOException
* @throws WigFileException
*/
protected abstract void process(Interval chunk) throws IOException, WigFileException;
@Override
public final void run() throws IOException {
log.debug("Executing setup operations");
prepare();
Set<String> chromosomes = null;
if (unionExtents) {
chromosomes = getUnionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the union of all inputs");
} else {
chromosomes = getIntersectionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the intersection of all inputs");
}
log.debug("Initializing thread pool with " + nThreads + " threads");
pool = Executors.newFixedThreadPool(nThreads);
log.debug("Performing main computation");
List<Future<?>> futures = new ArrayList<>();
try {
for (String chr : chromosomes) {
Interval interval = unionExtents ? getUnion(inputs, chr) : getIntersection(inputs, chr);
+ if (interval == null) {
+ continue; // input files contain data for disjoint intervals in chr
+ }
// Process the chromosome in chunks
int bp = interval.low();
while (bp < interval.high()) {
int chunkStart = bp;
int chunkStop = Math.min(bp + chunkSize - 1, interval.high());
final Interval chunk = new Interval(chr, chunkStart, chunkStop);
futures.add(pool.submit(new Runnable() {
@Override
public void run() {
log.debug("Processing chunk " + chunk);
try {
process(chunk);
} catch (Exception e) {
throw new CommandLineToolException("Exception while processing chunk " + chunk, e);
}
}
}));
// Move to the next chunk
bp = chunkStop + 1;
}
}
for (Future<?> f : futures) {
f.get();
}
} catch (InterruptedException | ExecutionException e) {
throw new CommandLineToolException(e);
} catch (IntervalException e) {
throw new CommandLineToolException(e);
} finally {
pool.shutdownNow();
shutdown();
close();
}
}
/**
* Get the set of chromosomes that are held in common by all input files
*
* @param wigs
* a list of Wig files to get the common chromosomes of
* @return the set of chromosomes held in common by all Wig files in wigs
*/
public static Set<String> getIntersectionChromosomes(List<WigFileReader> wigs) {
if (wigs == null || wigs.isEmpty()) {
return new HashSet<String>();
}
Set<String> chromosomes = wigs.get(0).chromosomes();
Iterator<String> it = chromosomes.iterator();
while (it.hasNext()) {
String chr = it.next();
for (WigFileReader wig : wigs) {
if (!wig.includes(chr)) {
it.remove();
break;
}
}
}
return chromosomes;
}
/**
* Gets the intersecting Interval for a chromosome amongst all wigs
*
* @param wigs
* a List of wig files
* @param chr
* the chromosome to get the most conservative start base for
* @return an Interval for which all wigs have data
*/
public static Interval getIntersection(List<WigFileReader> wigs, String chr) {
if (wigs == null || wigs.isEmpty()) {
return null;
}
Interval intersection = wigs.get(0).getChrExtents(chr);
for (int i = 1; i < wigs.size(); i++) {
if (intersection == null)
break;
intersection = intersection.intersection(wigs.get(i).getChrExtents(chr));
}
return intersection;
}
/**
* Get the set of chromosomes that are held in common by all input files
*
* @param wigs
* a list of Wig files to get the common chromosomes of
* @return the set of chromosomes held in common by all Wig files in wigs
*/
public static Set<String> getUnionChromosomes(List<WigFileReader> wigs) {
Set<String> chromosomes = new HashSet<>();
for (WigFileReader wig : wigs) {
chromosomes.addAll(wig.chromosomes());
}
return chromosomes;
}
/**
* Gets the union Interval for a chromosome amongst all wigs
*
* @param wigs
* a List of wig files
* @param chr
* the chromosome to get the most conservative start base for
* @return an Interval for which at least one wig has data
* @throws IntervalException
* if one of the wigs does not contain chr
*/
public static Interval getUnion(List<WigFileReader> wigs, String chr) throws IntervalException {
if (wigs == null || wigs.isEmpty()) {
return null;
}
Interval union = null;
for (WigFileReader wig : wigs) {
if (!wig.includes(chr))
continue;
union = wig.getChrExtents(chr).union(union);
}
return union;
}
}
| true | true | public final void run() throws IOException {
log.debug("Executing setup operations");
prepare();
Set<String> chromosomes = null;
if (unionExtents) {
chromosomes = getUnionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the union of all inputs");
} else {
chromosomes = getIntersectionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the intersection of all inputs");
}
log.debug("Initializing thread pool with " + nThreads + " threads");
pool = Executors.newFixedThreadPool(nThreads);
log.debug("Performing main computation");
List<Future<?>> futures = new ArrayList<>();
try {
for (String chr : chromosomes) {
Interval interval = unionExtents ? getUnion(inputs, chr) : getIntersection(inputs, chr);
// Process the chromosome in chunks
int bp = interval.low();
while (bp < interval.high()) {
int chunkStart = bp;
int chunkStop = Math.min(bp + chunkSize - 1, interval.high());
final Interval chunk = new Interval(chr, chunkStart, chunkStop);
futures.add(pool.submit(new Runnable() {
@Override
public void run() {
log.debug("Processing chunk " + chunk);
try {
process(chunk);
} catch (Exception e) {
throw new CommandLineToolException("Exception while processing chunk " + chunk, e);
}
}
}));
// Move to the next chunk
bp = chunkStop + 1;
}
}
for (Future<?> f : futures) {
f.get();
}
} catch (InterruptedException | ExecutionException e) {
throw new CommandLineToolException(e);
} catch (IntervalException e) {
throw new CommandLineToolException(e);
} finally {
pool.shutdownNow();
shutdown();
close();
}
}
| public final void run() throws IOException {
log.debug("Executing setup operations");
prepare();
Set<String> chromosomes = null;
if (unionExtents) {
chromosomes = getUnionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the union of all inputs");
} else {
chromosomes = getIntersectionChromosomes(inputs);
log.debug("Found " + chromosomes.size() + " chromosomes in the intersection of all inputs");
}
log.debug("Initializing thread pool with " + nThreads + " threads");
pool = Executors.newFixedThreadPool(nThreads);
log.debug("Performing main computation");
List<Future<?>> futures = new ArrayList<>();
try {
for (String chr : chromosomes) {
Interval interval = unionExtents ? getUnion(inputs, chr) : getIntersection(inputs, chr);
if (interval == null) {
continue; // input files contain data for disjoint intervals in chr
}
// Process the chromosome in chunks
int bp = interval.low();
while (bp < interval.high()) {
int chunkStart = bp;
int chunkStop = Math.min(bp + chunkSize - 1, interval.high());
final Interval chunk = new Interval(chr, chunkStart, chunkStop);
futures.add(pool.submit(new Runnable() {
@Override
public void run() {
log.debug("Processing chunk " + chunk);
try {
process(chunk);
} catch (Exception e) {
throw new CommandLineToolException("Exception while processing chunk " + chunk, e);
}
}
}));
// Move to the next chunk
bp = chunkStop + 1;
}
}
for (Future<?> f : futures) {
f.get();
}
} catch (InterruptedException | ExecutionException e) {
throw new CommandLineToolException(e);
} catch (IntervalException e) {
throw new CommandLineToolException(e);
} finally {
pool.shutdownNow();
shutdown();
close();
}
}
|
diff --git a/jobbie/src/java/org/openqa/selenium/ie/ErrorHandler.java b/jobbie/src/java/org/openqa/selenium/ie/ErrorHandler.java
index 4231740b5..da396a74b 100644
--- a/jobbie/src/java/org/openqa/selenium/ie/ErrorHandler.java
+++ b/jobbie/src/java/org/openqa/selenium/ie/ErrorHandler.java
@@ -1,93 +1,93 @@
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-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 org.openqa.selenium.ie;
import static org.openqa.selenium.ie.ExportedWebDriverFunctions.SUCCESS;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.InvalidCookieDomainException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.UnableToSetCookieException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.NoSuchWindowException;
class ErrorHandler {
public void verifyErrorCode(int errorCode, String message) {
switch (errorCode) {
case SUCCESS:
break; // Nothing to do
case 7:
throw new NoSuchElementException(message);
case 8:
throw new NoSuchFrameException(message);
case 9:
throw new UnsupportedOperationException("You may not perform the requested action");
case 10:
throw new StaleElementReferenceException(
String.format("You may not %s this element. It looks as if the reference is stale. " +
"Did you navigate away from the page with this element on?", message));
case 11:
throw new ElementNotVisibleException(
String.format("You may not %s an element that is not displayed", message));
case 12:
throw new UnsupportedOperationException(
String.format("You may not %s an element that is not enabled", message));
case 14:
throw new WebDriverException("An unhandled exception has occured. " + message);
case 15:
throw new UnsupportedOperationException(
String.format("The element appears to be unselectable: %s", message));
case 16:
throw new NoSuchElementException(message + " (no document found)");
case 17:
throw new UnexpectedJavascriptExecutionException(message);
case 21:
throw new TimedOutException("The driver reported that the command timed out. There may "
- + "be several reasons for this. Check that the destination"
+ + "be several reasons for this. Check that the destination "
+ "site is in IE's 'Trusted Sites' (accessed from Tools->"
+ "Internet Options in the 'Security' tab) If it is a "
- + "trusted site, then the request may have taken more than"
+ + "trusted site, then the request may have taken more than "
+ "a minute to finish.");
case 23:
throw new NoSuchWindowException(message);
case 24:
throw new InvalidCookieDomainException(message);
case 25:
throw new UnableToSetCookieException(message);
default:
throw new IllegalStateException(String.format("%s (%d)", message, errorCode));
}
}
}
| false | true | public void verifyErrorCode(int errorCode, String message) {
switch (errorCode) {
case SUCCESS:
break; // Nothing to do
case 7:
throw new NoSuchElementException(message);
case 8:
throw new NoSuchFrameException(message);
case 9:
throw new UnsupportedOperationException("You may not perform the requested action");
case 10:
throw new StaleElementReferenceException(
String.format("You may not %s this element. It looks as if the reference is stale. " +
"Did you navigate away from the page with this element on?", message));
case 11:
throw new ElementNotVisibleException(
String.format("You may not %s an element that is not displayed", message));
case 12:
throw new UnsupportedOperationException(
String.format("You may not %s an element that is not enabled", message));
case 14:
throw new WebDriverException("An unhandled exception has occured. " + message);
case 15:
throw new UnsupportedOperationException(
String.format("The element appears to be unselectable: %s", message));
case 16:
throw new NoSuchElementException(message + " (no document found)");
case 17:
throw new UnexpectedJavascriptExecutionException(message);
case 21:
throw new TimedOutException("The driver reported that the command timed out. There may "
+ "be several reasons for this. Check that the destination"
+ "site is in IE's 'Trusted Sites' (accessed from Tools->"
+ "Internet Options in the 'Security' tab) If it is a "
+ "trusted site, then the request may have taken more than"
+ "a minute to finish.");
case 23:
throw new NoSuchWindowException(message);
case 24:
throw new InvalidCookieDomainException(message);
case 25:
throw new UnableToSetCookieException(message);
default:
throw new IllegalStateException(String.format("%s (%d)", message, errorCode));
}
}
| public void verifyErrorCode(int errorCode, String message) {
switch (errorCode) {
case SUCCESS:
break; // Nothing to do
case 7:
throw new NoSuchElementException(message);
case 8:
throw new NoSuchFrameException(message);
case 9:
throw new UnsupportedOperationException("You may not perform the requested action");
case 10:
throw new StaleElementReferenceException(
String.format("You may not %s this element. It looks as if the reference is stale. " +
"Did you navigate away from the page with this element on?", message));
case 11:
throw new ElementNotVisibleException(
String.format("You may not %s an element that is not displayed", message));
case 12:
throw new UnsupportedOperationException(
String.format("You may not %s an element that is not enabled", message));
case 14:
throw new WebDriverException("An unhandled exception has occured. " + message);
case 15:
throw new UnsupportedOperationException(
String.format("The element appears to be unselectable: %s", message));
case 16:
throw new NoSuchElementException(message + " (no document found)");
case 17:
throw new UnexpectedJavascriptExecutionException(message);
case 21:
throw new TimedOutException("The driver reported that the command timed out. There may "
+ "be several reasons for this. Check that the destination "
+ "site is in IE's 'Trusted Sites' (accessed from Tools->"
+ "Internet Options in the 'Security' tab) If it is a "
+ "trusted site, then the request may have taken more than "
+ "a minute to finish.");
case 23:
throw new NoSuchWindowException(message);
case 24:
throw new InvalidCookieDomainException(message);
case 25:
throw new UnableToSetCookieException(message);
default:
throw new IllegalStateException(String.format("%s (%d)", message, errorCode));
}
}
|
diff --git a/src/main/java/com/dumptruckman/chunky/object/ChunkyObject.java b/src/main/java/com/dumptruckman/chunky/object/ChunkyObject.java
index 772c5d7..58893e1 100644
--- a/src/main/java/com/dumptruckman/chunky/object/ChunkyObject.java
+++ b/src/main/java/com/dumptruckman/chunky/object/ChunkyObject.java
@@ -1,189 +1,189 @@
package com.dumptruckman.chunky.object;
import com.dumptruckman.chunky.Chunky;
import com.dumptruckman.chunky.event.object.ChunkyObjectNameEvent;
import com.dumptruckman.chunky.persistance.DatabaseManager;
import java.util.HashMap;
import java.util.HashSet;
/**
* @author dumptruckman, SwearWord
*/
public abstract class ChunkyObject {
/**
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
protected ChunkyObject owner;
protected HashMap<Integer, HashSet<ChunkyObject>> ownables = new HashMap<Integer, HashSet<ChunkyObject>>();
private String name;
private int classHash;
public ChunkyObject(String name) {
this.name = name;
classHash = this.getClass().getName().hashCode();
}
public String getName() {
return name;
}
public void setName(String name) {
ChunkyObjectNameEvent event = new ChunkyObjectNameEvent(this, name);
Chunky.getModuleManager().callEvent(event);
if (event.isCancelled()) return;
this.name = event.getNewName();
}
public int hashCode() {
return (getType() + ":" + getName()).hashCode();
}
public boolean equals(Object obj) {
return obj instanceof ChunkyObject && ((ChunkyObject)obj).getName().equals(this.getName());
}
public Integer getType() {
return classHash;
}
final public boolean isOwned() {
return !(owner == null);
}
/**
* Causes o to be owned by this object.
* @param o object to become owned.
* @return true if this object did not already own o.
*/
private boolean addOwnable(ChunkyObject o) {
if (o == null)
throw new IllegalArgumentException();
// If owner is a owned by the child, remove owner from tree first.
// ex. town.setOwner(Peasant) Peasant is removed from parent (Town).
- if(this.isOwnedBy(o)) {
+ if(this.isOwnedBy(o) && this.owner != null) {
this.getOwner().removeOwnableAndTakeChildren(this);
}
if (ownables.containsKey(o.getType())) {
Boolean exists = ownables.get(o.getType()).add(o);
if(exists) DatabaseManager.addOwnership(this,o);
return exists;
} else {
HashSet<ChunkyObject> ownables = new HashSet<ChunkyObject>();
ownables.add(o);
this.ownables.put(o.getType(), ownables);
DatabaseManager.addOwnership(this,o);
return true;
}
}
/**
* Removes an ownable o from this object.
* @param o the ownable to remove
* @return true if the set contained the specified element
*/
private boolean removeOwnable(ChunkyObject o) {
Boolean removed = ownables.containsKey(o.getType()) && ownables.get(o.getType()).remove(o);
if(removed) {
o.owner = null;
DatabaseManager.removeOwnership(this,o);
}
return removed;
}
private void removeOwnableAndTakeChildren(ChunkyObject o) {
if(removeOwnable(o)) takeChildren(o);
}
public void takeChildren(ChunkyObject o) {
// If a child is removed, parent reposesses all their objects.
// ex. If a child of a town is removed then their plots are owned by town.
HashMap<Integer, HashSet<ChunkyObject>> reposess = o.getOwnables();
o.ownables = new HashMap<Integer, HashSet<ChunkyObject>>();
for(Integer key : reposess.keySet()) {
for(ChunkyObject co : reposess.get(key)) {
this.addOwnable(co);
}
}
}
/**
* Checks if o is owned by this object.
* @param o object to check ownership for
* @return true if this object owns o
*/
final public boolean isOwnerOf(ChunkyObject o) {
return o.isOwnedBy(this);
}
/**
* @param owner Check if this object is an ancestor.
* @return
*/
final public boolean isOwnedBy(ChunkyObject owner) {
if (owner == null)
return false;
ChunkyObject current = this;
while (current != null && current != owner)
current = current.getOwner();
return current == owner;
}
final public boolean isDirectlyOwnnedBy(ChunkyObject owner) {
return this.owner == owner;
}
/**
* Returns the owner <code>TreeNode</code> of the receiver.
*/
public ChunkyObject getOwner() {
return owner;
}
/**
* @param object the object that will become the owner.
* @param keepChildren false transfers the object's children to current owner.
*/
public void setOwner(ChunkyObject object, Boolean keepChildren) {
//TODO IS THIS RIGHT?!?!
ChunkyObject oldowner = this.owner;
if (owner != null)
if(keepChildren) owner.removeOwnable(this);
else owner.removeOwnableAndTakeChildren(this);
if (object != null) {
if (object.addOwnable(this)) owner = object;
} else {
owner = null;
}
if(oldowner != null) {
}
}
/**
* Returns true if the receiver is a leaf.
*/
public boolean isLeaf() {
return ownables.size() == 0;
}
/**
* Returns all ownables of this object. You may not change the structure/values of this HashMap.
* @return
*/
public HashMap<Integer, HashSet<ChunkyObject>> getOwnables() {
@SuppressWarnings("unchecked")
HashMap<Integer, HashSet<ChunkyObject>> ownables = (HashMap<Integer, HashSet<ChunkyObject>>)this.ownables.clone();
return ownables;
}
}
| true | true | private boolean addOwnable(ChunkyObject o) {
if (o == null)
throw new IllegalArgumentException();
// If owner is a owned by the child, remove owner from tree first.
// ex. town.setOwner(Peasant) Peasant is removed from parent (Town).
if(this.isOwnedBy(o)) {
this.getOwner().removeOwnableAndTakeChildren(this);
}
if (ownables.containsKey(o.getType())) {
Boolean exists = ownables.get(o.getType()).add(o);
if(exists) DatabaseManager.addOwnership(this,o);
return exists;
} else {
HashSet<ChunkyObject> ownables = new HashSet<ChunkyObject>();
ownables.add(o);
this.ownables.put(o.getType(), ownables);
DatabaseManager.addOwnership(this,o);
return true;
}
}
| private boolean addOwnable(ChunkyObject o) {
if (o == null)
throw new IllegalArgumentException();
// If owner is a owned by the child, remove owner from tree first.
// ex. town.setOwner(Peasant) Peasant is removed from parent (Town).
if(this.isOwnedBy(o) && this.owner != null) {
this.getOwner().removeOwnableAndTakeChildren(this);
}
if (ownables.containsKey(o.getType())) {
Boolean exists = ownables.get(o.getType()).add(o);
if(exists) DatabaseManager.addOwnership(this,o);
return exists;
} else {
HashSet<ChunkyObject> ownables = new HashSet<ChunkyObject>();
ownables.add(o);
this.ownables.put(o.getType(), ownables);
DatabaseManager.addOwnership(this,o);
return true;
}
}
|
diff --git a/installer/it/src/test/java/org/apache/sling/installer/it/RegisterResourcesTest.java b/installer/it/src/test/java/org/apache/sling/installer/it/RegisterResourcesTest.java
index deaf844564..1da2f72916 100644
--- a/installer/it/src/test/java/org/apache/sling/installer/it/RegisterResourcesTest.java
+++ b/installer/it/src/test/java/org/apache/sling/installer/it/RegisterResourcesTest.java
@@ -1,226 +1,226 @@
/*
* 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.sling.installer.it;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.installer.api.InstallableResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.Bundle;
@RunWith(JUnit4TestRunner.class)
/** Test the {@link OsgiInstaller.registerResources} method, which lets a client
* supply a new list of resources.
*/
public class RegisterResourcesTest extends OsgiInstallerTestBase {
@org.ops4j.pax.exam.junit.Configuration
public static Option[] configuration() {
return defaultConfiguration();
}
@Before
public void setUp() {
setupInstaller();
}
@After
public void tearDown() {
super.tearDown();
}
@Test
public void initialRegistrationTest() throws Exception {
final Object listener = this.startObservingBundleEvents();
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.1.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar"))[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED));
final String info = "After initial registration";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
}
@Test
public void removeAndReaddBundlesTest() throws Exception {
{
final Object listener = this.startObservingBundleEvents();
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.1.jar"))[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.STARTED));
final String info = "After initial registration";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.1", Bundle.ACTIVE);
}
{
// Add test 1.2 in between, to make sure it disappears in next registerResources call
final Object listener = this.startObservingBundleEvents();
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED));
assertBundle("After adding testbundle V1.2", "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
}
{
// Add a bundle with different URL scheme - must not be removed by registerResources
final Object listener = this.startObservingBundleEvents();
installer.updateResources("anotherscheme", new InstallableResource[] {new MockInstallableResource(
"osgi-installer-testA.jar",
new FileInputStream(getTestBundle(BUNDLE_BASE_NAME + "-testA-1.0.jar")),
"digest1", null, null)}, null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.STARTED));
assertBundle("testA bundle added", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Simulate later registration where some bundles have disappeared
// the installer must mark them "not installable" and act accordingly
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-snap.jar"), "digest1")[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.UNINSTALLED),
- new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.INSTALLED),
+ new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.UPDATED),
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.STARTED));
assertBundle("Snapshot bundle must be started",
"osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
assertNull("Bundle testB must be gone", findBundle("osgi-installer-testB"));
final Bundle b = assertBundle("Bundle needsB must still be present",
"osgi-installer-needsB", "1.0", -1);
final int state = b.getState();
assertFalse("Bundle needsB must be stopped as testB is gone (" + state + ")", Bundle.ACTIVE == state);
assertBundle("Testbundle must be back to 1.0 as 1.1 and 1.2 is gone",
"osgi-installer-testbundle", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Re-add the missing bundles and recheck
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar")), null);
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.UPDATED),
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED));
final String info = "After re-adding missing bundles";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
final Bundle b = findBundle("osgi-installer-needsB");
b.start();
assertBundle("After reinstalling testB, needsB must be startable, ",
"osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
}
@Test
public void reAddZeroResourcesTest() throws Exception {
{
final Object listener = this.startObservingBundleEvents();
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.1.jar"))[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.STARTED));
final String info = "After initial registration";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.1", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
installer.registerResources(URL_SCHEME, new InstallableResource[0]);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.UNINSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.UNINSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.UNINSTALLED));
assertNull("After registration with no resources, testB bundle must be gone", findBundle("osgi-installer-testB"));
assertNull("After registration with no resources, testB bundle must be gone", findBundle("osgi-installer-needsB"));
assertNull("After registration with no resources, testB bundle must be gone", findBundle("osgi-installer-testbundle"));
}
}
}
| true | true | public void removeAndReaddBundlesTest() throws Exception {
{
final Object listener = this.startObservingBundleEvents();
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.1.jar"))[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.STARTED));
final String info = "After initial registration";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.1", Bundle.ACTIVE);
}
{
// Add test 1.2 in between, to make sure it disappears in next registerResources call
final Object listener = this.startObservingBundleEvents();
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED));
assertBundle("After adding testbundle V1.2", "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
}
{
// Add a bundle with different URL scheme - must not be removed by registerResources
final Object listener = this.startObservingBundleEvents();
installer.updateResources("anotherscheme", new InstallableResource[] {new MockInstallableResource(
"osgi-installer-testA.jar",
new FileInputStream(getTestBundle(BUNDLE_BASE_NAME + "-testA-1.0.jar")),
"digest1", null, null)}, null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.STARTED));
assertBundle("testA bundle added", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Simulate later registration where some bundles have disappeared
// the installer must mark them "not installable" and act accordingly
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-snap.jar"), "digest1")[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.UNINSTALLED),
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.STARTED));
assertBundle("Snapshot bundle must be started",
"osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
assertNull("Bundle testB must be gone", findBundle("osgi-installer-testB"));
final Bundle b = assertBundle("Bundle needsB must still be present",
"osgi-installer-needsB", "1.0", -1);
final int state = b.getState();
assertFalse("Bundle needsB must be stopped as testB is gone (" + state + ")", Bundle.ACTIVE == state);
assertBundle("Testbundle must be back to 1.0 as 1.1 and 1.2 is gone",
"osgi-installer-testbundle", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Re-add the missing bundles and recheck
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar")), null);
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.UPDATED),
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED));
final String info = "After re-adding missing bundles";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
final Bundle b = findBundle("osgi-installer-needsB");
b.start();
assertBundle("After reinstalling testB, needsB must be startable, ",
"osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
}
| public void removeAndReaddBundlesTest() throws Exception {
{
final Object listener = this.startObservingBundleEvents();
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.1.jar"))[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-needsB", "1.0", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testbundle", "1.1", org.osgi.framework.BundleEvent.STARTED));
final String info = "After initial registration";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.1", Bundle.ACTIVE);
}
{
// Add test 1.2 in between, to make sure it disappears in next registerResources call
final Object listener = this.startObservingBundleEvents();
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED));
assertBundle("After adding testbundle V1.2", "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
}
{
// Add a bundle with different URL scheme - must not be removed by registerResources
final Object listener = this.startObservingBundleEvents();
installer.updateResources("anotherscheme", new InstallableResource[] {new MockInstallableResource(
"osgi-installer-testA.jar",
new FileInputStream(getTestBundle(BUNDLE_BASE_NAME + "-testA-1.0.jar")),
"digest1", null, null)}, null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testA", "1.0", org.osgi.framework.BundleEvent.STARTED));
assertBundle("testA bundle added", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Simulate later registration where some bundles have disappeared
// the installer must mark them "not installable" and act accordingly
final List<InstallableResource> r = new ArrayList<InstallableResource>();
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-needsB.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.0.jar"))[0]);
r.add(getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-snap.jar"), "digest1")[0]);
installer.registerResources(URL_SCHEME, r.toArray(new InstallableResource[r.size()]));
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.STOPPED),
new BundleEvent("osgi-installer-testB", org.osgi.framework.BundleEvent.UNINSTALLED),
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.UPDATED),
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.STARTED));
assertBundle("Snapshot bundle must be started",
"osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
assertNull("Bundle testB must be gone", findBundle("osgi-installer-testB"));
final Bundle b = assertBundle("Bundle needsB must still be present",
"osgi-installer-needsB", "1.0", -1);
final int state = b.getState();
assertFalse("Bundle needsB must be stopped as testB is gone (" + state + ")", Bundle.ACTIVE == state);
assertBundle("Testbundle must be back to 1.0 as 1.1 and 1.2 is gone",
"osgi-installer-testbundle", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
{
final Object listener = this.startObservingBundleEvents();
// Re-add the missing bundles and recheck
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testB-1.0.jar")), null);
installer.updateResources(URL_SCHEME, getInstallableResource(getTestBundle(BUNDLE_BASE_NAME + "-testbundle-1.2.jar")), null);
this.waitForBundleEvents("Bundles must be installed and started.", listener,
new BundleEvent("osgi-installer-testbundle", org.osgi.framework.BundleEvent.UPDATED),
new BundleEvent("osgi-installer-testbundle", "1.2", org.osgi.framework.BundleEvent.STARTED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.INSTALLED),
new BundleEvent("osgi-installer-testB", "1.0", org.osgi.framework.BundleEvent.STARTED));
final String info = "After re-adding missing bundles";
assertBundle(info, "osgi-installer-testB", "1.0", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-testbundle", "1.2", Bundle.ACTIVE);
assertBundle(info, "osgi-installer-snapshot-test", "1.0.0.SNAPSHOT", Bundle.ACTIVE);
final Bundle b = findBundle("osgi-installer-needsB");
b.start();
assertBundle("After reinstalling testB, needsB must be startable, ",
"osgi-installer-needsB", "1.0", Bundle.ACTIVE);
assertBundle("testA bundle should still be present", "osgi-installer-testA", "1.0", Bundle.ACTIVE);
}
}
|
diff --git a/src/main/java/com/TeamNovus/Supernaturals/Custom/Effect/EffectTypes/BlindingArrow.java b/src/main/java/com/TeamNovus/Supernaturals/Custom/Effect/EffectTypes/BlindingArrow.java
index c6ceb8f..7bde072 100644
--- a/src/main/java/com/TeamNovus/Supernaturals/Custom/Effect/EffectTypes/BlindingArrow.java
+++ b/src/main/java/com/TeamNovus/Supernaturals/Custom/Effect/EffectTypes/BlindingArrow.java
@@ -1,47 +1,47 @@
package com.TeamNovus.Supernaturals.Custom.Effect.EffectTypes;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.TeamNovus.Supernaturals.SNPlayers;
import com.TeamNovus.Supernaturals.Custom.Effect.Effect;
import com.TeamNovus.Supernaturals.Custom.Effect.EffectType;
import com.TeamNovus.Supernaturals.Events.EntityDamageEntityByProjectileEvent;
import com.TeamNovus.Supernaturals.Events.EntityEffectBeginEvent;
import com.TeamNovus.Supernaturals.Events.EntityEffectExpireEvent;
import com.TeamNovus.Supernaturals.Player.SNPlayer;
public class BlindingArrow extends EffectType {
public void onEffectBegin(EntityEffectBeginEvent event) {
if(event.getEntity() instanceof Player) {
SNPlayer player = SNPlayers.i.get((Player) event.getEntity());
player.getPlayer().setSneaking(true);
player.sendMessage(ChatColor.GREEN + "Your arrows occasionally blind your enemies!");
}
}
public void onEntityDamageEntityByProjectile(EntityDamageEntityByProjectileEvent event, Effect effect) {
if(new Random().nextInt(101) <= effect.getAmplifier()) {
- if(event.getEntity() instanceof LivingEntity) {
- LivingEntity target = (LivingEntity) event.getEntity();
+ if(event.getDamaged() instanceof LivingEntity) {
+ LivingEntity target = (LivingEntity) event.getDamaged();
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5 * effect.getAmplifier(), effect.getAmplifier()));
}
}
}
public void onEffectExpire(EntityEffectExpireEvent event) {
if(event.getEntity() instanceof Player) {
SNPlayer player = SNPlayers.i.get((Player) event.getEntity());
player.getPlayer().setSneaking(true);
player.sendMessage(ChatColor.RED + "Your arrows no longer blind your enemies!");
}
}
}
| true | true | public void onEntityDamageEntityByProjectile(EntityDamageEntityByProjectileEvent event, Effect effect) {
if(new Random().nextInt(101) <= effect.getAmplifier()) {
if(event.getEntity() instanceof LivingEntity) {
LivingEntity target = (LivingEntity) event.getEntity();
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5 * effect.getAmplifier(), effect.getAmplifier()));
}
}
}
| public void onEntityDamageEntityByProjectile(EntityDamageEntityByProjectileEvent event, Effect effect) {
if(new Random().nextInt(101) <= effect.getAmplifier()) {
if(event.getDamaged() instanceof LivingEntity) {
LivingEntity target = (LivingEntity) event.getDamaged();
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5 * effect.getAmplifier(), effect.getAmplifier()));
}
}
}
|
diff --git a/h2/src/test/org/h2/test/unit/TestDataPage.java b/h2/src/test/org/h2/test/unit/TestDataPage.java
index 00af2844c..b30665a34 100644
--- a/h2/src/test/org/h2/test/unit/TestDataPage.java
+++ b/h2/src/test/org/h2/test/unit/TestDataPage.java
@@ -1,329 +1,330 @@
/*
* Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import org.h2.store.Data;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.store.LobStorage;
import org.h2.test.TestBase;
import org.h2.tools.SimpleResultSet;
import org.h2.util.SmallLRUCache;
import org.h2.util.TempFileDeleter;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueByte;
import org.h2.value.ValueBytes;
import org.h2.value.ValueDate;
import org.h2.value.ValueDecimal;
import org.h2.value.ValueDouble;
import org.h2.value.ValueFloat;
import org.h2.value.ValueInt;
import org.h2.value.ValueJavaObject;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueResultSet;
import org.h2.value.ValueShort;
import org.h2.value.ValueString;
import org.h2.value.ValueStringFixed;
import org.h2.value.ValueStringIgnoreCase;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueUuid;
/**
* Data page tests.
*/
public class TestDataPage extends TestBase implements DataHandler {
private boolean testPerformance;
private CompareMode compareMode = CompareMode.getInstance(null, 0);
/**
* Run just this test.
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
public void test() {
if (testPerformance) {
testPerformance();
System.exit(0);
return;
}
testValues();
testAll();
}
private static void testPerformance() {
Data data = Data.create(null, 1024);
for (int j = 0; j < 4; j++) {
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
data.reset();
for (int k = 0; k < 30; k++) {
data.writeString("Hello World");
}
}
// for (int i = 0; i < 5000000; i++) {
// data.reset();
// for (int k = 0; k < 100; k++) {
// data.writeInt(k * k);
// }
// }
// for (int i = 0; i < 200000; i++) {
// data.reset();
// for (int k = 0; k < 100; k++) {
// data.writeVarInt(k * k);
// }
// }
System.out.println("write: " + (System.currentTimeMillis() - time) + " ms");
}
for (int j = 0; j < 4; j++) {
long time = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
data.reset();
for (int k = 0; k < 30; k++) {
data.readString();
}
}
// for (int i = 0; i < 3000000; i++) {
// data.reset();
// for (int k = 0; k < 100; k++) {
// data.readVarInt();
// }
// }
// for (int i = 0; i < 50000000; i++) {
// data.reset();
// for (int k = 0; k < 100; k++) {
// data.readInt();
// }
// }
System.out.println("read: " + (System.currentTimeMillis() - time) + " ms");
}
}
private void testValues() {
testValue(ValueNull.INSTANCE);
testValue(ValueBoolean.get(false));
testValue(ValueBoolean.get(true));
for (int i = 0; i < 256; i++) {
testValue(ValueByte.get((byte) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueShort.get((short) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueInt.get(i));
testValue(ValueInt.get(-i));
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueInt.get(Integer.MAX_VALUE));
testValue(ValueInt.get(Integer.MIN_VALUE));
for (long i = 0; i < Integer.MAX_VALUE; i += 10 + i / 4) {
testValue(ValueInt.get((int) i));
testValue(ValueInt.get((int) -i));
}
testValue(ValueLong.get(Long.MAX_VALUE));
testValue(ValueLong.get(Long.MIN_VALUE));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueDecimal.get(BigDecimal.ZERO));
testValue(ValueDecimal.get(BigDecimal.ONE));
testValue(ValueDecimal.get(BigDecimal.TEN));
testValue(ValueDecimal.get(BigDecimal.ONE.negate()));
testValue(ValueDecimal.get(BigDecimal.TEN.negate()));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueDecimal.get(new BigDecimal(i)));
testValue(ValueDecimal.get(new BigDecimal(-i)));
for (int j = 0; j < 200; j += 50) {
testValue(ValueDecimal.get(new BigDecimal(i).setScale(j)));
testValue(ValueDecimal.get(new BigDecimal(i * i).setScale(j)));
}
testValue(ValueDecimal.get(new BigDecimal(i * i)));
}
testValue(ValueDate.get(new Date(System.currentTimeMillis())));
testValue(ValueDate.get(new Date(0)));
testValue(ValueTime.get(new Time(System.currentTimeMillis())));
testValue(ValueTime.get(new Time(0)));
testValue(ValueTimestamp.get(new Timestamp(System.currentTimeMillis())));
testValue(ValueTimestamp.get(new Timestamp(0)));
testValue(ValueJavaObject.getNoCopy(new byte[0]));
testValue(ValueJavaObject.getNoCopy(new byte[100]));
for (int i = 0; i < 300; i++) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
testValue(ValueUuid.getNewRandom());
for (int i = 0; i < 100; i++) {
testValue(ValueString.get(new String(new char[i])));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueString.get(new String(new char[i])));
testValue(ValueStringFixed.get(new String(new char[i])));
testValue(ValueStringIgnoreCase.get(new String(new char[i])));
}
testValue(ValueFloat.get(0f));
testValue(ValueFloat.get(1f));
testValue(ValueFloat.get(-1f));
testValue(ValueDouble.get(0));
testValue(ValueDouble.get(1));
testValue(ValueDouble.get(-1));
for (int i = 0; i < 65000; i += 10 + i) {
for (double j = 0.1; j < 65000; j += 10 + j) {
testValue(ValueFloat.get((float) (i / j)));
testValue(ValueDouble.get(i / j));
testValue(ValueFloat.get((float) -(i / j)));
testValue(ValueDouble.get(-(i / j)));
}
}
testValue(ValueArray.get(new Value[0]));
testValue(ValueArray.get(new Value[] {ValueBoolean.get(true), ValueInt.get(10)}));
SimpleResultSet rs = new SimpleResultSet();
+ rs.setAutoClose(false);
rs.addColumn("ID", Types.INTEGER, 0, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addRow(1, "Hello");
rs.addRow(2, "World");
rs.addRow(3, "Peace");
testValue(ValueResultSet.get(rs));
}
private void testValue(Value v) {
Data data = Data.create(null, 1024);
data.checkCapacity((int) v.getPrecision());
data.writeValue(v);
data.writeInt(123);
data.reset();
Value v2 = data.readValue();
assertEquals(v.getType(), v2.getType());
assertEquals(0, v.compareTo(v2, compareMode));
assertEquals(123, data.readInt());
}
private void testAll() {
Data page = Data.create(this, 128);
char[] data = new char[0x10000];
for (int i = 0; i < data.length; i++) {
data[i] = (char) i;
}
String s = new String(data);
page.checkCapacity(s.length() * 4);
page.writeString(s);
int len = page.length();
assertEquals(len, Data.getStringLen(s));
page.reset();
assertEquals(s, page.readString());
page.reset();
page.writeString("H\u1111!");
page.writeString("John\tBrack's \"how are you\" M\u1111ller");
page.writeValue(ValueInt.get(10));
page.writeValue(ValueString.get("test"));
page.writeValue(ValueFloat.get(-2.25f));
page.writeValue(ValueDouble.get(10.40));
page.writeValue(ValueNull.INSTANCE);
trace(new String(page.getBytes()));
page.reset();
trace(page.readString());
trace(page.readString());
trace(page.readValue().getInt());
trace(page.readValue().getString());
trace("" + page.readValue().getFloat());
trace("" + page.readValue().getDouble());
trace(page.readValue().toString());
page.reset();
page.writeInt(0);
page.writeInt(Integer.MAX_VALUE);
page.writeInt(Integer.MIN_VALUE);
page.writeInt(1);
page.writeInt(-1);
page.writeInt(1234567890);
page.writeInt(54321);
trace(new String(page.getBytes()));
page.reset();
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
page = null;
}
public String getDatabasePath() {
return null;
}
public FileStore openFile(String name, String mode, boolean mustExist) {
return null;
}
public void checkPowerOff() {
// nothing to do
}
public void checkWritingAllowed() {
// ok
}
public void freeUpDiskSpace() {
// nothing to do
}
public int getMaxLengthInplaceLob() {
throw new AssertionError();
}
public String getLobCompressionAlgorithm(int type) {
throw new AssertionError();
}
public Object getLobSyncObject() {
return this;
}
public SmallLRUCache<String, String[]> getLobFileListCache() {
return null;
}
public TempFileDeleter getTempFileDeleter() {
return TempFileDeleter.getInstance();
}
public LobStorage getLobStorage() {
return null;
}
public Connection getLobConnection() {
return null;
}
}
| true | true | private void testValues() {
testValue(ValueNull.INSTANCE);
testValue(ValueBoolean.get(false));
testValue(ValueBoolean.get(true));
for (int i = 0; i < 256; i++) {
testValue(ValueByte.get((byte) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueShort.get((short) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueInt.get(i));
testValue(ValueInt.get(-i));
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueInt.get(Integer.MAX_VALUE));
testValue(ValueInt.get(Integer.MIN_VALUE));
for (long i = 0; i < Integer.MAX_VALUE; i += 10 + i / 4) {
testValue(ValueInt.get((int) i));
testValue(ValueInt.get((int) -i));
}
testValue(ValueLong.get(Long.MAX_VALUE));
testValue(ValueLong.get(Long.MIN_VALUE));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueDecimal.get(BigDecimal.ZERO));
testValue(ValueDecimal.get(BigDecimal.ONE));
testValue(ValueDecimal.get(BigDecimal.TEN));
testValue(ValueDecimal.get(BigDecimal.ONE.negate()));
testValue(ValueDecimal.get(BigDecimal.TEN.negate()));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueDecimal.get(new BigDecimal(i)));
testValue(ValueDecimal.get(new BigDecimal(-i)));
for (int j = 0; j < 200; j += 50) {
testValue(ValueDecimal.get(new BigDecimal(i).setScale(j)));
testValue(ValueDecimal.get(new BigDecimal(i * i).setScale(j)));
}
testValue(ValueDecimal.get(new BigDecimal(i * i)));
}
testValue(ValueDate.get(new Date(System.currentTimeMillis())));
testValue(ValueDate.get(new Date(0)));
testValue(ValueTime.get(new Time(System.currentTimeMillis())));
testValue(ValueTime.get(new Time(0)));
testValue(ValueTimestamp.get(new Timestamp(System.currentTimeMillis())));
testValue(ValueTimestamp.get(new Timestamp(0)));
testValue(ValueJavaObject.getNoCopy(new byte[0]));
testValue(ValueJavaObject.getNoCopy(new byte[100]));
for (int i = 0; i < 300; i++) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
testValue(ValueUuid.getNewRandom());
for (int i = 0; i < 100; i++) {
testValue(ValueString.get(new String(new char[i])));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueString.get(new String(new char[i])));
testValue(ValueStringFixed.get(new String(new char[i])));
testValue(ValueStringIgnoreCase.get(new String(new char[i])));
}
testValue(ValueFloat.get(0f));
testValue(ValueFloat.get(1f));
testValue(ValueFloat.get(-1f));
testValue(ValueDouble.get(0));
testValue(ValueDouble.get(1));
testValue(ValueDouble.get(-1));
for (int i = 0; i < 65000; i += 10 + i) {
for (double j = 0.1; j < 65000; j += 10 + j) {
testValue(ValueFloat.get((float) (i / j)));
testValue(ValueDouble.get(i / j));
testValue(ValueFloat.get((float) -(i / j)));
testValue(ValueDouble.get(-(i / j)));
}
}
testValue(ValueArray.get(new Value[0]));
testValue(ValueArray.get(new Value[] {ValueBoolean.get(true), ValueInt.get(10)}));
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 0, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addRow(1, "Hello");
rs.addRow(2, "World");
rs.addRow(3, "Peace");
testValue(ValueResultSet.get(rs));
}
| private void testValues() {
testValue(ValueNull.INSTANCE);
testValue(ValueBoolean.get(false));
testValue(ValueBoolean.get(true));
for (int i = 0; i < 256; i++) {
testValue(ValueByte.get((byte) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueShort.get((short) i));
}
for (int i = 0; i < 256 * 256; i += 10) {
testValue(ValueInt.get(i));
testValue(ValueInt.get(-i));
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueInt.get(Integer.MAX_VALUE));
testValue(ValueInt.get(Integer.MIN_VALUE));
for (long i = 0; i < Integer.MAX_VALUE; i += 10 + i / 4) {
testValue(ValueInt.get((int) i));
testValue(ValueInt.get((int) -i));
}
testValue(ValueLong.get(Long.MAX_VALUE));
testValue(ValueLong.get(Long.MIN_VALUE));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueLong.get(i));
testValue(ValueLong.get(-i));
}
testValue(ValueDecimal.get(BigDecimal.ZERO));
testValue(ValueDecimal.get(BigDecimal.ONE));
testValue(ValueDecimal.get(BigDecimal.TEN));
testValue(ValueDecimal.get(BigDecimal.ONE.negate()));
testValue(ValueDecimal.get(BigDecimal.TEN.negate()));
for (long i = 0; i >= 0; i += 10 + i / 4) {
testValue(ValueDecimal.get(new BigDecimal(i)));
testValue(ValueDecimal.get(new BigDecimal(-i)));
for (int j = 0; j < 200; j += 50) {
testValue(ValueDecimal.get(new BigDecimal(i).setScale(j)));
testValue(ValueDecimal.get(new BigDecimal(i * i).setScale(j)));
}
testValue(ValueDecimal.get(new BigDecimal(i * i)));
}
testValue(ValueDate.get(new Date(System.currentTimeMillis())));
testValue(ValueDate.get(new Date(0)));
testValue(ValueTime.get(new Time(System.currentTimeMillis())));
testValue(ValueTime.get(new Time(0)));
testValue(ValueTimestamp.get(new Timestamp(System.currentTimeMillis())));
testValue(ValueTimestamp.get(new Timestamp(0)));
testValue(ValueJavaObject.getNoCopy(new byte[0]));
testValue(ValueJavaObject.getNoCopy(new byte[100]));
for (int i = 0; i < 300; i++) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueBytes.getNoCopy(new byte[i]));
}
testValue(ValueUuid.getNewRandom());
for (int i = 0; i < 100; i++) {
testValue(ValueString.get(new String(new char[i])));
}
for (int i = 0; i < 65000; i += 10 + i) {
testValue(ValueString.get(new String(new char[i])));
testValue(ValueStringFixed.get(new String(new char[i])));
testValue(ValueStringIgnoreCase.get(new String(new char[i])));
}
testValue(ValueFloat.get(0f));
testValue(ValueFloat.get(1f));
testValue(ValueFloat.get(-1f));
testValue(ValueDouble.get(0));
testValue(ValueDouble.get(1));
testValue(ValueDouble.get(-1));
for (int i = 0; i < 65000; i += 10 + i) {
for (double j = 0.1; j < 65000; j += 10 + j) {
testValue(ValueFloat.get((float) (i / j)));
testValue(ValueDouble.get(i / j));
testValue(ValueFloat.get((float) -(i / j)));
testValue(ValueDouble.get(-(i / j)));
}
}
testValue(ValueArray.get(new Value[0]));
testValue(ValueArray.get(new Value[] {ValueBoolean.get(true), ValueInt.get(10)}));
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
rs.addColumn("ID", Types.INTEGER, 0, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addRow(1, "Hello");
rs.addRow(2, "World");
rs.addRow(3, "Peace");
testValue(ValueResultSet.get(rs));
}
|
diff --git a/src/com/imeeting/mvc/controller/ProfileController.java b/src/com/imeeting/mvc/controller/ProfileController.java
index bfc3f57..571a8f7 100644
--- a/src/com/imeeting/mvc/controller/ProfileController.java
+++ b/src/com/imeeting/mvc/controller/ProfileController.java
@@ -1,85 +1,85 @@
package com.imeeting.mvc.controller;
import java.io.File;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.imeeting.framework.Configuration;
import com.imeeting.framework.ContextLoader;
import com.imeeting.web.user.UserBean;
import com.richitec.ucenter.model.UserDAO;
import com.richitec.util.MD5Util;
import com.richitec.util.RandomString;
@Controller
@RequestMapping(value="/profile")
public class ProfileController {
private static Log log = LogFactory.getLog(ProfileController.class);
private Configuration config;
private UserDAO userDao;
@PostConstruct
public void init(){
config = ContextLoader.getConfiguration();
userDao = ContextLoader.getUserDAO();
}
@RequestMapping(value="/changepassword", method=RequestMethod.POST)
public @ResponseBody String changePassword(
HttpSession session,
HttpServletResponse response,
@RequestParam(value="oldPwd") String oldPwd,
@RequestParam(value="newPwd") String newPwd,
@RequestParam(value="newPwdConfirm") String newPwdConfirm) throws IOException{
UserBean user = (UserBean) session.getAttribute(UserBean.SESSION_BEAN);
if (!oldPwd.equals(user.getPassword())){
- return "403";
+ return "400";
}
if (newPwd.isEmpty() || !newPwd.equals(newPwdConfirm)){
- return "400";
+ return "403";
}
String md5Password = MD5Util.md5(newPwd);
if (userDao.changePassword(user.getName(), md5Password)<=0){
return "500";
}
user.setPassword(md5Password);
return "200";
}
@RequestMapping(value="/avatar", method=RequestMethod.GET)
public String uploadAvatar(){
return "avatar";
}
@RequestMapping(value="/avatar", method=RequestMethod.POST)
public String avatarHandler(
@RequestParam("username") String username,
@RequestParam("avatar") MultipartFile avatarFile) throws IllegalStateException, IOException{
log.info("Username: " + username);
log.info("File Origin Name: " + avatarFile.getOriginalFilename());
log.info("File Name: " + avatarFile.getName());
log.info("File Size: " + avatarFile.getSize());
String tmpDir = config.getUploadDir();
String source_id = "im_" + RandomString.genRandomNum(10);
String tmpFile = tmpDir + source_id;
avatarFile.transferTo(new File(tmpFile));
return "avatar";
}
}
| false | true | public @ResponseBody String changePassword(
HttpSession session,
HttpServletResponse response,
@RequestParam(value="oldPwd") String oldPwd,
@RequestParam(value="newPwd") String newPwd,
@RequestParam(value="newPwdConfirm") String newPwdConfirm) throws IOException{
UserBean user = (UserBean) session.getAttribute(UserBean.SESSION_BEAN);
if (!oldPwd.equals(user.getPassword())){
return "403";
}
if (newPwd.isEmpty() || !newPwd.equals(newPwdConfirm)){
return "400";
}
String md5Password = MD5Util.md5(newPwd);
if (userDao.changePassword(user.getName(), md5Password)<=0){
return "500";
}
user.setPassword(md5Password);
return "200";
}
| public @ResponseBody String changePassword(
HttpSession session,
HttpServletResponse response,
@RequestParam(value="oldPwd") String oldPwd,
@RequestParam(value="newPwd") String newPwd,
@RequestParam(value="newPwdConfirm") String newPwdConfirm) throws IOException{
UserBean user = (UserBean) session.getAttribute(UserBean.SESSION_BEAN);
if (!oldPwd.equals(user.getPassword())){
return "400";
}
if (newPwd.isEmpty() || !newPwd.equals(newPwdConfirm)){
return "403";
}
String md5Password = MD5Util.md5(newPwd);
if (userDao.changePassword(user.getName(), md5Password)<=0){
return "500";
}
user.setPassword(md5Password);
return "200";
}
|
diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java
index 4985e9283..560e5021b 100644
--- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java
+++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java
@@ -1,1643 +1,1643 @@
/*******************************************************************************
* Copyright (c) 2000, 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.ui.texteditor;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import com.ibm.icu.text.MessageFormat;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.commands.operations.IOperationApprover;
import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.IFileBufferStatusCodes;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewerExtension6;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.revisions.IRevisionRulerColumn;
import org.eclipse.jface.text.revisions.IRevisionRulerColumnExtension;
import org.eclipse.jface.text.revisions.RevisionInformation;
import org.eclipse.jface.text.revisions.IRevisionRulerColumnExtension.RenderingMode;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.ChangeRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationAccessExtension2;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IChangeRulerColumn;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.ISourceViewerExtension3;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.LineNumberChangeRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.ForwardingDocumentProvider;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.editors.text.ITextEditorHelpContextIds;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IURIEditorInput;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.internal.editors.quickdiff.CompositeRevertAction;
import org.eclipse.ui.internal.editors.quickdiff.RestoreAction;
import org.eclipse.ui.internal.editors.quickdiff.RevertBlockAction;
import org.eclipse.ui.internal.editors.quickdiff.RevertLineAction;
import org.eclipse.ui.internal.editors.quickdiff.RevertSelectionAction;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.internal.editors.text.NLSUtility;
import org.eclipse.ui.internal.texteditor.AnnotationColumn;
import org.eclipse.ui.internal.texteditor.BooleanPreferenceToggleAction;
import org.eclipse.ui.internal.texteditor.LineNumberColumn;
import org.eclipse.ui.internal.texteditor.TextChangeHover;
import org.eclipse.ui.keys.IBindingService;
import org.eclipse.ui.operations.NonLocalUndoUserApprover;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.rulers.IColumnSupport;
import org.eclipse.ui.texteditor.rulers.IContributedRulerColumn;
import org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor;
import org.eclipse.ui.texteditor.rulers.RulerColumnPreferenceAdapter;
import org.eclipse.ui.texteditor.rulers.RulerColumnRegistry;
import org.eclipse.ui.views.markers.MarkerViewUtil;
/**
* An intermediate editor comprising functionality not present in the leaner <code>AbstractTextEditor</code>,
* but used in many heavy weight (and especially source editing) editors, such as line numbers,
* change ruler, overview ruler, print margins, current line highlighting, etc.
*
* @since 3.0
*/
public abstract class AbstractDecoratedTextEditor extends StatusTextEditor {
/**
* Preference key for showing the line number ruler.
*/
private final static String LINE_NUMBER_RULER= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/**
* Preference key for showing the overview ruler.
*/
private final static String OVERVIEW_RULER= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER;
/**
* Preference key for highlighting current line.
*/
private final static String CURRENT_LINE= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE;
/**
* Preference key for highlight color of current line.
*/
private final static String CURRENT_LINE_COLOR= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/**
* Preference key for showing print margin ruler.
*/
private final static String PRINT_MARGIN= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN;
/**
* Preference key for print margin ruler color.
*/
private final static String PRINT_MARGIN_COLOR= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/**
* Preference key for print margin ruler column.
*/
private final static String PRINT_MARGIN_COLUMN= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/**
* Preference key to get whether the overwrite mode is disabled.
* @since 3.1
*/
private final static String DISABLE_OVERWRITE_MODE= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE;
/**
* Adapter class for <code>IGotoMarker</code>.
*/
private class GotoMarkerAdapter implements IGotoMarker {
public void gotoMarker(IMarker marker) {
AbstractDecoratedTextEditor.this.gotoMarker(marker);
}
}
/**
* The annotation preferences.
*/
private MarkerAnnotationPreferences fAnnotationPreferences;
/**
* The overview ruler of this editor.
*
* <p>This field should not be referenced by subclasses. It is <code>protected</code> for API
* compatibility reasons and will be made <code>private</code> soon. Use
* {@link #getOverviewRuler()} instead.</p>
*/
protected IOverviewRuler fOverviewRuler;
/**
* Helper for accessing annotation from the perspective of this editor.
*
* <p>This field should not be referenced by subclasses. It is <code>protected</code> for API
* compatibility reasons and will be made <code>private</code> soon. Use
* {@link #getAnnotationAccess()} instead.</p>
*/
protected IAnnotationAccess fAnnotationAccess;
/**
* Helper for managing the decoration support of this editor's viewer.
*
* <p>This field should not be referenced by subclasses. It is <code>protected</code> for API
* compatibility reasons and will be made <code>private</code> soon. Use
* {@link #getSourceViewerDecorationSupport(ISourceViewer)} instead.</p>
*/
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/**
* The line number column.
*
* <p>This field should not be referenced by subclasses. It is <code>protected</code> for API
* compatibility reasons and will be made <code>private</code> soon. Use
* {@link AbstractTextEditor#getVerticalRuler()} to access the vertical bar instead.</p>
*/
protected LineNumberRulerColumn fLineNumberRulerColumn;
/**
* The delegating line number ruler contribution.
* @since 3.3
*/
private LineNumberColumn fLineColumn;
/**
* The editor's implicit document provider.
*/
private IDocumentProvider fImplicitDocumentProvider;
/**
* The editor's goto marker adapter.
*/
private Object fGotoMarkerAdapter= new GotoMarkerAdapter();
/**
* Indicates whether this editor is updating views that show markers.
* @see #updateMarkerViews(Annotation)
* @since 3.2
*/
protected boolean fIsUpdatingMarkerViews= false;
/**
* Tells whether editing the current derived editor input is allowed.
* @since 3.3
*/
private boolean fIsEditingDerivedFileAllowed= true;
/**
* Tells whether the derived state has been validated.
* @since 3.3
*/
private boolean fIsDerivedStateValidated= false;
/*
* Workaround for IllegalAccessError thrown because we are accessing
* a protected method in a different bundle from an inner class.
*/
private IVerticalRuler internalGetVerticalRuler() {
return getVerticalRuler();
}
/**
* Creates a new text editor.
*/
public AbstractDecoratedTextEditor() {
super();
fAnnotationPreferences= EditorsPlugin.getDefault().getMarkerAnnotationPreferences();
setRangeIndicator(new DefaultRangeIndicator());
initializeKeyBindingScopes();
initializeEditor();
}
/**
* Initializes this editor. Subclasses may re-implement. If sub-classes do
* not change the contract, this method should not be extended, i.e. do not
* call <code>super.initializeEditor()</code> in order to avoid the
* temporary creation of objects that are immediately overwritten by
* subclasses.
*/
protected void initializeEditor() {
setPreferenceStore(EditorsPlugin.getDefault().getPreferenceStore());
}
/**
* Initializes the key binding scopes of this editor.
*/
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope" }); //$NON-NLS-1$
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= null;
}
fAnnotationAccess= null;
fAnnotationPreferences= null;
fLineNumberRulerColumn= null;
fLineColumn= null;
super.dispose();
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
fAnnotationAccess= getAnnotationAccess();
fOverviewRuler= createOverviewRuler(getSharedColors());
ISourceViewer viewer= new SourceViewer(parent, ruler, getOverviewRuler(), isOverviewRulerVisible(), styles);
// ensure decoration support has been created and configured.
getSourceViewerDecorationSupport(viewer);
return viewer;
}
protected ISharedTextColors getSharedColors() {
ISharedTextColors sharedColors= EditorsPlugin.getDefault().getSharedTextColors();
return sharedColors;
}
protected IOverviewRuler createOverviewRuler(ISharedTextColors sharedColors) {
IOverviewRuler ruler= new OverviewRuler(getAnnotationAccess(), VERTICAL_RULER_WIDTH, sharedColors);
Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator();
while (e.hasNext()) {
AnnotationPreference preference= (AnnotationPreference) e.next();
if (preference.contributesToHeader())
ruler.addHeaderAnnotationType(preference.getAnnotationType());
}
return ruler;
}
/**
* Creates the annotation access for this editor.
*
* @return the created annotation access
*/
protected IAnnotationAccess createAnnotationAccess() {
return new DefaultMarkerAnnotationAccess();
}
/**
* Configures the decoration support for this editor's source viewer. Subclasses may override this
* method, but should call their superclass' implementation at some point.
*
* @param support the decoration support to configure
*/
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator();
while (e.hasNext())
support.setAnnotationPreference((AnnotationPreference) e.next());
support.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
support.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
support.setSymbolicFontName(getFontPropertyPreferenceKey());
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
if (fSourceViewerDecorationSupport != null)
fSourceViewerDecorationSupport.install(getPreferenceStore());
IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class);
if (isLineNumberRulerVisible()) {
RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID);
if (lineNumberColumnDescriptor != null)
columnSupport.setColumnVisible(lineNumberColumnDescriptor, true);
}
if (isPrefQuickDiffAlwaysOn())
showChangeInformation(true);
if (!isOverwriteModeEnabled())
enableOverwriteMode(false);
if (!isRangeIndicatorEnabled()) {
getSourceViewer().removeRangeIndication();
getSourceViewer().setRangeIndicator(null);
}
// Assign the quick assist assistant to the annotation access.
ISourceViewer viewer= getSourceViewer();
if (fAnnotationAccess instanceof IAnnotationAccessExtension2 && viewer instanceof ISourceViewerExtension3)
((IAnnotationAccessExtension2)fAnnotationAccess).setQuickAssistAssistant(((ISourceViewerExtension3)viewer).getQuickAssistAssistant());
}
/*
* @see org.eclipse.ui.texteditor.StatusTextEditor#createStatusControl(org.eclipse.swt.widgets.Composite, org.eclipse.core.runtime.IStatus)
* @since 3.1
*/
protected Control createStatusControl(Composite parent, final IStatus status) {
Object adapter= getAdapter(IEncodingSupport.class);
DefaultEncodingSupport encodingSupport= null;
if (adapter instanceof DefaultEncodingSupport)
encodingSupport= (DefaultEncodingSupport)adapter;
if (encodingSupport == null || !encodingSupport.isEncodingError(status))
return super.createStatusControl(parent, status);
Shell shell= getSite().getShell();
Display display= shell.getDisplay();
Color bgColor= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
Color fgColor= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
composite.setBackground(bgColor);
composite.setForeground(fgColor);
Control control= super.createStatusControl(composite, status);
control.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite buttonComposite= new Composite(composite, SWT.NONE);
buttonComposite.setLayout(new GridLayout());
buttonComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
buttonComposite.setBackground(bgColor);
buttonComposite.setForeground(fgColor);
encodingSupport.createStatusEncodingChangeControl(buttonComposite, status);
//
// Button button= new Button(buttonComposite, SWT.PUSH | SWT.FLAT);
// button.setText(action.getText());
// button.addSelectionListener(new SelectionAdapter() {
// /*
// * @see org.eclipse.swt.events.SelectionAdapter#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
// */
// public void widgetSelected(SelectionEvent e) {
// action.run();
// }
// });
//
// Label filler= new Label(buttonComposite, SWT.NONE);
// filler.setLayoutData(new GridData(GridData.FILL_BOTH));
// filler.setBackground(bgColor);
//
return composite;
}
/**
* Tells whether the overview ruler is visible.
*
* @return whether the overview ruler is visible
*/
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store != null ? store.getBoolean(OVERVIEW_RULER) : false;
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean)
*/
public void showChangeInformation(boolean show) {
if (show == isChangeInformationShowing())
return;
IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class);
// only handle visibility of the combined column, but not the number/change only state
if (show && fLineColumn == null) {
RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID);
if (lineNumberColumnDescriptor != null)
columnSupport.setColumnVisible(lineNumberColumnDescriptor, true);
} else if (!show && fLineColumn != null && isLineNumberRulerVisible()) {
columnSupport.setColumnVisible(fLineColumn.getDescriptor(), false);
fLineColumn= null;
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing()
*/
public boolean isChangeInformationShowing() {
return fLineColumn != null && fLineColumn.isShowingChangeInformation();
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension4#showRevisionInformation(org.eclipse.jface.text.revisions.RevisionInformation, java.lang.String)
* @since 3.2
*/
public void showRevisionInformation(RevisionInformation info, String quickDiffProviderId) {
showChangeInformation(true);
if (fLineColumn != null)
fLineColumn.showRevisionInformation(info, quickDiffProviderId);
}
/**
* Returns whether the line number ruler column should be
* visible according to the preference store settings. Subclasses may override this
* method to provide a custom preference setting.
*
* @return <code>true</code> if the line numbers should be visible
*/
protected boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store != null ? store.getBoolean(LINE_NUMBER_RULER) : false;
}
/**
* Returns whether the overwrite mode is enabled according to the preference
* store settings. Subclasses may override this method to provide a custom
* preference setting.
*
* @return <code>true</code> if overwrite mode is enabled
* @since 3.1
*/
protected boolean isOverwriteModeEnabled() {
IPreferenceStore store= getPreferenceStore();
return store != null ? !store.getBoolean(DISABLE_OVERWRITE_MODE) : true;
}
/**
* Returns whether the range indicator is enabled according to the preference
* store settings. Subclasses may override this method to provide a custom
* preference setting.
*
* @return <code>true</code> if overwrite mode is enabled
* @since 3.1
*/
private boolean isRangeIndicatorEnabled() {
IPreferenceStore store= getPreferenceStore();
return store != null ? store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.SHOW_RANGE_INDICATOR) : true;
}
/**
* Returns whether quick diff info should be visible upon opening an editor
* according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
*/
protected boolean isPrefQuickDiffAlwaysOn() {
IPreferenceStore store= getPreferenceStore();
boolean setting= store != null ? store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON) : false;
return setting && isEditorInputModifiable();
}
/**
* Initializes the given line number ruler column from the preference store.
*
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
/*
* Left for compatibility. See LineNumberColumn.
*/
if (fLineColumn != null)
fLineColumn.initializeLineNumberRulerColumn(rulerColumn);
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return the created line number column
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
/*
* Left for compatibility. See LineNumberColumn.
*/
fLineNumberRulerColumn= new LineNumberChangeRulerColumn(getSharedColors());
((IChangeRulerColumn) fLineNumberRulerColumn).setHover(createChangeHover());
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/**
* Creates and returns a <code>LineChangeHover</code> to be used on this editor's change
* ruler column. This default implementation returns a plain <code>LineChangeHover</code>.
* Subclasses may override.
*
* @return the change hover to be used by this editors quick diff display
*/
protected LineChangeHover createChangeHover() {
return new TextChangeHover();
}
/**
* Creates a new change ruler column for quick diff display independent of the
* line number ruler column
*
* @return a new change ruler column
* @deprecated as of 3.3. Not called any longer, replaced by {@link #createLineNumberRulerColumn()}
*/
protected IChangeRulerColumn createChangeRulerColumn() {
/*
* Left for compatibility. See LineNumberColumn.
*/
return new ChangeRulerColumn(getSharedColors());
}
/**
* Returns {@link #createCompositeRuler()}. Subclasses should not override this method, but
* rather <code>createCompositeRuler</code> if they want to contribute their own vertical ruler
* implementation. If not an instance of {@link CompositeRuler} is returned, the built-in ruler
* columns (line numbers, annotations) will not work.
*
* <p>May become <code>final</code> in the future.</p>
*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
return createCompositeRuler();
}
/**
* Creates a composite ruler to be used as the vertical ruler by this editor.
* Subclasses may re-implement this method.
*
* @return the vertical ruler
*/
protected CompositeRuler createCompositeRuler() {
return new CompositeRuler();
}
/**
* Creates the annotation ruler column. Subclasses may re-implement or extend.
*
* @param ruler the composite ruler that the column will be added
* @return an annotation ruler column
* @since 3.2
*/
protected IVerticalRulerColumn createAnnotationRulerColumn(CompositeRuler ruler) {
return new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createColumnSupport()
* @since 3.3
*/
protected final IColumnSupport createColumnSupport() {
return new ColumnSupport(this, RulerColumnRegistry.getDefault()) {
/*
* @see org.eclipse.ui.texteditor.rulers.ColumnSupport#initializeColumn(org.eclipse.ui.texteditor.rulers.AbstractContributedRulerColumn)
*/
protected void initializeColumn(IContributedRulerColumn column) {
super.initializeColumn(column);
RulerColumnDescriptor descriptor= column.getDescriptor();
IVerticalRuler ruler= internalGetVerticalRuler();
if (ruler instanceof CompositeRuler) {
if (AnnotationColumn.ID.equals(descriptor.getId())) {
((AnnotationColumn)column).setDelegate(createAnnotationRulerColumn((CompositeRuler) ruler));
} else if (LineNumberColumn.ID.equals(descriptor.getId())) {
fLineColumn= ((LineNumberColumn) column);
fLineColumn.setForwarder(new LineNumberColumn.ICompatibilityForwarder() {
public IVerticalRulerColumn createLineNumberRulerColumn() {
return AbstractDecoratedTextEditor.this.createLineNumberRulerColumn();
}
public boolean isQuickDiffEnabled() {
return AbstractDecoratedTextEditor.this.isPrefQuickDiffAlwaysOn();
}
public boolean isLineNumberRulerVisible() {
return AbstractDecoratedTextEditor.this.isLineNumberRulerVisible();
}
});
}
}
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.ColumnSupport#dispose()
*/
public void dispose() {
fLineColumn= null;
super.dispose();
}
};
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (fSourceViewerDecorationSupport != null && fOverviewRuler != null && OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (DISABLE_OVERWRITE_MODE.equals(property)) {
enableOverwriteMode(isOverwriteModeEnabled());
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
// only handle visibility of the combined column, but not the number/change only state
IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class);
if (isLineNumberRulerVisible() && fLineColumn == null) {
RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID);
if (lineNumberColumnDescriptor != null)
columnSupport.setColumnVisible(lineNumberColumnDescriptor, true);
} else if (!isLineNumberRulerVisible() && fLineColumn != null && !fLineColumn.isShowingChangeInformation()) {
columnSupport.setColumnVisible(fLineColumn.getDescriptor(), false);
fLineColumn= null;
}
return;
}
if (AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON.equals(property)) {
showChangeInformation(isPrefQuickDiffAlwaysOn());
}
if (AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
IPreferenceStore store= getPreferenceStore();
if (store != null)
sourceViewer.getTextWidget().setTabs(store.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH));
return;
}
if (AbstractDecoratedTextEditorPreferenceConstants.EDITOR_UNDO_HISTORY_SIZE.equals(property) && sourceViewer instanceof ITextViewerExtension6) {
IPreferenceStore store= getPreferenceStore();
if (store != null)
((ITextViewerExtension6)sourceViewer).getUndoManager().setMaximalUndoLevel(store.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_UNDO_HISTORY_SIZE));
return;
}
if (AbstractDecoratedTextEditorPreferenceConstants.SHOW_RANGE_INDICATOR.equals(property)) {
if (isRangeIndicatorEnabled()) {
getSourceViewer().setRangeIndicator(getRangeIndicator());
} else {
getSourceViewer().removeRangeIndication();
getSourceViewer().setRangeIndicator(null);
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Shows the overview ruler.
*/
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
/**
* Hides the overview ruler.
*/
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
/**
* Returns the annotation access.
*
* @return the annotation access
*/
protected IAnnotationAccess getAnnotationAccess() {
if (fAnnotationAccess == null)
fAnnotationAccess= createAnnotationAccess();
return fAnnotationAccess;
}
/**
* Returns the annotation preference lookup.
*
* @return the annotation preference lookup
*/
protected AnnotationPreferenceLookup getAnnotationPreferenceLookup() {
return EditorsPlugin.getDefault().getAnnotationPreferenceLookup();
}
/**
* Returns the overview ruler.
*
* @return the overview ruler
*/
protected IOverviewRuler getOverviewRuler() {
if (fOverviewRuler == null)
fOverviewRuler= createOverviewRuler(getSharedColors());
return fOverviewRuler;
}
/**
* Returns the source viewer decoration support.
*
* @param viewer the viewer for which to return a decoration support
* @return the source viewer decoration support
*/
protected SourceViewerDecorationSupport getSourceViewerDecorationSupport(ISourceViewer viewer) {
if (fSourceViewerDecorationSupport == null) {
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, getOverviewRuler(), getAnnotationAccess(), getSharedColors());
configureSourceViewerDecorationSupport(fSourceViewerDecorationSupport);
}
return fSourceViewerDecorationSupport;
}
/**
* Returns the annotation preferences.
*
* @return the annotation preferences
*/
protected MarkerAnnotationPreferences getAnnotationPreferences() {
return fAnnotationPreferences;
}
/**
* If the editor can be saved all marker ranges have been changed according to
* the text manipulations. However, those changes are not yet propagated to the
* marker manager. Thus, when opening a marker, the marker's position in the editor
* must be determined as it might differ from the position stated in the marker.
*
* @param marker the marker to go to
* @deprecated visibility will be reduced, use <code>getAdapter(IGotoMarker.class) for accessing this method</code>
*/
public void gotoMarker(IMarker marker) {
if (fIsUpdatingMarkerViews)
return;
if (getSourceViewer() == null)
return;
int start= MarkerUtilities.getCharStart(marker);
int end= MarkerUtilities.getCharEnd(marker);
boolean selectLine= start < 0 || end < 0;
// look up the current range of the marker when the document has been edited
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
if (model instanceof AbstractMarkerAnnotationModel) {
AbstractMarkerAnnotationModel markerModel= (AbstractMarkerAnnotationModel) model;
Position pos= markerModel.getMarkerPosition(marker);
if (pos != null && !pos.isDeleted()) {
// use position instead of marker values
start= pos.getOffset();
end= pos.getOffset() + pos.getLength();
}
if (pos != null && pos.isDeleted()) {
// do nothing if position has been deleted
return;
}
}
IDocument document= getDocumentProvider().getDocument(getEditorInput());
if (selectLine) {
int line;
try {
if (start >= 0)
line= document.getLineOfOffset(start);
else {
line= MarkerUtilities.getLineNumber(marker);
// Marker line numbers are 1-based
-- line;
start= document.getLineOffset(line);
}
end= start + document.getLineLength(line) - 1;
} catch (BadLocationException e) {
return;
}
}
int length= document.getLength();
if (end - 1 < length && start < length)
selectAndReveal(start, end - start);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditable()
* @since 3.3
*/
public boolean isEditable() {
if (!super.isEditable())
return false;
return fIsEditingDerivedFileAllowed;
}
/*
* @see org.eclipse.ui.texteditor.StatusTextEditor#validateEditorInputState()
* @since 3.3
*/
public boolean validateEditorInputState() {
if (!super.validateEditorInputState())
return false;
return validateEditorInputDerived();
}
/**
* Validates the editor input for derived state.
* If the given input is derived then this method
* can show a dialog asking whether to edit the
* derived file.
*
* @return <code>true</code> if the input is OK for editing, <code>false</code> otherwise
* @since 3.3
*/
private boolean validateEditorInputDerived() {
if (fIsDerivedStateValidated)
return fIsEditingDerivedFileAllowed;
if (getDocumentProvider() instanceof IDocumentProviderExtension) {
IDocumentProviderExtension extension= (IDocumentProviderExtension)getDocumentProvider();
IStatus status= extension.getStatus(getEditorInput());
String pluginId= status.getPlugin();
boolean isDerivedStatus= status.getCode() == IFileBufferStatusCodes.DERIVED_FILE && (FileBuffers.PLUGIN_ID.equals(pluginId) || EditorsUI.PLUGIN_ID.equals(pluginId));
if (!isDerivedStatus)
return true;
}
final String warnKey= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WARN_IF_INPUT_DERIVED;
IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(warnKey))
return true;
MessageDialogWithToggle toggleDialog= MessageDialogWithToggle.openYesNoQuestion(
getSite().getShell(),
TextEditorMessages.AbstractDecoratedTextEditor_warning_derived_title,
TextEditorMessages.AbstractDecoratedTextEditor_warning_derived_message,
TextEditorMessages.AbstractDecoratedTextEditor_warning_derived_dontShowAgain,
false,
null,
null);
EditorsUI.getPreferenceStore().setValue(warnKey, !toggleDialog.getToggleState());
fIsDerivedStateValidated= true;
return fIsEditingDerivedFileAllowed= toggleDialog.getReturnCode() == IDialogConstants.YES_ID;
}
/*
* For an explanation why we override this method see:
* bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=42230
*
* @see org.eclipse.ui.texteditor.StatusTextEditor#isErrorStatus(org.eclipse.core.runtime.IStatus)
*/
protected boolean isErrorStatus(IStatus status) {
if (!super.isErrorStatus(status))
return false;
if (!status.isMultiStatus())
return !isReadOnlyLocalStatus(status);
IStatus[] childrenStatus= status.getChildren();
for (int i= 0; i < childrenStatus.length; i++) {
if (childrenStatus[i].getSeverity() == IStatus.ERROR && !isReadOnlyLocalStatus(childrenStatus[i]))
return true;
}
return false;
}
/**
* Check whether the given status is a <code>IResourceStatus.READ_ONLY_LOCAL</code>
* error.
*
* @param status the status to be checked
* @return <code>true</code> if the given status is a <code>IResourceStatus.READ_ONLY_LOCAL</code> error
* @since 3.3
*/
private boolean isReadOnlyLocalStatus(IStatus status) {
return status.getCode() == IResourceStatus.READ_ONLY_LOCAL;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
ResourceAction action= new AddMarkerAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.AddBookmark.", this, IMarker.BOOKMARK, true); //$NON-NLS-1$
action.setHelpContextId(ITextEditorHelpContextIds.BOOKMARK_ACTION);
action.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_BOOKMARK);
setAction(IDEActionFactory.BOOKMARK.getId(), action);
action= new AddTaskAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.AddTask.", this); //$NON-NLS-1$
action.setHelpContextId(ITextEditorHelpContextIds.ADD_TASK_ACTION);
action.setActionDefinitionId(IWorkbenchActionDefinitionIds.ADD_TASK);
setAction(IDEActionFactory.ADD_TASK.getId(), action);
action= new ChangeEncodingAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ChangeEncodingAction.", this); //$NON-NLS-1$
action.setHelpContextId(ITextEditorHelpContextIds.CHANGE_ENCODING);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.CHANGE_ENCODING);
setAction(ITextEditorActionConstants.CHANGE_ENCODING, action);
markAsPropertyDependentAction(ITextEditorActionConstants.CHANGE_ENCODING, true);
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ToggleLineNumbersAction.", IAction.AS_CHECK_BOX) { //$NON-NLS-1$
public void run() {
toggleLineNumberRuler();
}
};
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINENUMBER_TOGGLE);
setAction(ITextEditorActionConstants.LINENUMBERS_TOGGLE, action);
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ToggleQuickDiffAction.", IAction.AS_CHECK_BOX) { //$NON-NLS-1$
public void run() {
toggleQuickDiffRuler();
}
};
action.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICKDIFF_TOGGLE);
setAction(ITextEditorActionConstants.QUICKDIFF_TOGGLE, action);
action= new RevertLineAction(this, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICKDIFF_REVERTLINE);
setAction(ITextEditorActionConstants.QUICKDIFF_REVERTLINE, action);
action= new RevertSelectionAction(this, false);
setAction(ITextEditorActionConstants.QUICKDIFF_REVERTSELECTION, action);
action= new RevertBlockAction(this, false);
setAction(ITextEditorActionConstants.QUICKDIFF_REVERTBLOCK, action);
action= new RestoreAction(this, false);
setAction(ITextEditorActionConstants.QUICKDIFF_REVERTDELETION, action);
IAction action2= new CompositeRevertAction(new IAction[] {
getAction(ITextEditorActionConstants.QUICKDIFF_REVERTSELECTION),
getAction(ITextEditorActionConstants.QUICKDIFF_REVERTBLOCK),
getAction(ITextEditorActionConstants.QUICKDIFF_REVERTDELETION),
getAction(ITextEditorActionConstants.QUICKDIFF_REVERTLINE)});
action2.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICKDIFF_REVERT);
setAction(ITextEditorActionConstants.QUICKDIFF_REVERT, action2);
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.HideRevisionInformationAction.") { //$NON-NLS-1$
public void run() {
if (fLineColumn != null)
fLineColumn.hideRevisionInformation();
}
};
setAction(ITextEditorActionConstants.REVISION_HIDE_INFO, action);
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.CycleRevisionRenderingAction.") { //$NON-NLS-1$
public void run() {
final RenderingMode[] modes= { IRevisionRulerColumnExtension.AGE, IRevisionRulerColumnExtension.AUTHOR, IRevisionRulerColumnExtension.AUTHOR_SHADED_BY_AGE};
IPreferenceStore store= EditorsUI.getPreferenceStore();
String current= store.getString(AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_RENDERING_MODE);
for (int i= 0; i < modes.length; i++) {
String mode= modes[i].name();
if (mode.equals(current)) {
int nextIndex= (i + 1) % modes.length;
RenderingMode nextMode= modes[nextIndex];
store.setValue(AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_RENDERING_MODE, nextMode.name());
}
}
}
};
action.setActionDefinitionId(ITextEditorActionDefinitionIds.REVISION_RENDERING_CYCLE);
setAction(ITextEditorActionConstants.REVISION_RENDERING_CYCLE, action);
action= new BooleanPreferenceToggleAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ToggleRevisionAuthorAction.", IAction.AS_CHECK_BOX, EditorsUI.getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_SHOW_AUTHOR); //$NON-NLS-1$
action.setActionDefinitionId(ITextEditorActionDefinitionIds.REVISION_AUTHOR_TOGGLE);
setAction(ITextEditorActionConstants.REVISION_SHOW_AUTHOR_TOGGLE, action);
action= new BooleanPreferenceToggleAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ToggleRevisionIdAction.", IAction.AS_CHECK_BOX, EditorsUI.getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_SHOW_REVISION); //$NON-NLS-1$
action.setActionDefinitionId(ITextEditorActionDefinitionIds.REVISION_ID_TOGGLE);
setAction(ITextEditorActionConstants.REVISION_SHOW_ID_TOGGLE, action);
final Shell shell;
if (getSourceViewer() != null)
shell= getSourceViewer().getTextWidget().getShell();
else
shell= null;
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.RulerPreferencesAction.") { //$NON-NLS-1$
public void run() {
String[] preferencePages= collectRulerMenuPreferencePages();
if (preferencePages.length > 0 && (shell == null || !shell.isDisposed()))
PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, null).open();
}
};
setAction(ITextEditorActionConstants.RULER_PREFERENCES, action);
action= new ResourceAction(TextEditorMessages.getBundleForConstructedKeys(), "Editor.ContextPreferencesAction.") { //$NON-NLS-1$
public void run() {
String[] preferencePages= collectContextMenuPreferencePages();
if (preferencePages.length > 0 && (shell == null || !shell.isDisposed()))
PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, null).open();
}
};
action.setId(ITextEditorActionConstants.CONTEXT_PREFERENCES);
setAction(ITextEditorActionConstants.CONTEXT_PREFERENCES, action);
IAction showWhitespaceCharactersAction= getAction(ITextEditorActionConstants.SHOW_WHITESPACE_CHARACTERS);
if (showWhitespaceCharactersAction instanceof ShowWhitespaceCharactersAction)
((ShowWhitespaceCharactersAction)showWhitespaceCharactersAction).setPreferenceStore(EditorsUI.getPreferenceStore());
}
public Object getAdapter(Class adapter) {
if (IGotoMarker.class.equals(adapter))
return fGotoMarkerAdapter;
if (IAnnotationAccess.class.equals(adapter))
return getAnnotationAccess();
if (adapter == IShowInSource.class) {
return new IShowInSource() {
public ShowInContext getShowInContext() {
ISelection selection= null;
ISelectionProvider selectionProvider= getSelectionProvider();
if (selectionProvider != null)
selection= selectionProvider.getSelection();
return new ShowInContext(getEditorInput(), selection);
}
};
}
if (IRevisionRulerColumn.class.equals(adapter)) {
if (fLineNumberRulerColumn instanceof IRevisionRulerColumn)
return fLineNumberRulerColumn;
}
return super.getAdapter(adapter);
}
/*
* If there is no explicit document provider set, the implicit one is
* re-initialized based on the given editor input.
*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#setDocumentProvider(org.eclipse.ui.IEditorInput)
*/
protected void setDocumentProvider(IEditorInput input) {
fImplicitDocumentProvider= DocumentProviderRegistry.getDefault().getDocumentProvider(input);
IDocumentProvider provider= super.getDocumentProvider();
if (provider instanceof ForwardingDocumentProvider) {
ForwardingDocumentProvider forwarder= (ForwardingDocumentProvider) provider;
forwarder.setParentProvider(fImplicitDocumentProvider);
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditor#getDocumentProvider()
*/
public IDocumentProvider getDocumentProvider() {
IDocumentProvider provider= super.getDocumentProvider();
if (provider == null)
return fImplicitDocumentProvider;
return provider;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#disposeDocumentProvider()
*/
protected void disposeDocumentProvider() {
super.disposeDocumentProvider();
fImplicitDocumentProvider= null;
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*
* This implementation also updates change information in the quick diff
* ruler.
*/
protected void doSetInput(IEditorInput input) throws CoreException {
fIsDerivedStateValidated= false;
fIsEditingDerivedFileAllowed= true;
if (fLineColumn != null)
fLineColumn.hideRevisionInformation();
super.doSetInput(input);
RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID);
if (lineNumberColumnDescriptor != null) {
IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class);
columnSupport.setColumnVisible(lineNumberColumnDescriptor, isLineNumberRulerVisible() || isPrefQuickDiffAlwaysOn());
}
}
/**
* This implementation asks the user for the workspace path of a file resource and saves the document there.
*
* @param progressMonitor the progress monitor to be used
* @since 3.2
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
final IEditorInput input= getEditorInput();
IDocumentProvider provider= getDocumentProvider();
final IEditorInput newInput;
- if (input instanceof IURIEditorInput) {
+ if (input instanceof IURIEditorInput && !(input instanceof IFileEditorInput)) {
FileDialog dialog= new FileDialog(shell, SWT.SAVE);
IPath oldPath= URIUtil.toPath(((IURIEditorInput)input).getURI());
if (oldPath != null) {
dialog.setFileName(oldPath.lastSegment());
dialog.setFilterPath(oldPath.toOSString());
}
String path= dialog.open();
if (path == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
// Check whether file exists and if so, confirm overwrite
final File localFile= new File(path);
if (localFile.exists()) {
MessageDialog overwriteDialog= new MessageDialog(
shell,
TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_title,
null,
NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_message, path),
MessageDialog.WARNING,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL },
1); // 'No' is the default
if (overwriteDialog.open() != Window.OK) {
if (progressMonitor != null) {
progressMonitor.setCanceled(true);
return;
}
}
}
IFileStore fileStore;
try {
fileStore= EFS.getStore(localFile.toURI());
} catch (CoreException ex) {
EditorsPlugin.log(ex.getStatus());
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, ex.getMessage());
MessageDialog.openError(shell, title, msg);
return;
}
IFile file= getWorkspaceFile(fileStore);
if (file != null)
newInput= new FileEditorInput(file);
else
newInput= new FileStoreEditorInput(fileStore);
} else {
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
if (provider.isDeleted(input) && original != null) {
String message= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_warning_saveAs_deleted, original.getName());
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
newInput= new FileEditorInput(file);
}
if (provider == null) {
// editor has programmatically been closed while the dialog was open
return;
}
boolean success= false;
try {
provider.aboutToChange(newInput);
provider.saveDocument(progressMonitor, newInput, provider.getDocument(input), true);
success= true;
} catch (CoreException x) {
final IStatus status= x.getStatus();
if (status == null || status.getSeverity() != IStatus.CANCEL) {
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, x.getMessage());
MessageDialog.openError(shell, title, msg);
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/**
* Checks whether there given file store points
* to a file in the workspace. Only returns a
* workspace file if there's a single match.
*
* @param fileStore the file store
* @return the <code>IFile</code> that matches the given file store
* @since 3.2
*/
private IFile getWorkspaceFile(IFileStore fileStore) {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile[] files= workspaceRoot.findFilesForLocation(URIUtil.toPath(fileStore.toURI()));
if (files != null && files.length == 1)
return files[0];
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#rulerContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
* @since 3.1
*/
protected void rulerContextMenuAboutToShow(IMenuManager menu) {
/*
* XXX: workaround for reliable menu item ordering.
* This can be changed once the action contribution story converges,
* see http://dev.eclipse.org/viewcvs/index.cgi/~checkout~/platform-ui-home/R3_1/dynamic_teams/dynamic_teams.html#actionContributions
*/
// pre-install menus for contributions and call super
menu.add(new Separator("debug")); //$NON-NLS-1$
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_RESTORE));
menu.add(new Separator("add")); //$NON-NLS-1$
menu.add(new Separator(ITextEditorActionConstants.GROUP_RULERS));
menu.add(new Separator(ITextEditorActionConstants.GROUP_REST));
super.rulerContextMenuAboutToShow(menu);
addRulerContributionActions(menu);
/* quick diff */
if (isEditorInputModifiable()) {
IAction quickdiffAction= getAction(ITextEditorActionConstants.QUICKDIFF_TOGGLE);
quickdiffAction.setChecked(isChangeInformationShowing());
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, quickdiffAction);
if (isChangeInformationShowing()) {
TextEditorAction revertLine= new RevertLineAction(this, true);
TextEditorAction revertSelection= new RevertSelectionAction(this, true);
TextEditorAction revertBlock= new RevertBlockAction(this, true);
TextEditorAction revertDeletion= new RestoreAction(this, true);
revertSelection.update();
revertBlock.update();
revertLine.update();
revertDeletion.update();
// only add block action if selection action is not enabled
if (revertSelection.isEnabled())
menu.appendToGroup(ITextEditorActionConstants.GROUP_RESTORE, revertSelection);
else if (revertBlock.isEnabled())
menu.appendToGroup(ITextEditorActionConstants.GROUP_RESTORE, revertBlock);
if (revertLine.isEnabled())
menu.appendToGroup(ITextEditorActionConstants.GROUP_RESTORE, revertLine);
if (revertDeletion.isEnabled())
menu.appendToGroup(ITextEditorActionConstants.GROUP_RESTORE, revertDeletion);
}
}
// revision info
if (fLineColumn != null && fLineColumn.isShowingRevisionInformation()) {
IMenuManager revisionMenu= new MenuManager(TextEditorMessages.AbstractDecoratedTextEditor_revisions_menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, revisionMenu);
IAction hideRevisionInfoAction= getAction(ITextEditorActionConstants.REVISION_HIDE_INFO);
revisionMenu.add(hideRevisionInfoAction);
revisionMenu.add(new Separator());
String[] labels= { TextEditorMessages.AbstractDecoratedTextEditor_revision_colors_option_by_date, TextEditorMessages.AbstractDecoratedTextEditor_revision_colors_option_by_author, TextEditorMessages.AbstractDecoratedTextEditor_revision_colors_option_by_author_and_date };
final RenderingMode[] modes= { IRevisionRulerColumnExtension.AGE, IRevisionRulerColumnExtension.AUTHOR, IRevisionRulerColumnExtension.AUTHOR_SHADED_BY_AGE};
final IPreferenceStore uiStore= EditorsUI.getPreferenceStore();
String current= uiStore.getString(AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_RENDERING_MODE);
for (int i= 0; i < modes.length; i++) {
final String mode= modes[i].name();
IAction action= new Action(labels[i], IAction.AS_RADIO_BUTTON) {
public void run() {
// set preference globally, LineNumberColumn reacts on preference change
uiStore.setValue(AbstractDecoratedTextEditorPreferenceConstants.REVISION_RULER_RENDERING_MODE, mode);
}
};
action.setChecked(mode.equals(current));
revisionMenu.add(action);
}
revisionMenu.add(new Separator());
revisionMenu.add(getAction(ITextEditorActionConstants.REVISION_SHOW_AUTHOR_TOGGLE));
revisionMenu.add(getAction(ITextEditorActionConstants.REVISION_SHOW_ID_TOGGLE));
}
IAction lineNumberAction= getAction(ITextEditorActionConstants.LINENUMBERS_TOGGLE);
lineNumberAction.setChecked(fLineColumn != null && fLineColumn.isShowingLineNumbers());
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, lineNumberAction);
IAction preferencesAction= getAction(ITextEditorActionConstants.RULER_PREFERENCES);
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, new Separator(ITextEditorActionConstants.GROUP_SETTINGS));
menu.appendToGroup(ITextEditorActionConstants.GROUP_SETTINGS, preferencesAction);
}
/**
* Adds "show" actions for all contributed rulers that support it.
*
* @param menu the ruler context menu
* @since 3.3
*/
private void addRulerContributionActions(IMenuManager menu) {
// store directly in generic editor preferences
final IColumnSupport support= (IColumnSupport) getAdapter(IColumnSupport.class);
IPreferenceStore store= EditorsUI.getPreferenceStore();
final RulerColumnPreferenceAdapter adapter= new RulerColumnPreferenceAdapter(store, AbstractTextEditor.PREFERENCE_RULER_CONTRIBUTIONS);
List descriptors= RulerColumnRegistry.getDefault().getColumnDescriptors();
for (Iterator t= descriptors.iterator(); t.hasNext();) {
final RulerColumnDescriptor descriptor= (RulerColumnDescriptor) t.next();
if (!descriptor.isIncludedInMenu() || !support.isColumnSupported(descriptor))
continue;
final boolean isVisible= support.isColumnVisible(descriptor);
IAction action= new Action(MessageFormat.format(TextEditorMessages.AbstractDecoratedTextEditor_show_ruler_label, new Object[] {descriptor.getName()}), IAction.AS_CHECK_BOX) {
public void run() {
if (descriptor.isGlobal())
// column state is modified via preference listener of AbstractTextEditor
adapter.setEnabled(descriptor, !isVisible);
else
// directly modify column for this editor instance
support.setColumnVisible(descriptor, !isVisible);
}
};
action.setChecked(isVisible);
action.setImageDescriptor(descriptor.getIcon());
menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, action);
}
}
/**
* Toggles the line number global preference and shows the line number ruler
* accordingly.
*
* @since 3.1
*/
private void toggleLineNumberRuler() {
// globally
IPreferenceStore store= EditorsUI.getPreferenceStore();
store.setValue(LINE_NUMBER_RULER, !isLineNumberRulerVisible());
}
/**
* Toggles the quick diff global preference and shows the quick diff ruler
* accordingly.
*
* @since 3.1
*/
private void toggleQuickDiffRuler() {
// change the visibility locally if this editor is not in sync with the global preference
// toggle the preference if we are in sync.
IPreferenceStore store= EditorsUI.getPreferenceStore();
boolean current= store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
if (current == isChangeInformationShowing())
store.setValue(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON, !current);
else
showChangeInformation(current);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager)
* @since 3.1
*/
protected void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
IAction preferencesAction= getAction(ITextEditorActionConstants.CONTEXT_PREFERENCES);
menu.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new Separator(ITextEditorActionConstants.GROUP_SETTINGS));
menu.appendToGroup(ITextEditorActionConstants.GROUP_SETTINGS, preferencesAction);
menu.appendToGroup(ITextEditorActionConstants.GROUP_SAVE, new Separator(ITextEditorActionConstants.GROUP_OPEN));
MenuManager showInSubMenu= new MenuManager(getShowInMenuLabel());
showInSubMenu.add(ContributionItemFactory.VIEWS_SHOW_IN.create(getEditorSite().getWorkbenchWindow()));
menu.appendToGroup(ITextEditorActionConstants.GROUP_OPEN, showInSubMenu);
}
/**
* Returns the menu label for 'Show In' together with its key binding string.
*
* @return the 'Show In' menu label
* @since 3.2
*/
private String getShowInMenuLabel() {
String keyBinding= null;
IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
if (bindingService != null)
keyBinding= bindingService.getBestActiveBindingFormattedFor("org.eclipse.ui.navigate.showInQuickMenu"); //$NON-NLS-1$
if (keyBinding == null)
keyBinding= ""; //$NON-NLS-1$
return NLS.bind(TextEditorMessages.AbstractDecoratedTextEditor_showIn_menu, keyBinding);
}
/**
* Returns the preference page ids of the preference pages to be shown
* when executing the preferences action from the editor context menu.
* <p>
* Subclasses may extend or replace.
* </p>
*
* @return the preference page ids to show, may be empty
* @since 3.1
*/
protected String[] collectContextMenuPreferencePages() {
return new String[] {
"org.eclipse.ui.preferencePages.GeneralTextEditor", //$NON-NLS-1$
"org.eclipse.ui.editors.preferencePages.Annotations", //$NON-NLS-1$
"org.eclipse.ui.editors.preferencePages.QuickDiff", //$NON-NLS-1$
"org.eclipse.ui.editors.preferencePages.Accessibility", //$NON-NLS-1$
"org.eclipse.ui.editors.preferencePages.Spelling", //$NON-NLS-1$
"org.eclipse.ui.editors.preferencePages.LinkedModePreferencePage", //$NON-NLS-1$
};
}
/**
* Returns the preference page ids of the preference pages to be shown when
* executing the preferences action from the editor ruler context menu.
* <p>
* The default is to return the same list as
* <code>collectContextMenuPreferencePages</code>.
* </p>
* <p>
* Subclasses may extend or replace.
* </p>
*
* @return the preference page ids to show, may be empty
* @since 3.1
*/
protected String[] collectRulerMenuPreferencePages() {
return collectContextMenuPreferencePages();
}
/*
* @see AbstractTextEditor#getUndoRedoOperationApprover(IUndoContext)
* @since 3.1
*/
protected IOperationApprover getUndoRedoOperationApprover(IUndoContext undoContext) {
IEditorInput input= getEditorInput();
if (input != null && input.getAdapter(IResource.class) != null)
return new NonLocalUndoUserApprover(undoContext, this, new Object [] { input }, IResource.class);
return super.getUndoRedoOperationApprover(undoContext);
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions.
* <p>
* The annotation is a target if their annotation type is configured to be
* in the Next/Previous tool bar drop down menu and if it is checked.
* </p>
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code> otherwise
* @since 3.2
*/
protected boolean isNavigationTarget(Annotation annotation) {
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && getPreferenceStore().getBoolean(key));
}
/**
* {@inheritDoc}
* <p>
* This extended implementation updates views that also show the
* select marker annotation.
* </p>
* @since 3.2
*/
public Annotation gotoAnnotation(boolean forward) {
Annotation annotation= super.gotoAnnotation(forward);
if (annotation != null)
updateMarkerViews(annotation);
return annotation;
}
/**
* Updates visible views that show markers.
* <p>
* If the given annotation can be associated with a marker then
* this method tries select the this marker in views that show
* markers.
* </p>
* @param annotation
* @since 3.2
*/
protected void updateMarkerViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation)annotation).getMarker();
if (marker != null) {
try {
fIsUpdatingMarkerViews= true;
IWorkbenchPage page= getSite().getPage();
MarkerViewUtil.showMarker(page, marker, false);
} finally {
fIsUpdatingMarkerViews= false;
}
}
}
}
| true | true | protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
final IEditorInput input= getEditorInput();
IDocumentProvider provider= getDocumentProvider();
final IEditorInput newInput;
if (input instanceof IURIEditorInput) {
FileDialog dialog= new FileDialog(shell, SWT.SAVE);
IPath oldPath= URIUtil.toPath(((IURIEditorInput)input).getURI());
if (oldPath != null) {
dialog.setFileName(oldPath.lastSegment());
dialog.setFilterPath(oldPath.toOSString());
}
String path= dialog.open();
if (path == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
// Check whether file exists and if so, confirm overwrite
final File localFile= new File(path);
if (localFile.exists()) {
MessageDialog overwriteDialog= new MessageDialog(
shell,
TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_title,
null,
NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_message, path),
MessageDialog.WARNING,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL },
1); // 'No' is the default
if (overwriteDialog.open() != Window.OK) {
if (progressMonitor != null) {
progressMonitor.setCanceled(true);
return;
}
}
}
IFileStore fileStore;
try {
fileStore= EFS.getStore(localFile.toURI());
} catch (CoreException ex) {
EditorsPlugin.log(ex.getStatus());
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, ex.getMessage());
MessageDialog.openError(shell, title, msg);
return;
}
IFile file= getWorkspaceFile(fileStore);
if (file != null)
newInput= new FileEditorInput(file);
else
newInput= new FileStoreEditorInput(fileStore);
} else {
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
if (provider.isDeleted(input) && original != null) {
String message= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_warning_saveAs_deleted, original.getName());
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
newInput= new FileEditorInput(file);
}
if (provider == null) {
// editor has programmatically been closed while the dialog was open
return;
}
boolean success= false;
try {
provider.aboutToChange(newInput);
provider.saveDocument(progressMonitor, newInput, provider.getDocument(input), true);
success= true;
} catch (CoreException x) {
final IStatus status= x.getStatus();
if (status == null || status.getSeverity() != IStatus.CANCEL) {
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, x.getMessage());
MessageDialog.openError(shell, title, msg);
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
| protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
final IEditorInput input= getEditorInput();
IDocumentProvider provider= getDocumentProvider();
final IEditorInput newInput;
if (input instanceof IURIEditorInput && !(input instanceof IFileEditorInput)) {
FileDialog dialog= new FileDialog(shell, SWT.SAVE);
IPath oldPath= URIUtil.toPath(((IURIEditorInput)input).getURI());
if (oldPath != null) {
dialog.setFileName(oldPath.lastSegment());
dialog.setFilterPath(oldPath.toOSString());
}
String path= dialog.open();
if (path == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
// Check whether file exists and if so, confirm overwrite
final File localFile= new File(path);
if (localFile.exists()) {
MessageDialog overwriteDialog= new MessageDialog(
shell,
TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_title,
null,
NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_saveAs_overwrite_message, path),
MessageDialog.WARNING,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL },
1); // 'No' is the default
if (overwriteDialog.open() != Window.OK) {
if (progressMonitor != null) {
progressMonitor.setCanceled(true);
return;
}
}
}
IFileStore fileStore;
try {
fileStore= EFS.getStore(localFile.toURI());
} catch (CoreException ex) {
EditorsPlugin.log(ex.getStatus());
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, ex.getMessage());
MessageDialog.openError(shell, title, msg);
return;
}
IFile file= getWorkspaceFile(fileStore);
if (file != null)
newInput= new FileEditorInput(file);
else
newInput= new FileStoreEditorInput(fileStore);
} else {
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
if (provider.isDeleted(input) && original != null) {
String message= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_warning_saveAs_deleted, original.getName());
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Window.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
newInput= new FileEditorInput(file);
}
if (provider == null) {
// editor has programmatically been closed while the dialog was open
return;
}
boolean success= false;
try {
provider.aboutToChange(newInput);
provider.saveDocument(progressMonitor, newInput, provider.getDocument(input), true);
success= true;
} catch (CoreException x) {
final IStatus status= x.getStatus();
if (status == null || status.getSeverity() != IStatus.CANCEL) {
String title= TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_title;
String msg= NLSUtility.format(TextEditorMessages.AbstractDecoratedTextEditor_error_saveAs_message, x.getMessage());
MessageDialog.openError(shell, title, msg);
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
|
diff --git a/hazelcast-client/src/test/java/com/hazelcast/client/lock/ClientConditionTest.java b/hazelcast-client/src/test/java/com/hazelcast/client/lock/ClientConditionTest.java
index d6011fd00b..43bc99f681 100644
--- a/hazelcast-client/src/test/java/com/hazelcast/client/lock/ClientConditionTest.java
+++ b/hazelcast-client/src/test/java/com/hazelcast/client/lock/ClientConditionTest.java
@@ -1,266 +1,266 @@
package com.hazelcast.client.lock;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.*;
import com.hazelcast.spi.exception.DistributedObjectDestroyedException;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.*;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientConditionTest {
static final String name = "test";
static HazelcastInstance hz;
static ILock l;
@BeforeClass
public static void init() {
Hazelcast.newHazelcastInstance();
hz = HazelcastClient.newHazelcastClient(null);
l = hz.getLock(name);
}
@AfterClass
public static void destroy() {
hz.getLifecycleService().shutdown();
Hazelcast.shutdownAll();
}
@Before
@After
public void clear() throws IOException {
l.forceUnlock();
}
@Test
public void testLockConditionSimpleUsage() throws InterruptedException {
final String name = "testLockConditionSimpleUsage";
final ILock lock = hz.getLock(name);
final ICondition condition = lock.newCondition(name + "c");
final AtomicInteger count = new AtomicInteger(0);
Thread t = new Thread(new Runnable() {
public void run() {
lock.lock();
try {
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
condition.await();
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
}
}
});
t.start();
Thread.sleep(1000);
Assert.assertEquals(false, lock.isLocked());
lock.lock();
Assert.assertEquals(true, lock.isLocked());
condition.signal();
lock.unlock();
t.join();
Assert.assertEquals(2, count.get());
}
@Test
public void testLockConditionSignalAll() throws InterruptedException {
final String name = "testLockConditionSimpleUsage";
final ILock lock = hz.getLock(name);
final ICondition condition = lock.newCondition(name + "c");
final AtomicInteger count = new AtomicInteger(0);
final int k = 50;
final CountDownLatch awaitLatch = new CountDownLatch(k);
final CountDownLatch finalLatch = new CountDownLatch(k);
for (int i = 0; i < k; i++) {
new Thread(new Runnable() {
public void run() {
lock.lock();
try {
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
awaitLatch.countDown();
condition.await();
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
finalLatch.countDown();
}
}
}).start();
}
awaitLatch.await(1, TimeUnit.MINUTES);
lock.lock();
condition.signalAll();
lock.unlock();
finalLatch.await(1, TimeUnit.MINUTES);
Assert.assertEquals(k * 2, count.get());
}
@Test
public void testLockConditionSignalAllShutDownKeyOwner() throws InterruptedException {
final String name = "testLockConditionSignalAllShutDownKeyOwner";
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final AtomicInteger count = new AtomicInteger(0);
final int size = 50;
int k = 0;
final HazelcastInstance keyOwner = Hazelcast.newHazelcastInstance();
final Member keyOwnerMember = keyOwner.getCluster().getLocalMember();
- final Member partitionOwnerMember = instance.getPartitionService().getPartition(++k).getOwner();
- while (!keyOwnerMember.equals(partitionOwnerMember)) {
+ final PartitionService partitionService = instance.getPartitionService();
+ while (!keyOwnerMember.equals(partitionService.getPartition(++k).getOwner())) {
Thread.sleep(10);
}
final ILock lock = hz.getLock(k);
final ICondition condition = lock.newCondition(name);
final CountDownLatch awaitLatch = new CountDownLatch(size);
final CountDownLatch finalLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
new Thread(new Runnable() {
public void run() {
lock.lock();
try {
awaitLatch.countDown();
condition.await();
Thread.sleep(5);
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
finalLatch.countDown();
}
}
}).start();
}
awaitLatch.await(1, TimeUnit.MINUTES);
lock.lock();
condition.signalAll();
lock.unlock();
keyOwner.getLifecycleService().shutdown();
finalLatch.await(2, TimeUnit.MINUTES);
Assert.assertEquals(size, count.get());
}
@Test(timeout = 100000)
public void testKeyOwnerDiesOnCondition() throws Exception {
final HazelcastInstance keyOwner = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance();
final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance();
int k = 0;
final AtomicInteger atomicInteger = new AtomicInteger(0);
final Member keyOwnerMember = keyOwner.getCluster().getLocalMember();
final PartitionService partitionService = instance1.getPartitionService();
while (keyOwnerMember.equals(partitionService.getPartition(k++).getOwner())) {
Thread.sleep(10);
}
final int key = k;
final ILock lock1 = hz.getLock(key);
final String name = "testKeyOwnerDiesOnCondition";
final ICondition condition1 = lock1.newCondition(name);
Thread t = new Thread(new Runnable() {
public void run() {
final ILock lock = hz.getLock(key);
final ICondition condition = lock.newCondition(name);
lock.lock();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
atomicInteger.incrementAndGet();
}
});
t.start();
Thread.sleep(1000);
lock1.lock();
keyOwner.getLifecycleService().shutdown();
condition1.signal();
lock1.unlock();
Thread.sleep(1000);
t.join();
Assert.assertEquals(1, atomicInteger.get());
}
@Test(expected = DistributedObjectDestroyedException.class)
public void testDestroyLockWhenOtherWaitingOnConditionAwait() {
final ILock lock = hz.getLock("testDestroyLockWhenOtherWaitingOnConditionAwait");
final ICondition condition = lock.newCondition("condition");
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
public void run() {
try {
latch.await(30, TimeUnit.SECONDS);
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.destroy();
}
}).start();
lock.lock();
try {
latch.countDown();
condition.await();
} catch (InterruptedException e) {
}
lock.unlock();
}
@Test(expected = IllegalMonitorStateException.class)
public void testIllegalConditionUsageWithoutAcquiringLock() {
final ICondition condition = l.newCondition("condition");
try {
condition.await();
} catch (InterruptedException e) {
}
}
@Test(expected = IllegalMonitorStateException.class)
public void testIllegalConditionUsageSignalToNonAwaiter() {
final ICondition condition = l.newCondition("condition");
condition.signal();
}
@Test
public void testConditionUsage() throws InterruptedException {
l.lock();
final ICondition condition = l.newCondition("condition");
condition.await(1, TimeUnit.SECONDS);
l.unlock();
}
}
| true | true | public void testLockConditionSignalAllShutDownKeyOwner() throws InterruptedException {
final String name = "testLockConditionSignalAllShutDownKeyOwner";
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final AtomicInteger count = new AtomicInteger(0);
final int size = 50;
int k = 0;
final HazelcastInstance keyOwner = Hazelcast.newHazelcastInstance();
final Member keyOwnerMember = keyOwner.getCluster().getLocalMember();
final Member partitionOwnerMember = instance.getPartitionService().getPartition(++k).getOwner();
while (!keyOwnerMember.equals(partitionOwnerMember)) {
Thread.sleep(10);
}
final ILock lock = hz.getLock(k);
final ICondition condition = lock.newCondition(name);
final CountDownLatch awaitLatch = new CountDownLatch(size);
final CountDownLatch finalLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
new Thread(new Runnable() {
public void run() {
lock.lock();
try {
awaitLatch.countDown();
condition.await();
Thread.sleep(5);
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
finalLatch.countDown();
}
}
}).start();
}
awaitLatch.await(1, TimeUnit.MINUTES);
lock.lock();
condition.signalAll();
lock.unlock();
keyOwner.getLifecycleService().shutdown();
finalLatch.await(2, TimeUnit.MINUTES);
Assert.assertEquals(size, count.get());
}
| public void testLockConditionSignalAllShutDownKeyOwner() throws InterruptedException {
final String name = "testLockConditionSignalAllShutDownKeyOwner";
final HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final AtomicInteger count = new AtomicInteger(0);
final int size = 50;
int k = 0;
final HazelcastInstance keyOwner = Hazelcast.newHazelcastInstance();
final Member keyOwnerMember = keyOwner.getCluster().getLocalMember();
final PartitionService partitionService = instance.getPartitionService();
while (!keyOwnerMember.equals(partitionService.getPartition(++k).getOwner())) {
Thread.sleep(10);
}
final ILock lock = hz.getLock(k);
final ICondition condition = lock.newCondition(name);
final CountDownLatch awaitLatch = new CountDownLatch(size);
final CountDownLatch finalLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
new Thread(new Runnable() {
public void run() {
lock.lock();
try {
awaitLatch.countDown();
condition.await();
Thread.sleep(5);
if (lock.isLockedByCurrentThread()) {
count.incrementAndGet();
}
} catch (InterruptedException ignored) {
} finally {
lock.unlock();
finalLatch.countDown();
}
}
}).start();
}
awaitLatch.await(1, TimeUnit.MINUTES);
lock.lock();
condition.signalAll();
lock.unlock();
keyOwner.getLifecycleService().shutdown();
finalLatch.await(2, TimeUnit.MINUTES);
Assert.assertEquals(size, count.get());
}
|
diff --git a/src/main/java/org/xbib/elasticsearch/river/jdbc/strategy/simple/SimpleRiverFlow.java b/src/main/java/org/xbib/elasticsearch/river/jdbc/strategy/simple/SimpleRiverFlow.java
index 074e3390..ac2f44ee 100644
--- a/src/main/java/org/xbib/elasticsearch/river/jdbc/strategy/simple/SimpleRiverFlow.java
+++ b/src/main/java/org/xbib/elasticsearch/river/jdbc/strategy/simple/SimpleRiverFlow.java
@@ -1,218 +1,218 @@
package org.xbib.elasticsearch.river.jdbc.strategy.simple;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.indices.IndexMissingException;
import org.xbib.elasticsearch.river.jdbc.RiverFlow;
import org.xbib.elasticsearch.river.jdbc.RiverMouth;
import org.xbib.elasticsearch.river.jdbc.RiverSource;
import org.xbib.elasticsearch.river.jdbc.support.RiverContext;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import static org.elasticsearch.client.Requests.indexRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* A river flow implementation for the 'simple' strategy.
* <p/>
* This river flow runs fetch actions in a loop and waits before the next cycle begins.
* <p/>
* A version counter is incremented each time a fetch move is executed.
* <p/>
* The state of the river flow is saved between runs. So, in case of a restart, the
* river flow will recover with the last known state of the river.
*
* @author Jörg Prante <[email protected]>
*/
public class SimpleRiverFlow implements RiverFlow {
private final ESLogger logger = ESLoggerFactory.getLogger(SimpleRiverFlow.class.getSimpleName());
protected RiverContext context;
protected Date startDate;
protected boolean abort = false;
protected ESLogger logger() {
return logger;
}
@Override
public String strategy() {
return "simple";
}
@Override
public SimpleRiverFlow riverContext(RiverContext context) {
this.context = context;
return this;
}
@Override
public RiverContext riverContext() {
return context;
}
/**
* Set a start date
*
* @param creationDate the creation date
*/
@Override
public SimpleRiverFlow startDate(Date creationDate) {
this.startDate = creationDate;
return this;
}
/**
* Return the start date of the river task
*
* @return the creation date
*/
@Override
public Date startDate() {
return startDate;
}
/**
* Delay the connector for poll millis, and notify a reason.
*
* @param reason the reason for the dealy
*/
@Override
public SimpleRiverFlow delay(String reason) {
TimeValue poll = context.pollingInterval();
if (poll.millis() > 0L) {
logger().info("{}, waiting {}", reason, poll);
try {
Thread.sleep(poll.millis());
} catch (InterruptedException e) {
logger().debug("Thread interrupted while waiting, stopping");
abort();
}
}
return this;
}
/**
* Triggers flag to abort the connector down at next run.
*/
@Override
public void abort() {
this.abort = true;
}
/**
* The river task loop. Execute move, check if the task must be aborted, continue with next run after a delay.
*/
@Override
public void run() {
while (!abort) {
move();
if (abort) {
return;
}
delay("next run");
}
}
/**
* A single river move.
*/
@Override
public void move() {
try {
RiverSource source = context.riverSource();
RiverMouth riverMouth = context.riverMouth();
Client client = context.riverMouth().client();
Number version;
GetResponse get = null;
// wait for cluster health
riverMouth.waitForCluster();
try {
// read state from _custom
client.admin().indices().prepareRefresh(context.riverIndexName()).execute().actionGet();
get = client.prepareGet(context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX).execute().actionGet();
} catch (IndexMissingException e) {
logger().warn("river state missing: {}/{}/{}", context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX);
}
if (get != null && get.isExists()) {
Map jdbcState = (Map) get.getSourceAsMap().get("jdbc");
if (jdbcState != null) {
version = (Number) jdbcState.get("version");
- version = version.longValue() + 1; // increase to next version
+ version = version == null ? 1L : version.longValue() + 1; // increase to next version
} else {
throw new IOException("can't retrieve previously persisted state from " + context.riverIndexName() + "/" + context.riverName());
}
} else {
version = 1L;
}
// save state, write activity flag
try {
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("since", new Date())
.field("active", true);
builder.endObject().endObject();
client.index(indexRequest(context.riverIndexName())
.type(riverContext().riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder)).actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
// set default job name to current version number
context.job(Long.toString(version.longValue()));
String mergeDigest = source.fetch();
// this end is required before house keeping starts
riverMouth.flush();
// save state
try {
// save state to _custom
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("version", version.longValue())
.field("digest", mergeDigest)
.field("since", new Date())
.field("active", false);
builder.endObject().endObject();
if (logger().isDebugEnabled()) {
logger().debug(builder.string());
}
client.index(indexRequest(context.riverIndexName())
.type(context.riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder))
.actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
} catch (Exception e) {
logger().error(e.getMessage(), e);
abort = true;
}
}
}
| true | true | public void move() {
try {
RiverSource source = context.riverSource();
RiverMouth riverMouth = context.riverMouth();
Client client = context.riverMouth().client();
Number version;
GetResponse get = null;
// wait for cluster health
riverMouth.waitForCluster();
try {
// read state from _custom
client.admin().indices().prepareRefresh(context.riverIndexName()).execute().actionGet();
get = client.prepareGet(context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX).execute().actionGet();
} catch (IndexMissingException e) {
logger().warn("river state missing: {}/{}/{}", context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX);
}
if (get != null && get.isExists()) {
Map jdbcState = (Map) get.getSourceAsMap().get("jdbc");
if (jdbcState != null) {
version = (Number) jdbcState.get("version");
version = version.longValue() + 1; // increase to next version
} else {
throw new IOException("can't retrieve previously persisted state from " + context.riverIndexName() + "/" + context.riverName());
}
} else {
version = 1L;
}
// save state, write activity flag
try {
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("since", new Date())
.field("active", true);
builder.endObject().endObject();
client.index(indexRequest(context.riverIndexName())
.type(riverContext().riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder)).actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
// set default job name to current version number
context.job(Long.toString(version.longValue()));
String mergeDigest = source.fetch();
// this end is required before house keeping starts
riverMouth.flush();
// save state
try {
// save state to _custom
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("version", version.longValue())
.field("digest", mergeDigest)
.field("since", new Date())
.field("active", false);
builder.endObject().endObject();
if (logger().isDebugEnabled()) {
logger().debug(builder.string());
}
client.index(indexRequest(context.riverIndexName())
.type(context.riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder))
.actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
} catch (Exception e) {
logger().error(e.getMessage(), e);
abort = true;
}
}
| public void move() {
try {
RiverSource source = context.riverSource();
RiverMouth riverMouth = context.riverMouth();
Client client = context.riverMouth().client();
Number version;
GetResponse get = null;
// wait for cluster health
riverMouth.waitForCluster();
try {
// read state from _custom
client.admin().indices().prepareRefresh(context.riverIndexName()).execute().actionGet();
get = client.prepareGet(context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX).execute().actionGet();
} catch (IndexMissingException e) {
logger().warn("river state missing: {}/{}/{}", context.riverIndexName(), context.riverName(), ID_INFO_RIVER_INDEX);
}
if (get != null && get.isExists()) {
Map jdbcState = (Map) get.getSourceAsMap().get("jdbc");
if (jdbcState != null) {
version = (Number) jdbcState.get("version");
version = version == null ? 1L : version.longValue() + 1; // increase to next version
} else {
throw new IOException("can't retrieve previously persisted state from " + context.riverIndexName() + "/" + context.riverName());
}
} else {
version = 1L;
}
// save state, write activity flag
try {
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("since", new Date())
.field("active", true);
builder.endObject().endObject();
client.index(indexRequest(context.riverIndexName())
.type(riverContext().riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder)).actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
// set default job name to current version number
context.job(Long.toString(version.longValue()));
String mergeDigest = source.fetch();
// this end is required before house keeping starts
riverMouth.flush();
// save state
try {
// save state to _custom
XContentBuilder builder = jsonBuilder();
builder.startObject().startObject("jdbc");
if (startDate != null) {
builder.field("created", startDate);
}
builder.field("version", version.longValue())
.field("digest", mergeDigest)
.field("since", new Date())
.field("active", false);
builder.endObject().endObject();
if (logger().isDebugEnabled()) {
logger().debug(builder.string());
}
client.index(indexRequest(context.riverIndexName())
.type(context.riverName())
.id(ID_INFO_RIVER_INDEX)
.source(builder))
.actionGet();
} catch (Exception e) {
logger().error(e.getMessage(), e);
}
} catch (Exception e) {
logger().error(e.getMessage(), e);
abort = true;
}
}
|
diff --git a/survey/src/com/gallatinsystems/survey/device/view/SubmitTabContentFactory.java b/survey/src/com/gallatinsystems/survey/device/view/SubmitTabContentFactory.java
index f7ff9aae..c774d142 100644
--- a/survey/src/com/gallatinsystems/survey/device/view/SubmitTabContentFactory.java
+++ b/survey/src/com/gallatinsystems/survey/device/view/SubmitTabContentFactory.java
@@ -1,165 +1,164 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.survey.device.view;
import java.util.ArrayList;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import com.gallatinsystems.survey.device.R;
import com.gallatinsystems.survey.device.activity.SurveyViewActivity;
import com.gallatinsystems.survey.device.dao.SurveyDbAdapter;
import com.gallatinsystems.survey.device.domain.Question;
import com.gallatinsystems.survey.device.util.ConstantUtil;
import com.gallatinsystems.survey.device.util.ViewUtil;
/**
* this tab handles rendering of all validation errors so the user can see what
* is is preventing submission of a survey.
*
* @author Christopher Fagiani
*/
public class SubmitTabContentFactory extends SurveyTabContentFactory {
private Button submitButton;
private static final int DEFAULT_WIDTH = 200;
private static final int HEADING_TEXT_SIZE = 20;
private static final String HEADING_COLOR = "red";
public SubmitTabContentFactory(SurveyViewActivity c,
SurveyDbAdapter dbAdaptor, float textSize, String defaultLang,
String[] languageCodes) {
super(c, dbAdaptor, textSize, defaultLang, languageCodes);
}
@Override
public View createTabContent(String tag) {
return replaceViewContent(null);
}
/**
* checks completion status of questions and renders the view appropriately
*
* @return
*/
public View refreshView(boolean setMissing) {
// first, re-save all questions to make sure we didn't miss anything
context.saveAllResponses();
submitButton = configureActionButton(R.string.submitbutton,
new OnClickListener() {
public void onClick(View v) {
// if we have no missing responses, submit the survey
databaseAdaptor.submitResponses(context
.getRespondentId().toString());
// send a broadcast message indicating new data is
// available
Intent i = new Intent(
ConstantUtil.DATA_AVAILABLE_INTENT);
context.sendBroadcast(i);
ViewUtil.showConfirmDialog(
R.string.submitcompletetitle,
R.string.submitcompletetext, context,
false,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
- dialog.cancel();
context.finish();
}
}
});
}
});
TableLayout table = new TableLayout(context);
table.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// get the list (across all tabs) of missing mandatory
// responses
ArrayList<Question> missingQuestions = context.checkMandatory();
if (setMissing) {
getContext().setMissingQuestions(missingQuestions);
}
if (missingQuestions.size() == 0) {
table.addView(constructHeadingRow(context
.getString(R.string.submittext)));
// display the "all ok" text and
toggleButtons(true);
} else {
table.addView(constructHeadingRow(context
.getString(R.string.mandatorywarning)));
for (int i = 0; i < missingQuestions.size(); i++) {
TableRow tr = new TableRow(context);
tr.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
QuestionView qv = new QuestionView(context,
missingQuestions.get(i), getDefaultLang(),
languageCodes, true);
qv.suppressHelp(true);
// force the view to be visible (if the question has
// dependencies, it'll be hidden by default)
qv.setVisibility(View.VISIBLE);
View ruler = new View(context);
ruler.setBackgroundColor(0xFFFFFFFF);
qv.addView(ruler, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 2));
tr.addView(qv);
table.addView(tr);
}
toggleButtons(false);
}
TableRow row = new TableRow(context);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
row.addView(submitButton);
table.addView(row);
return replaceViewContent(table);
}
/**
* constructs a row in the table consisting of a single text view
* initialized with the text passed in
*
* @param text
* @return
*/
private TableRow constructHeadingRow(String text) {
TableRow tr = new TableRow(context);
TextView heading = new TextView(context);
heading.setWidth(DEFAULT_WIDTH);
heading.setTextSize(HEADING_TEXT_SIZE);
heading.setText(
Html.fromHtml("<font color='" + HEADING_COLOR + "'>" + text
+ "</font>"), BufferType.SPANNABLE);
tr.addView(heading);
return tr;
}
}
| true | true | public View refreshView(boolean setMissing) {
// first, re-save all questions to make sure we didn't miss anything
context.saveAllResponses();
submitButton = configureActionButton(R.string.submitbutton,
new OnClickListener() {
public void onClick(View v) {
// if we have no missing responses, submit the survey
databaseAdaptor.submitResponses(context
.getRespondentId().toString());
// send a broadcast message indicating new data is
// available
Intent i = new Intent(
ConstantUtil.DATA_AVAILABLE_INTENT);
context.sendBroadcast(i);
ViewUtil.showConfirmDialog(
R.string.submitcompletetitle,
R.string.submitcompletetext, context,
false,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.cancel();
context.finish();
}
}
});
}
});
TableLayout table = new TableLayout(context);
table.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// get the list (across all tabs) of missing mandatory
// responses
ArrayList<Question> missingQuestions = context.checkMandatory();
if (setMissing) {
getContext().setMissingQuestions(missingQuestions);
}
if (missingQuestions.size() == 0) {
table.addView(constructHeadingRow(context
.getString(R.string.submittext)));
// display the "all ok" text and
toggleButtons(true);
} else {
table.addView(constructHeadingRow(context
.getString(R.string.mandatorywarning)));
for (int i = 0; i < missingQuestions.size(); i++) {
TableRow tr = new TableRow(context);
tr.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
QuestionView qv = new QuestionView(context,
missingQuestions.get(i), getDefaultLang(),
languageCodes, true);
qv.suppressHelp(true);
// force the view to be visible (if the question has
// dependencies, it'll be hidden by default)
qv.setVisibility(View.VISIBLE);
View ruler = new View(context);
ruler.setBackgroundColor(0xFFFFFFFF);
qv.addView(ruler, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 2));
tr.addView(qv);
table.addView(tr);
}
toggleButtons(false);
}
TableRow row = new TableRow(context);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
row.addView(submitButton);
table.addView(row);
return replaceViewContent(table);
}
| public View refreshView(boolean setMissing) {
// first, re-save all questions to make sure we didn't miss anything
context.saveAllResponses();
submitButton = configureActionButton(R.string.submitbutton,
new OnClickListener() {
public void onClick(View v) {
// if we have no missing responses, submit the survey
databaseAdaptor.submitResponses(context
.getRespondentId().toString());
// send a broadcast message indicating new data is
// available
Intent i = new Intent(
ConstantUtil.DATA_AVAILABLE_INTENT);
context.sendBroadcast(i);
ViewUtil.showConfirmDialog(
R.string.submitcompletetitle,
R.string.submitcompletetext, context,
false,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
context.finish();
}
}
});
}
});
TableLayout table = new TableLayout(context);
table.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// get the list (across all tabs) of missing mandatory
// responses
ArrayList<Question> missingQuestions = context.checkMandatory();
if (setMissing) {
getContext().setMissingQuestions(missingQuestions);
}
if (missingQuestions.size() == 0) {
table.addView(constructHeadingRow(context
.getString(R.string.submittext)));
// display the "all ok" text and
toggleButtons(true);
} else {
table.addView(constructHeadingRow(context
.getString(R.string.mandatorywarning)));
for (int i = 0; i < missingQuestions.size(); i++) {
TableRow tr = new TableRow(context);
tr.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
QuestionView qv = new QuestionView(context,
missingQuestions.get(i), getDefaultLang(),
languageCodes, true);
qv.suppressHelp(true);
// force the view to be visible (if the question has
// dependencies, it'll be hidden by default)
qv.setVisibility(View.VISIBLE);
View ruler = new View(context);
ruler.setBackgroundColor(0xFFFFFFFF);
qv.addView(ruler, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 2));
tr.addView(qv);
table.addView(tr);
}
toggleButtons(false);
}
TableRow row = new TableRow(context);
row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
row.addView(submitButton);
table.addView(row);
return replaceViewContent(table);
}
|
diff --git a/srcj/com/sun/electric/tool/routing/RouteElementArc.java b/srcj/com/sun/electric/tool/routing/RouteElementArc.java
index 14d4aecfd..5cde4720a 100755
--- a/srcj/com/sun/electric/tool/routing/RouteElementArc.java
+++ b/srcj/com/sun/electric/tool/routing/RouteElementArc.java
@@ -1,394 +1,395 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: RouteElementArc.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.routing;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.Dimension2D;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitiveArc;
import com.sun.electric.tool.user.Highlight;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.Job;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
/**
* Created by IntelliJ IDEA.
* User: root
* Date: Jul 19, 2004
* Time: 9:16:17 PM
* To change this template use File | Settings | File Templates.
*/
public class RouteElementArc extends RouteElement {
// ---- New Arc info ----
/** Arc type to create */ private ArcProto arcProto;
/** width of arc */ private double arcWidth;
/** Head of arc */ private RouteElementPort headRE;
/** Tail of arc */ private RouteElementPort tailRE;
/** Head connecting point */ private Point2D headConnPoint;
/** Tail connecting point */ private Point2D tailConnPoint;
/** Name of arc */ private String arcName;
/** Text descriptor of name */ private TextDescriptor arcNameDescriptor;
/** Angle of arc */ private int arcAngle;
/** inherit properties from this arc */ private ArcInst inheritFrom;
/** This contains the newly create instance, or the instance to delete */ private ArcInst arcInst;
/**
* Private Constructor
* @param action the action this RouteElementAction will do.
*/
private RouteElementArc(RouteElementAction action, Cell cell) { super(action, cell); }
/**
* Factory method for making a newArc RouteElement
* @param ap Type of ArcInst to make
* @param headRE RouteElement (must be newNode or existingPortInst) at head of arc
* @param tailRE RouteElement (must be newNode or existingPortInst) at tail or arc
* @param nameTextDescriptor
* @param inheritFrom
*/
public static RouteElementArc newArc(Cell cell, ArcProto ap, double arcWidth, RouteElementPort headRE, RouteElementPort tailRE,
Point2D headConnPoint, Point2D tailConnPoint, String name, TextDescriptor nameTextDescriptor,
ArcInst inheritFrom) {
RouteElementArc e = new RouteElementArc(RouteElementAction.newArc, cell);
e.arcProto = ap;
e.arcWidth = arcWidth;
e.headRE = headRE;
e.tailRE = tailRE;
e.arcName = name;
e.arcNameDescriptor = nameTextDescriptor;
if (headRE.getAction() != RouteElement.RouteElementAction.newNode &&
headRE.getAction() != RouteElement.RouteElementAction.existingPortInst)
System.out.println(" ERROR: headRE of newArc RouteElementArc must be newNode or existingPortInst");
if (tailRE.getAction() != RouteElement.RouteElementAction.newNode &&
tailRE.getAction() != RouteElement.RouteElementAction.existingPortInst)
System.out.println(" ERROR: tailRE of newArc RouteElementArc must be newNode or existingPortInst");
headRE.addConnectingNewArc(e);
tailRE.addConnectingNewArc(e);
e.headConnPoint = headConnPoint;
e.tailConnPoint = tailConnPoint;
assert(e.headConnPoint != null);
assert(e.tailConnPoint != null);
e.arcAngle = 0;
e.arcInst = null;
e.inheritFrom = inheritFrom;
return e;
}
/**
* Factory method for making a deleteArc RouteElement
* @param arcInstToDelete the arcInst to delete
*/
public static RouteElementArc deleteArc(ArcInst arcInstToDelete) {
RouteElementArc e = new RouteElementArc(RouteElementAction.deleteArc, arcInstToDelete.getParent());
e.arcProto = arcInstToDelete.getProto();
e.arcWidth = arcInstToDelete.getWidth();
e.headRE = RouteElementPort.existingPortInst(arcInstToDelete.getHead().getPortInst(), arcInstToDelete.getHead().getLocation());
e.tailRE = RouteElementPort.existingPortInst(arcInstToDelete.getTail().getPortInst(), arcInstToDelete.getTail().getLocation());
e.arcName = arcInstToDelete.getName();
e.arcNameDescriptor = arcInstToDelete.getNameTextDescriptor();
e.headConnPoint = arcInstToDelete.getHead().getLocation();
e.tailConnPoint = arcInstToDelete.getTail().getLocation();
e.arcAngle = 0;
e.arcInst = arcInstToDelete;
e.inheritFrom = null;
return e;
}
/**
* Get the arc proto to be created/deleted.
* @return the arc proto.
*/
public ArcProto getArcProto() { return arcProto; }
public RouteElementPort getHead() { return headRE; }
public RouteElementPort getTail() { return tailRE; }
public Point2D getHeadConnPoint() { return headConnPoint; }
public Point2D getTailConnPoint() { return tailConnPoint; }
/**
* Return arc width
*/
public double getArcWidth() { return arcWidth; }
/**
* Return arc width.
* This returns the arc width taking into account any offset
*/
public double getOffsetArcWidth() {
return arcWidth - arcProto.getWidthOffset();
}
/**
* Set the arc width if this is a newArc RouteElement, otherwise does nothing.
* This is the non-offset width (i.e. the bloated width).
*/
public void setArcWidth(double width) {
if (getAction() == RouteElementAction.newArc)
arcWidth = width;
}
/**
* Set the arc width if this is a newArc RouteElement, otherwise does nothing.
* This is offset arc width (i.e. what the user sees).
*/
public void setOffsetArcWidth(double width) {
if (getAction() == RouteElementAction.newArc)
arcWidth = width + arcProto.getWidthOffset();
}
/**
* Set a newArc's angle. This only does something if both the
* head and tail of the arc are coincident points. This does
* nothing if the RouteElement is not a newArc
* @param angle the angle, in tenth degrees
*/
public void setArcAngle(int angle) {
if (getAction() == RouteElementAction.newArc)
arcAngle = angle;
}
/**
* Return true if the new arc is a vertical arc, false otherwise
*/
public boolean isArcVertical() {
Point2D head = headConnPoint;
Point2D tail = tailConnPoint;
if (head == null) head = headRE.getLocation();
if (tail == null) tail = tailRE.getLocation();
if ((head == null) || (tail == null)) return false;
if (head.getX() == tail.getX()) return true;
return false;
}
/**
* Return true if the new arc is a horizontal arc, false otherwise
*/
public boolean isArcHorizontal() {
Point2D head = headConnPoint;
Point2D tail = tailConnPoint;
if (head == null) head = headRE.getLocation();
if (tail == null) tail = tailRE.getLocation();
if ((head == null) || (tail == null)) return false;
if (head.getY() == tail.getY()) return true;
return false;
}
/**
* Used to update end points of new arc if they change
* Only valid if called on newArcs, does nothing otherwise.
* @return true if either (a) this arc does not use oldEnd, or
* (b) this arc replaced oldEnd with newEnd, and no longer uses oldEnd at all.
*/
public boolean replaceArcEnd(RouteElementPort oldEnd, RouteElementPort newEnd) {
if (getAction() == RouteElementAction.newArc) {
Poly poly = newEnd.getConnectingSite();
if (headRE == oldEnd) {
if (poly != null && poly.contains(headConnPoint)) {
headRE = newEnd;
// update book-keeping
oldEnd.removeConnectingNewArc(this);
newEnd.addConnectingNewArc(this);
}
}
if (tailRE == oldEnd) {
if (poly != null && poly.contains(tailConnPoint)) {
tailRE = newEnd;
// update book-keeping
oldEnd.removeConnectingNewArc(this);
newEnd.addConnectingNewArc(this);
}
}
}
if (headRE == oldEnd || tailRE == oldEnd) return false;
return true;
}
/**
* Perform the action specified by RouteElementAction <i>action</i>.
* Note that this method performs database editing, and should only
* be called from within a Job.
* @return the object created, or null if deleted or nothing done.
*/
public ElectricObject doAction() {
Job.checkChanging();
if (isDone()) return null;
if (getAction() == RouteElementAction.newArc) {
PortInst headPi = headRE.getPortInst();
PortInst tailPi = tailRE.getPortInst();
Point2D headPoint = headConnPoint;
Point2D tailPoint = tailConnPoint;
// special case when routing to expandable gate (and, or, mux, etc.)
Poly headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint))
{
NodeInst headNi = headPi.getNodeInst();
NodeProto np = headNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
headNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint)) {
// can't connect
System.out.println("Arc head point ("+headPoint.getX()+","+headPoint.getY()+") not inside port "+headPi+": "+headPi.getBounds());
return null;
}
Poly tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint))
{
NodeInst tailNi = tailPi.getNodeInst();
NodeProto np = tailNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
tailNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint)) {
// can't connect
System.out.println("Arc tail point ("+tailPoint.getX()+","+tailPoint.getY()+") not inside port "+tailPi+": "+tailPi.getBounds());
return null;
}
// now run the arc
ArcInst newAi = ArcInst.makeInstance(arcProto, arcWidth, headPi, tailPi, headPoint, tailPoint, arcName);
+ if (newAi == null) return null;
if (arcAngle != 0)
newAi.setAngle(arcAngle);
if ((arcName != null) && (arcNameDescriptor != null)) {
newAi.getNameTextDescriptor().copy(arcNameDescriptor);
}
setDone();
arcInst = newAi;
arcInst.copyPropertiesFrom(inheritFrom);
return newAi;
}
if (getAction() == RouteElementAction.deleteArc) {
// delete existing arc
arcInst.kill();
setDone();
}
return null;
}
/**
* Adds RouteElement to highlights
*/
public void addHighlightArea(Highlighter highlighter) {
if (!isShowHighlight()) return;
if (getAction() == RouteElementAction.newArc) {
// figure out highlight area based on arc width and start and end locations
Point2D headPoint = headConnPoint;
Point2D tailPoint = tailConnPoint;
boolean endsExtend = ((PrimitiveArc)arcProto).isExtended();
double offset = 0.5*getOffsetArcWidth();
double offsetX, offsetY;
double offsetEnds = endsExtend ? offset : 0;
Point2D head1, head2, tail1, tail2;
if (headPoint.getX() == tailPoint.getX()) {
// vertical arc
if (headPoint.getY() > tailPoint.getY()) {
offsetX = offset;
offsetY = offsetEnds;
} else {
offsetX = offset;
offsetY = -offsetEnds;
}
head1 = new Point2D.Double(headPoint.getX()+offsetX, headPoint.getY()+offsetY);
head2 = new Point2D.Double(headPoint.getX()-offsetX, headPoint.getY()+offsetY);
tail1 = new Point2D.Double(tailPoint.getX()+offsetX, tailPoint.getY()-offsetY);
tail2 = new Point2D.Double(tailPoint.getX()-offsetX, tailPoint.getY()-offsetY);
} else {
assert(headPoint.getY() == tailPoint.getY());
if (headPoint.getX() > tailPoint.getX()) {
offsetX = offsetEnds;
offsetY = offset;
} else {
offsetX = -offsetEnds;
offsetY = offset;
}
head1 = new Point2D.Double(headPoint.getX()+offsetX, headPoint.getY()+offsetY);
head2 = new Point2D.Double(headPoint.getX()+offsetX, headPoint.getY()-offsetY);
tail1 = new Point2D.Double(tailPoint.getX()-offsetX, tailPoint.getY()+offsetY);
tail2 = new Point2D.Double(tailPoint.getX()-offsetX, tailPoint.getY()-offsetY);
}
Cell cell = getCell();
highlighter.addLine(head1, tail1, cell);
//Highlight.addLine(headPoint, tailPoint, cell);
highlighter.addLine(head2, tail2, cell);
highlighter.addLine(head1, head2, cell);
highlighter.addLine(tail1, tail2, cell);
}
if (getAction() == RouteElementAction.deleteArc) {
highlighter.addElectricObject(arcInst, getCell());
}
}
/** Return string decribing the RouteElement */
public String toString() {
if (getAction() == RouteElementAction.newArc) {
return "RouteElementArc newArc "+arcProto+",\nhead: "+headRE+"\ntail: "+tailRE;
}
else if (getAction() == RouteElementAction.deleteArc) {
return "RouteElement deleteArc "+arcInst;
}
return "RouteElement bad action";
}
}
| true | true | public ElectricObject doAction() {
Job.checkChanging();
if (isDone()) return null;
if (getAction() == RouteElementAction.newArc) {
PortInst headPi = headRE.getPortInst();
PortInst tailPi = tailRE.getPortInst();
Point2D headPoint = headConnPoint;
Point2D tailPoint = tailConnPoint;
// special case when routing to expandable gate (and, or, mux, etc.)
Poly headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint))
{
NodeInst headNi = headPi.getNodeInst();
NodeProto np = headNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
headNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint)) {
// can't connect
System.out.println("Arc head point ("+headPoint.getX()+","+headPoint.getY()+") not inside port "+headPi+": "+headPi.getBounds());
return null;
}
Poly tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint))
{
NodeInst tailNi = tailPi.getNodeInst();
NodeProto np = tailNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
tailNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint)) {
// can't connect
System.out.println("Arc tail point ("+tailPoint.getX()+","+tailPoint.getY()+") not inside port "+tailPi+": "+tailPi.getBounds());
return null;
}
// now run the arc
ArcInst newAi = ArcInst.makeInstance(arcProto, arcWidth, headPi, tailPi, headPoint, tailPoint, arcName);
if (arcAngle != 0)
newAi.setAngle(arcAngle);
if ((arcName != null) && (arcNameDescriptor != null)) {
newAi.getNameTextDescriptor().copy(arcNameDescriptor);
}
setDone();
arcInst = newAi;
arcInst.copyPropertiesFrom(inheritFrom);
return newAi;
}
if (getAction() == RouteElementAction.deleteArc) {
// delete existing arc
arcInst.kill();
setDone();
}
return null;
}
| public ElectricObject doAction() {
Job.checkChanging();
if (isDone()) return null;
if (getAction() == RouteElementAction.newArc) {
PortInst headPi = headRE.getPortInst();
PortInst tailPi = tailRE.getPortInst();
Point2D headPoint = headConnPoint;
Point2D tailPoint = tailConnPoint;
// special case when routing to expandable gate (and, or, mux, etc.)
Poly headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint))
{
NodeInst headNi = headPi.getNodeInst();
NodeProto np = headNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
headNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
headPoly = headPi.getPoly();
if (!headPoly.isInside(headPoint)) {
// can't connect
System.out.println("Arc head point ("+headPoint.getX()+","+headPoint.getY()+") not inside port "+headPi+": "+headPi.getBounds());
return null;
}
Poly tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint))
{
NodeInst tailNi = tailPi.getNodeInst();
NodeProto np = tailNi.getProto();
if (np instanceof PrimitiveNode)
{
PrimitiveNode pNp = (PrimitiveNode)np;
Dimension2D autoGrowth = pNp.getAutoGrowth();
if (autoGrowth != null)
{
// grow the node to allow expandable port to fit
tailNi.modifyInstance(0, 0, autoGrowth.getWidth(), autoGrowth.getHeight(), 0);
}
}
}
tailPoly = tailPi.getPoly();
if (!tailPoly.isInside(tailPoint)) {
// can't connect
System.out.println("Arc tail point ("+tailPoint.getX()+","+tailPoint.getY()+") not inside port "+tailPi+": "+tailPi.getBounds());
return null;
}
// now run the arc
ArcInst newAi = ArcInst.makeInstance(arcProto, arcWidth, headPi, tailPi, headPoint, tailPoint, arcName);
if (newAi == null) return null;
if (arcAngle != 0)
newAi.setAngle(arcAngle);
if ((arcName != null) && (arcNameDescriptor != null)) {
newAi.getNameTextDescriptor().copy(arcNameDescriptor);
}
setDone();
arcInst = newAi;
arcInst.copyPropertiesFrom(inheritFrom);
return newAi;
}
if (getAction() == RouteElementAction.deleteArc) {
// delete existing arc
arcInst.kill();
setDone();
}
return null;
}
|
diff --git a/fsrepo/src/main/java/cz/topolik/fsrepo/model/FileSystemFolder.java b/fsrepo/src/main/java/cz/topolik/fsrepo/model/FileSystemFolder.java
index c5a5525..e336fbc 100644
--- a/fsrepo/src/main/java/cz/topolik/fsrepo/model/FileSystemFolder.java
+++ b/fsrepo/src/main/java/cz/topolik/fsrepo/model/FileSystemFolder.java
@@ -1,142 +1,142 @@
/**
* Copyright (c) 2012 Tomáš Polešovský
*
* 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.
*/
package cz.topolik.fsrepo.model;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
import cz.topolik.fsrepo.LocalFileSystemRepository;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Tomas Polesovsky
*/
public class FileSystemFolder extends FileSystemModel implements Folder {
private File folder;
private long folderId;
private Folder parentFolder;
public FileSystemFolder(LocalFileSystemRepository repository, String uuid, long folderId, File folder) {
super(repository, uuid, folder);
this.folder = folder;
this.folderId = folderId;
}
public List<Folder> getAncestors() throws PortalException, SystemException {
List<Folder> result = new ArrayList<Folder>();
Folder f = this;
while (!f.isRoot()) {
f = f.getParentFolder();
result.add(f);
}
return result;
}
public void setFolderId(long folderId) {
this.folderId = folderId;
}
public long getFolderId() {
return folderId;
}
public Date getLastPostDate() {
return new Date(folder.lastModified());
}
public String getName() {
return folder.getName();
}
public Folder getParentFolder() throws PortalException, SystemException {
try {
if (parentFolder != null) {
return parentFolder;
}
File parentFile = folder.getParentFile();
File rootFolder = repository.getRootFolder();
- if (parentFile.equals(rootFolder)) {
+ if (parentFile.getAbsolutePath().length() <= rootFolder.getAbsolutePath().length()) {
Folder mountFolder = DLAppLocalServiceUtil.getMountFolder(getRepositoryId());
parentFolder = mountFolder;
} else {
parentFolder = repository.fileToFolder(parentFile);
}
return parentFolder;
} catch (FileNotFoundException ex) {
throw new SystemException("Cannot get parent folder for [folder]: ["+folder.getAbsolutePath()+"]", ex);
}
}
public long getParentFolderId() {
try {
Folder f = getParentFolder();
return f == null ? DLFolderConstants.DEFAULT_PARENT_FOLDER_ID : f.getFolderId();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
return DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
}
public boolean isMountPoint() {
return false;
}
public boolean isRoot() {
if (getParentFolderId() == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
return true;
} else {
return false;
}
}
public boolean isSupportsMultipleUpload() {
return false;
}
public boolean isSupportsShortcuts() {
return false;
}
public Class<?> getModelClass() {
return DLFolder.class;
}
public String getModelClassName() {
return DLFolder.class.getName();
}
public Folder toEscapedModel() {
return this;
}
@Override
public long getPrimaryKey() {
return folderId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setFolderId(primaryKey);
}
}
| true | true | public Folder getParentFolder() throws PortalException, SystemException {
try {
if (parentFolder != null) {
return parentFolder;
}
File parentFile = folder.getParentFile();
File rootFolder = repository.getRootFolder();
if (parentFile.equals(rootFolder)) {
Folder mountFolder = DLAppLocalServiceUtil.getMountFolder(getRepositoryId());
parentFolder = mountFolder;
} else {
parentFolder = repository.fileToFolder(parentFile);
}
return parentFolder;
} catch (FileNotFoundException ex) {
throw new SystemException("Cannot get parent folder for [folder]: ["+folder.getAbsolutePath()+"]", ex);
}
}
| public Folder getParentFolder() throws PortalException, SystemException {
try {
if (parentFolder != null) {
return parentFolder;
}
File parentFile = folder.getParentFile();
File rootFolder = repository.getRootFolder();
if (parentFile.getAbsolutePath().length() <= rootFolder.getAbsolutePath().length()) {
Folder mountFolder = DLAppLocalServiceUtil.getMountFolder(getRepositoryId());
parentFolder = mountFolder;
} else {
parentFolder = repository.fileToFolder(parentFile);
}
return parentFolder;
} catch (FileNotFoundException ex) {
throw new SystemException("Cannot get parent folder for [folder]: ["+folder.getAbsolutePath()+"]", ex);
}
}
|
diff --git a/Runner/Runner.java b/Runner/Runner.java
index 1dd5c00..e1c1427 100755
--- a/Runner/Runner.java
+++ b/Runner/Runner.java
@@ -1,142 +1,144 @@
package Tools.Runner;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JFileChooser;
import javax.swing.border.TitledBorder;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.BufferedInputStream;
import Tools.Data.MotionDataConverter;
public class Runner extends JPanel implements ActionListener, Runnable{
private int WIDTH, HEIGHT;
private MotionDataConverter mdc;
private JFileChooser fc = new JFileChooser();
private JTextField path = new JTextField("./main.exe");
private JButton runButton = new JButton("Run");
private JButton selectButton = new JButton("Select File");
// private JEditorPane out = new JEditorPane();
private boolean end = true;
// private JScrollPane scroll = new JScrollPane(out);
public Runner(MotionDataConverter mdc){
this.mdc = mdc;
init();
}
public void init(){
setLayout(new BorderLayout());
JPanel pathPanel = new JPanel();
// scroll.setPreferredSize(new Dimension(160,160));
pathPanel.setLayout(new FlowLayout());
pathPanel.add(new JLabel("Kimoiss Path : "));
pathPanel.add(path);
pathPanel.add(selectButton);
selectButton.addActionListener(this);
JPanel runPanel = new JPanel();
runPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
runPanel.add(runButton);
runButton.addActionListener(this);
add(runPanel,BorderLayout.EAST);
// add(scroll,BorderLayout.CENTER);
add(pathPanel,BorderLayout.WEST);
}
public void update(){
revalidate();
repaint();
}
public void run(){
if(!end)return;
end = false;
/*
ArrayList<String> command = new ArrayList<String>();
command.add(Option.kPath);
command.add("-f "+Option.fps);
switch(Option.mode){
case Option.MODEL_MODE:
command.add("-m m");
command.add("-sm "+Option.saveModel);
break;
case Option.USER_MODE:
command.add("-m u");
command.add("-mo "+Option.modelPath);
command.add("-su "+Option.saveUser);
command.add("-sc "+Option.saveConvert);
break;
}
*/
try{
Runtime rt = Runtime.getRuntime();
// Process process = rt.exec(command.toArray(new String[0]));
- Process process = rt.exec(path.getText());
+ String[] str = new String[1];
+ str[0] = path.getText();
+ Process process = rt.exec(str);
String tmp = "";
byte[] output = new byte[1];
BufferedInputStream in = new BufferedInputStream(process.getInputStream());
int charactor = 0;
String[] line;
while((charactor = in.read(output)) >= 0){
if(charactor > 0){
tmp += new String(output);
if(tmp.indexOf("\r\n")>0){
line = tmp.split("\r\n");
}else if(tmp.indexOf("\r")>0){
line = tmp.split("\r");
}else if(tmp.indexOf("\n")>0){
line = tmp.split("\n");
}else{
line = new String[1];
line[0] = tmp;
}
for(int i = 0; i < line.length; i++){
String[] idxFile = line[i].split(":");
if(idxFile.length == 2){
mdc.readFile(idxFile);
}
}
// out.setText(tmp);
}
}
System.out.println(tmp);
}catch(IOException e){
e.printStackTrace();
}
end = true;
}
public void actionPerformed(ActionEvent e){
String str = e.getActionCommand();
if(str.equals("Run")){
new Thread(this).start();
}
if(str.equals("Select File")){
if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
path.setText(fc.getSelectedFile().getAbsolutePath());
}
}
}
}
| true | true | public void run(){
if(!end)return;
end = false;
/*
ArrayList<String> command = new ArrayList<String>();
command.add(Option.kPath);
command.add("-f "+Option.fps);
switch(Option.mode){
case Option.MODEL_MODE:
command.add("-m m");
command.add("-sm "+Option.saveModel);
break;
case Option.USER_MODE:
command.add("-m u");
command.add("-mo "+Option.modelPath);
command.add("-su "+Option.saveUser);
command.add("-sc "+Option.saveConvert);
break;
}
*/
try{
Runtime rt = Runtime.getRuntime();
// Process process = rt.exec(command.toArray(new String[0]));
Process process = rt.exec(path.getText());
String tmp = "";
byte[] output = new byte[1];
BufferedInputStream in = new BufferedInputStream(process.getInputStream());
int charactor = 0;
String[] line;
while((charactor = in.read(output)) >= 0){
if(charactor > 0){
tmp += new String(output);
if(tmp.indexOf("\r\n")>0){
line = tmp.split("\r\n");
}else if(tmp.indexOf("\r")>0){
line = tmp.split("\r");
}else if(tmp.indexOf("\n")>0){
line = tmp.split("\n");
}else{
line = new String[1];
line[0] = tmp;
}
for(int i = 0; i < line.length; i++){
String[] idxFile = line[i].split(":");
if(idxFile.length == 2){
mdc.readFile(idxFile);
}
}
// out.setText(tmp);
}
}
System.out.println(tmp);
}catch(IOException e){
e.printStackTrace();
}
end = true;
}
| public void run(){
if(!end)return;
end = false;
/*
ArrayList<String> command = new ArrayList<String>();
command.add(Option.kPath);
command.add("-f "+Option.fps);
switch(Option.mode){
case Option.MODEL_MODE:
command.add("-m m");
command.add("-sm "+Option.saveModel);
break;
case Option.USER_MODE:
command.add("-m u");
command.add("-mo "+Option.modelPath);
command.add("-su "+Option.saveUser);
command.add("-sc "+Option.saveConvert);
break;
}
*/
try{
Runtime rt = Runtime.getRuntime();
// Process process = rt.exec(command.toArray(new String[0]));
String[] str = new String[1];
str[0] = path.getText();
Process process = rt.exec(str);
String tmp = "";
byte[] output = new byte[1];
BufferedInputStream in = new BufferedInputStream(process.getInputStream());
int charactor = 0;
String[] line;
while((charactor = in.read(output)) >= 0){
if(charactor > 0){
tmp += new String(output);
if(tmp.indexOf("\r\n")>0){
line = tmp.split("\r\n");
}else if(tmp.indexOf("\r")>0){
line = tmp.split("\r");
}else if(tmp.indexOf("\n")>0){
line = tmp.split("\n");
}else{
line = new String[1];
line[0] = tmp;
}
for(int i = 0; i < line.length; i++){
String[] idxFile = line[i].split(":");
if(idxFile.length == 2){
mdc.readFile(idxFile);
}
}
// out.setText(tmp);
}
}
System.out.println(tmp);
}catch(IOException e){
e.printStackTrace();
}
end = true;
}
|
diff --git a/project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/Downloader/DownloadAsyncTask.java b/project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/Downloader/DownloadAsyncTask.java
index 391e1a8ca..4ca5b8643 100644
--- a/project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/Downloader/DownloadAsyncTask.java
+++ b/project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/Downloader/DownloadAsyncTask.java
@@ -1,223 +1,223 @@
/*
* Hedgewars for Android. An Android port of Hedgewars, a free turn based strategy game
* Copyright (c) 2011-2012 Richard Deurwaarder <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
package org.hedgewars.hedgeroid.Downloader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.hedgewars.hedgeroid.Downloader.DownloadService.DownloadTask;
import android.os.AsyncTask;
/**
* This is an AsyncTask which will download a zip from an URL and unzip it to a specified path
*
* a typical call to start the task would be new DownloadAsyncTask().execute(getExternalStorage(), "www.hedgewars.org/data.zip");
* @author Xeli
*
*/
public class DownloadAsyncTask extends AsyncTask<DownloadPackage, Object, Integer> {
//private final static String URL_WITHOUT_SUFFIX = "http://www.xelification.com/tmp/firebutton.";
private final static String URL_ZIP_SUFFIX = ".zip";
private final static String URL_HASH_SUFFIX = ".hash";
public static final int EXIT_SUCCESS = 0;
public static final int EXIT_URLFAIL = 1;
public static final int EXIT_CONNERROR = 2;
public static final int EXIT_FNF = 3;
public static final int EXIT_MD5 = 4;
public static final int EXIT_CANCELLED = 5;
private DownloadTask task;
private long lastUpdateMillis = 0;
public DownloadAsyncTask(DownloadTask _task){
task = _task;
}
/**
*
* @param params - A {@link}DownloadTask which gives information about where to download from and store the files to
*/
protected Integer doInBackground(DownloadPackage...packages) {
DownloadPackage pack = packages[0];//just use one task per execute call for now
HttpURLConnection conn = null;
MessageDigest digester = null;
String rootZipDest = pack.getPathToStore();
File rootDest = new File(rootZipDest);//TODO check for nullpointer, it hints to the absence of an sdcard
- rootDest.mkdir();
+ rootDest.mkdirs();
try {
URL url = new URL(pack.getURL() + URL_ZIP_SUFFIX);
conn = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
return EXIT_URLFAIL;
}
String contentType = conn.getContentType();
if(contentType == null || contentType.contains("zip")){ //Seeing as we provide the url if the contentType is unknown lets assume zips
int bytesDecompressed = 0;
ZipEntry entry = null;
ZipInputStream input = null;
FileOutputStream output = null;
int kbytesToProcess = conn.getContentLength()/1024;
byte[] buffer = new byte[1024];
task.start(kbytesToProcess);
try {
digester = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try{
input = new ZipInputStream(conn.getInputStream());
entry = input.getNextEntry();
}catch(IOException e){
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}
while(entry != null){
if(isCancelled()) break;
try {
String fileName = entry.getName();
File f = new File(rootZipDest + fileName);
bytesDecompressed += entry.getCompressedSize();
if(entry.isDirectory()){
f.mkdir();
}else{
if(f.exists()){
f.delete();
}
f.createNewFile();
output = new FileOutputStream(f);
int count = 0;
while((count = input.read(buffer)) != -1){
output.write(buffer, 0, count);
digester.update(buffer, 0, count);
if(System.currentTimeMillis() - lastUpdateMillis > 1000){
lastUpdateMillis = System.currentTimeMillis();
publishProgress(bytesDecompressed, kbytesToProcess, fileName);
}
}
output.flush();
input.closeEntry();
}//if isDir
entry = input.getNextEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_FNF;
} catch (IOException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}finally{
try {
if( output != null) output.close();
} catch (IOException e) {}
}
}//end while(entry != null)
if( input != null)
try {
input.close();
} catch (IOException e) {}
}else{//end if contentType == "zip"
return EXIT_URLFAIL;
}
if(conn != null) conn.disconnect();
if(checkMD5(digester, pack))return EXIT_SUCCESS;
else return EXIT_MD5;
}
//TODO proper result handling
protected void onPostExecute(Integer result){
task.done(result);
}
protected void onProgressUpdate(Object...objects){
task.update((Integer)objects[0], (Integer)objects[1], (String)objects[2]);
}
protected void onCancelled(){
onPostExecute(EXIT_CANCELLED);
}
private boolean checkMD5(MessageDigest digester, DownloadPackage task){
if(digester != null) {
byte[] messageDigest = digester.digest();
try {
URL url = new URL(task.getURL() + URL_HASH_SUFFIX);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
byte[] buffer = new byte[1024];//size is large enough to hold the entire hash
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
int bytesRead = bis.read(buffer);
String hash = null;
if(bytesRead > -1){
hash = new String(buffer, 0, bytesRead);
}
StringBuffer sb = new StringBuffer();
Integer tmp = 0;
for(int i = 0; i < messageDigest.length; i++){
tmp = 0xFF & messageDigest[i];
if(tmp < 0xF) sb.append('0');
sb.append(Integer.toHexString(tmp));
}
sb.append('\n');//add newline to become identical with the hash file
return hash.equals(sb.toString());
} catch (IOException e) {
e.printStackTrace();
return true;
}
}else{
return true;
}
}
}
| true | true | protected Integer doInBackground(DownloadPackage...packages) {
DownloadPackage pack = packages[0];//just use one task per execute call for now
HttpURLConnection conn = null;
MessageDigest digester = null;
String rootZipDest = pack.getPathToStore();
File rootDest = new File(rootZipDest);//TODO check for nullpointer, it hints to the absence of an sdcard
rootDest.mkdir();
try {
URL url = new URL(pack.getURL() + URL_ZIP_SUFFIX);
conn = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
return EXIT_URLFAIL;
}
String contentType = conn.getContentType();
if(contentType == null || contentType.contains("zip")){ //Seeing as we provide the url if the contentType is unknown lets assume zips
int bytesDecompressed = 0;
ZipEntry entry = null;
ZipInputStream input = null;
FileOutputStream output = null;
int kbytesToProcess = conn.getContentLength()/1024;
byte[] buffer = new byte[1024];
task.start(kbytesToProcess);
try {
digester = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try{
input = new ZipInputStream(conn.getInputStream());
entry = input.getNextEntry();
}catch(IOException e){
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}
while(entry != null){
if(isCancelled()) break;
try {
String fileName = entry.getName();
File f = new File(rootZipDest + fileName);
bytesDecompressed += entry.getCompressedSize();
if(entry.isDirectory()){
f.mkdir();
}else{
if(f.exists()){
f.delete();
}
f.createNewFile();
output = new FileOutputStream(f);
int count = 0;
while((count = input.read(buffer)) != -1){
output.write(buffer, 0, count);
digester.update(buffer, 0, count);
if(System.currentTimeMillis() - lastUpdateMillis > 1000){
lastUpdateMillis = System.currentTimeMillis();
publishProgress(bytesDecompressed, kbytesToProcess, fileName);
}
}
output.flush();
input.closeEntry();
}//if isDir
entry = input.getNextEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_FNF;
} catch (IOException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}finally{
try {
if( output != null) output.close();
} catch (IOException e) {}
}
}//end while(entry != null)
if( input != null)
try {
input.close();
} catch (IOException e) {}
}else{//end if contentType == "zip"
return EXIT_URLFAIL;
}
if(conn != null) conn.disconnect();
if(checkMD5(digester, pack))return EXIT_SUCCESS;
else return EXIT_MD5;
}
| protected Integer doInBackground(DownloadPackage...packages) {
DownloadPackage pack = packages[0];//just use one task per execute call for now
HttpURLConnection conn = null;
MessageDigest digester = null;
String rootZipDest = pack.getPathToStore();
File rootDest = new File(rootZipDest);//TODO check for nullpointer, it hints to the absence of an sdcard
rootDest.mkdirs();
try {
URL url = new URL(pack.getURL() + URL_ZIP_SUFFIX);
conn = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
return EXIT_URLFAIL;
}
String contentType = conn.getContentType();
if(contentType == null || contentType.contains("zip")){ //Seeing as we provide the url if the contentType is unknown lets assume zips
int bytesDecompressed = 0;
ZipEntry entry = null;
ZipInputStream input = null;
FileOutputStream output = null;
int kbytesToProcess = conn.getContentLength()/1024;
byte[] buffer = new byte[1024];
task.start(kbytesToProcess);
try {
digester = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
try{
input = new ZipInputStream(conn.getInputStream());
entry = input.getNextEntry();
}catch(IOException e){
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}
while(entry != null){
if(isCancelled()) break;
try {
String fileName = entry.getName();
File f = new File(rootZipDest + fileName);
bytesDecompressed += entry.getCompressedSize();
if(entry.isDirectory()){
f.mkdir();
}else{
if(f.exists()){
f.delete();
}
f.createNewFile();
output = new FileOutputStream(f);
int count = 0;
while((count = input.read(buffer)) != -1){
output.write(buffer, 0, count);
digester.update(buffer, 0, count);
if(System.currentTimeMillis() - lastUpdateMillis > 1000){
lastUpdateMillis = System.currentTimeMillis();
publishProgress(bytesDecompressed, kbytesToProcess, fileName);
}
}
output.flush();
input.closeEntry();
}//if isDir
entry = input.getNextEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_FNF;
} catch (IOException e) {
e.printStackTrace();
if(conn != null) conn.disconnect();
return EXIT_CONNERROR;
}finally{
try {
if( output != null) output.close();
} catch (IOException e) {}
}
}//end while(entry != null)
if( input != null)
try {
input.close();
} catch (IOException e) {}
}else{//end if contentType == "zip"
return EXIT_URLFAIL;
}
if(conn != null) conn.disconnect();
if(checkMD5(digester, pack))return EXIT_SUCCESS;
else return EXIT_MD5;
}
|
diff --git a/src/main/java/no/niths/services/StudentService.java b/src/main/java/no/niths/services/StudentService.java
index 30624855..f55eae73 100644
--- a/src/main/java/no/niths/services/StudentService.java
+++ b/src/main/java/no/niths/services/StudentService.java
@@ -1,85 +1,86 @@
package no.niths.services;
import java.util.ArrayList;
import java.util.List;
import no.niths.domain.Student;
import no.niths.infrastructure.interfaces.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class StudentService {
private static final Logger logger = LoggerFactory
.getLogger(StudentService.class);
@Autowired
private StudentRepository repo;
public void createStudent(Student student) {
repo.create(student);
}
/**
* Finds and returns a student with a given id.
* Returns the student with courses and committees
*
* @param id ID of student to find
* @return the student
*/
public Student getStudentById(long id) {
Student s = repo.getById(id);
if (s != null) {
if (s.getCommittees().size() > 0) {
for (int i = 0; i < s.getCommittees().size(); i++) {
s.getCommittees().get(i).setEvents(null);
+ s.getCommittees().get(i).setLeaders(null);
}
}else{
s.setCommittees(null);
}
if (s.getCourses().size() > 0) {
for (int i = 0; i < s.getCourses().size(); i++) {
s.getCourses().get(i).setTopics(null);
}
}else{
s.setCourses(null);
}
}
return s;
}
public List<Student> getAllStudents(Student s) {
ArrayList<Student> temp = (ArrayList<Student>) repo.getAll(s);
for (int i = 0; i < temp.size(); i++) {
// temp.get(i).getCommittees().size();
// temp.get(i).getCourses().size();
temp.get(i).setCommittees(null);
temp.get(i).setCourses(null);
}
return temp;
}
public void updateStudent(Student student) {
repo.update(student);
}
public boolean deleteStudent(long id) {
return repo.delete(id);
}
public List<Student> getStudentsWithNamedCourse(String name){
ArrayList<Student> temp = (ArrayList<Student>) repo.getStudentsWithNamedCourse(name);
for (int i = 0; i < temp.size(); i++) {
temp.get(i).setCommittees(null);
temp.get(i).setCourses(null);
}
return temp;
}
}
| true | true | public Student getStudentById(long id) {
Student s = repo.getById(id);
if (s != null) {
if (s.getCommittees().size() > 0) {
for (int i = 0; i < s.getCommittees().size(); i++) {
s.getCommittees().get(i).setEvents(null);
}
}else{
s.setCommittees(null);
}
if (s.getCourses().size() > 0) {
for (int i = 0; i < s.getCourses().size(); i++) {
s.getCourses().get(i).setTopics(null);
}
}else{
s.setCourses(null);
}
}
return s;
}
| public Student getStudentById(long id) {
Student s = repo.getById(id);
if (s != null) {
if (s.getCommittees().size() > 0) {
for (int i = 0; i < s.getCommittees().size(); i++) {
s.getCommittees().get(i).setEvents(null);
s.getCommittees().get(i).setLeaders(null);
}
}else{
s.setCommittees(null);
}
if (s.getCourses().size() > 0) {
for (int i = 0; i < s.getCourses().size(); i++) {
s.getCourses().get(i).setTopics(null);
}
}else{
s.setCourses(null);
}
}
return s;
}
|
diff --git a/impl/src/main/java/ceylon/modules/jboss/runtime/CeylonModuleLoader.java b/impl/src/main/java/ceylon/modules/jboss/runtime/CeylonModuleLoader.java
index 91e8fef..2e27365 100644
--- a/impl/src/main/java/ceylon/modules/jboss/runtime/CeylonModuleLoader.java
+++ b/impl/src/main/java/ceylon/modules/jboss/runtime/CeylonModuleLoader.java
@@ -1,291 +1,291 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package ceylon.modules.jboss.runtime;
import ceylon.language.descriptor.Import;
import ceylon.language.descriptor.Module;
import ceylon.modules.api.runtime.AbstractRuntime;
import ceylon.modules.api.util.CeylonToJava;
import ceylon.modules.jboss.repository.ResourceLoaderProvider;
import com.redhat.ceylon.cmr.api.Repository;
import org.jboss.modules.DependencySpec;
import org.jboss.modules.LocalLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.ModuleSpec;
import org.jboss.modules.ResourceLoader;
import org.jboss.modules.ResourceLoaderSpec;
import org.jboss.modules.filter.PathFilters;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Ceylon JBoss Module loader.
* It understands Ceylon repository notion.
*
* @author <a href="mailto:[email protected]">Ales Justin</a>
*/
public class CeylonModuleLoader extends ModuleLoader {
private static final ModuleIdentifier LANGUAGE;
private static final ModuleIdentifier CMR;
private static final ModuleIdentifier MODULES;
private static final ModuleIdentifier RUNTIME;
private static final String CEYLON_RUNTIME_PATH;
private static final Set<ModuleIdentifier> BOOTSTRAP;
static {
final String defaultVersion = System.getProperty("ceylon.version", "0.1");
LANGUAGE = ModuleIdentifier.create("ceylon.language", defaultVersion);
CMR = ModuleIdentifier.create("com.redhat.ceylon.cmr");
MODULES = ModuleIdentifier.create("org.jboss.modules");
RUNTIME = ModuleIdentifier.create("ceylon.runtime");
CEYLON_RUNTIME_PATH = CeylonToJava.class.getPackage().getName().replace(".", "/");
BOOTSTRAP = new HashSet<ModuleIdentifier>();
BOOTSTRAP.add(LANGUAGE);
BOOTSTRAP.add(CMR);
BOOTSTRAP.add(MODULES);
BOOTSTRAP.add(RUNTIME);
}
private Repository repository;
private Map<ModuleIdentifier, List<DependencySpec>> dependencies = new ConcurrentHashMap<ModuleIdentifier, List<DependencySpec>>();
private Graph<ModuleIdentifier, ModuleIdentifier, Boolean> graph = new Graph<ModuleIdentifier, ModuleIdentifier, Boolean>();
public CeylonModuleLoader(Repository repository) {
if (repository == null)
throw new IllegalArgumentException("Null repository adapter");
this.repository = repository;
}
/**
* Update module.
* Should be thread safe per module.
*
* @param module the module to update
* @param dependencySpec new dependency
* @throws ModuleLoadException for any error
*/
void updateModule(org.jboss.modules.Module module, DependencySpec dependencySpec) throws ModuleLoadException {
ModuleIdentifier mi = module.getIdentifier();
List<DependencySpec> deps = dependencies.get(mi);
if (deps == null) // should not really happen
return;
deps.add(dependencySpec);
setAndRelinkDependencies(module, deps);
refreshResourceLoaders(module);
relink(mi, new HashSet<ModuleIdentifier>());
}
/**
* Relink modules.
*
* @param mi the current module identifier
* @param visited already visited modules
* @throws ModuleLoadException for any modules error
*/
@SuppressWarnings({"unchecked"})
private void relink(ModuleIdentifier mi, Set<ModuleIdentifier> visited) throws ModuleLoadException {
if (visited.add(mi) == false)
return;
Graph.Vertex v = graph.getVertex(mi);
if (v == null)
return;
org.jboss.modules.Module module = preloadModule(mi);
relink(module);
Set<Graph.Edge<ModuleIdentifier, Boolean>> in = v.getIn();
for (Graph.Edge<ModuleIdentifier, Boolean> edge : in) {
if (edge.getCost()) {
Graph.Vertex<ModuleIdentifier, Boolean> from = edge.getFrom();
relink(from.getValue(), visited);
}
}
}
@Override
protected org.jboss.modules.Module preloadModule(ModuleIdentifier mi) throws ModuleLoadException {
if (BOOTSTRAP.contains(mi))
return org.jboss.modules.Module.getBootModuleLoader().loadModule(mi);
return super.preloadModule(mi);
}
/**
* Unload module.
*
* @param module the module
*/
void unloadModule(org.jboss.modules.Module module) {
dependencies.remove(module.getIdentifier());
unloadModuleLocal(module);
}
protected Module readModule(ModuleIdentifier mi, File moduleFile) throws Exception {
// TODO -- handle directory
final URL url = moduleFile.toURI().toURL();
final ClassLoader parent = getClass().getClassLoader();
final ClassLoader cl = new URLClassLoader(new URL[]{url}, parent);
return AbstractRuntime.loadModule(cl, mi.getName());
}
@Override
protected ModuleSpec findModule(ModuleIdentifier moduleIdentifier) throws ModuleLoadException {
try {
File moduleFile = repository.getArtifact(moduleIdentifier.getName(), moduleIdentifier.getSlot());
if (moduleFile == null)
return null;
Module module = readModule(moduleIdentifier, moduleFile);
if (module == null)
throw new ModuleLoadException("No module descriptor in module: " + moduleFile);
final List<DependencySpec> deps = new ArrayList<DependencySpec>();
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
ResourceLoader resourceLoader = ResourceLoaderProvider.getResourceLoader(moduleIdentifier, repository, moduleFile);
ResourceLoaderSpec rls = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader, PathFilters.acceptAll());
builder.addResourceRoot(rls);
Graph.Vertex<ModuleIdentifier, Boolean> vertex = graph.createVertex(moduleIdentifier, moduleIdentifier);
DependencySpec lds = DependencySpec.createLocalDependencySpec();
builder.addDependency(lds); // local resources
deps.add(lds);
Iterable<? extends Import> imports = CeylonToJava.toIterable(module.getDependencies());
if (imports != null) {
Node<Import> root = new Node<Import>();
for (Import i : imports) {
if (i.getOptional()) {
String path = CeylonToJava.toString(i.getName());
Node<Import> current = root;
String[] tokens = path.split("\\.");
for (String token : tokens) {
Node<Import> child = current.getChild(token);
if (child == null)
child = current.addChild(token);
current = child;
}
current.setValue(i);
} else {
DependencySpec mds = createModuleDependency(i);
builder.addDependency(mds);
deps.add(mds);
}
ModuleIdentifier mi = createModuleIdentifier(i);
Graph.Vertex<ModuleIdentifier, Boolean> dv = graph.createVertex(mi, mi);
- Graph.Edge.create(false, vertex, dv);
+ Graph.Edge.create(i.getExport(), vertex, dv);
}
if (root.isEmpty() == false) {
LocalLoader onDemandLoader = new OnDemandLocalLoader(moduleIdentifier, this, root);
builder.setFallbackLoader(onDemandLoader);
}
}
createModuleDependency(vertex, deps, builder, LANGUAGE);
// add runtime utils
final DependencySpec sds = DependencySpec.createModuleDependencySpec(
PathFilters.match(CEYLON_RUNTIME_PATH),
PathFilters.rejectAll(),
this,
RUNTIME,
false
);
builder.addDependency(sds);
deps.add(sds);
dependencies.put(moduleIdentifier, deps);
return builder.create();
} catch (ModuleLoadException mle) {
throw mle;
} catch (Exception e) {
throw new ModuleLoadException(e);
}
}
protected void createModuleDependency(Graph.Vertex<ModuleIdentifier, Boolean> vertex, List<DependencySpec> deps, ModuleSpec.Builder builder, ModuleIdentifier mi) {
final DependencySpec dependency = DependencySpec.createModuleDependencySpec(
PathFilters.acceptAll(),
PathFilters.rejectAll(),
this,
mi,
false
);
builder.addDependency(dependency);
deps.add(dependency);
Graph.Vertex<ModuleIdentifier, Boolean> lv = graph.createVertex(mi, mi);
Graph.Edge.create(false, vertex, lv);
}
/**
* Create module dependency from import.
*
* @param i the import
* @return new module dependency
*/
DependencySpec createModuleDependency(Import i) {
final ModuleIdentifier mi = createModuleIdentifier(i);
final boolean export = i.getExport();
return DependencySpec.createModuleDependencySpec(
PathFilters.getDefaultImportFilterWithServices(), // import everything?
(export ? PathFilters.acceptAll() : PathFilters.rejectAll()),
this,
mi,
i.getOptional()
);
}
/**
* Create module identifier.
*
* @param i the import
* @return module identifer
*/
static ModuleIdentifier createModuleIdentifier(Import i) {
return ModuleIdentifier.create(CeylonToJava.toString(i.getName()), CeylonToJava.toString(i.getVersion()));
}
public String toString() {
return "Ceylon ModuleLoader: " + repository;
}
}
| true | true | protected ModuleSpec findModule(ModuleIdentifier moduleIdentifier) throws ModuleLoadException {
try {
File moduleFile = repository.getArtifact(moduleIdentifier.getName(), moduleIdentifier.getSlot());
if (moduleFile == null)
return null;
Module module = readModule(moduleIdentifier, moduleFile);
if (module == null)
throw new ModuleLoadException("No module descriptor in module: " + moduleFile);
final List<DependencySpec> deps = new ArrayList<DependencySpec>();
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
ResourceLoader resourceLoader = ResourceLoaderProvider.getResourceLoader(moduleIdentifier, repository, moduleFile);
ResourceLoaderSpec rls = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader, PathFilters.acceptAll());
builder.addResourceRoot(rls);
Graph.Vertex<ModuleIdentifier, Boolean> vertex = graph.createVertex(moduleIdentifier, moduleIdentifier);
DependencySpec lds = DependencySpec.createLocalDependencySpec();
builder.addDependency(lds); // local resources
deps.add(lds);
Iterable<? extends Import> imports = CeylonToJava.toIterable(module.getDependencies());
if (imports != null) {
Node<Import> root = new Node<Import>();
for (Import i : imports) {
if (i.getOptional()) {
String path = CeylonToJava.toString(i.getName());
Node<Import> current = root;
String[] tokens = path.split("\\.");
for (String token : tokens) {
Node<Import> child = current.getChild(token);
if (child == null)
child = current.addChild(token);
current = child;
}
current.setValue(i);
} else {
DependencySpec mds = createModuleDependency(i);
builder.addDependency(mds);
deps.add(mds);
}
ModuleIdentifier mi = createModuleIdentifier(i);
Graph.Vertex<ModuleIdentifier, Boolean> dv = graph.createVertex(mi, mi);
Graph.Edge.create(false, vertex, dv);
}
if (root.isEmpty() == false) {
LocalLoader onDemandLoader = new OnDemandLocalLoader(moduleIdentifier, this, root);
builder.setFallbackLoader(onDemandLoader);
}
}
createModuleDependency(vertex, deps, builder, LANGUAGE);
// add runtime utils
final DependencySpec sds = DependencySpec.createModuleDependencySpec(
PathFilters.match(CEYLON_RUNTIME_PATH),
PathFilters.rejectAll(),
this,
RUNTIME,
false
);
builder.addDependency(sds);
deps.add(sds);
dependencies.put(moduleIdentifier, deps);
return builder.create();
} catch (ModuleLoadException mle) {
throw mle;
} catch (Exception e) {
throw new ModuleLoadException(e);
}
}
| protected ModuleSpec findModule(ModuleIdentifier moduleIdentifier) throws ModuleLoadException {
try {
File moduleFile = repository.getArtifact(moduleIdentifier.getName(), moduleIdentifier.getSlot());
if (moduleFile == null)
return null;
Module module = readModule(moduleIdentifier, moduleFile);
if (module == null)
throw new ModuleLoadException("No module descriptor in module: " + moduleFile);
final List<DependencySpec> deps = new ArrayList<DependencySpec>();
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
ResourceLoader resourceLoader = ResourceLoaderProvider.getResourceLoader(moduleIdentifier, repository, moduleFile);
ResourceLoaderSpec rls = ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader, PathFilters.acceptAll());
builder.addResourceRoot(rls);
Graph.Vertex<ModuleIdentifier, Boolean> vertex = graph.createVertex(moduleIdentifier, moduleIdentifier);
DependencySpec lds = DependencySpec.createLocalDependencySpec();
builder.addDependency(lds); // local resources
deps.add(lds);
Iterable<? extends Import> imports = CeylonToJava.toIterable(module.getDependencies());
if (imports != null) {
Node<Import> root = new Node<Import>();
for (Import i : imports) {
if (i.getOptional()) {
String path = CeylonToJava.toString(i.getName());
Node<Import> current = root;
String[] tokens = path.split("\\.");
for (String token : tokens) {
Node<Import> child = current.getChild(token);
if (child == null)
child = current.addChild(token);
current = child;
}
current.setValue(i);
} else {
DependencySpec mds = createModuleDependency(i);
builder.addDependency(mds);
deps.add(mds);
}
ModuleIdentifier mi = createModuleIdentifier(i);
Graph.Vertex<ModuleIdentifier, Boolean> dv = graph.createVertex(mi, mi);
Graph.Edge.create(i.getExport(), vertex, dv);
}
if (root.isEmpty() == false) {
LocalLoader onDemandLoader = new OnDemandLocalLoader(moduleIdentifier, this, root);
builder.setFallbackLoader(onDemandLoader);
}
}
createModuleDependency(vertex, deps, builder, LANGUAGE);
// add runtime utils
final DependencySpec sds = DependencySpec.createModuleDependencySpec(
PathFilters.match(CEYLON_RUNTIME_PATH),
PathFilters.rejectAll(),
this,
RUNTIME,
false
);
builder.addDependency(sds);
deps.add(sds);
dependencies.put(moduleIdentifier, deps);
return builder.create();
} catch (ModuleLoadException mle) {
throw mle;
} catch (Exception e) {
throw new ModuleLoadException(e);
}
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
index f99246ba0..27f874e42 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
@@ -1,385 +1,385 @@
/*
* 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.synapse.core.axis2;
import org.apache.axiom.om.OMException;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.RelatesTo;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.async.AxisCallback;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.client.SandeshaClientConstants;
import org.apache.synapse.FaultHandler;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.audit.AuditConfigurable;
import org.apache.synapse.audit.statistics.StatisticsReporter;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.endpoints.dispatch.Dispatcher;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import org.apache.synapse.util.ResponseAcceptEncodingProcessor;
import java.util.*;
/**
* This is the message receiver that receives the responses for outgoing messages sent out
* by Synapse. It holds a callbackStore that maps the [unique] messageID of each message to
* a callback object that gets executed on timeout or when a response is received (before timeout)
*
* The AnonymousServiceFactory uses this MessageReceiver for all Anonymous services created by it.
* This however - effectively - is a singleton class
*/
public class SynapseCallbackReceiver implements MessageReceiver {
private static final Log log = LogFactory.getLog(SynapseCallbackReceiver.class);
/** This is the synchronized callbackStore that maps outgoing messageID's to callback objects */
private final Map<String, AxisCallback> callbackStore; // will made thread safe in the constructor
/**
* Create the *single* instance of this class that would be used by all anonymous services
* used for outgoing messaging.
* @param synCfg the Synapse configuration
*/
public SynapseCallbackReceiver(SynapseConfiguration synCfg) {
callbackStore = Collections.synchronizedMap(new HashMap<String, AxisCallback>());
// create the Timer object and a TimeoutHandler task
TimeoutHandler timeoutHandler = new TimeoutHandler(callbackStore);
Timer timeOutTimer = synCfg.getSynapseTimer();
long timeoutHandlerInterval = SynapseConfigUtils.getTimeoutHandlerInterval();
// schedule timeout handler to run every n seconds (n : specified or defaults to 15s)
timeOutTimer.schedule(timeoutHandler, 0, timeoutHandlerInterval);
}
public void addCallback(String MsgID, AxisCallback callback) {
callbackStore.put(MsgID, callback);
if (log.isDebugEnabled()) {
log.debug("Callback added. Total callbacks waiting for : " + callbackStore.size());
}
}
/**
* Everytime a response message is received this method gets invoked. It will then select
* the outgoing *Synapse* message context for the reply we received, and determine what action
* to take at the Synapse level
*
* @param messageCtx the Axis2 message context of the reply received
* @throws AxisFault
*/
public void receive(MessageContext messageCtx) throws AxisFault {
String messageID = null;
if (messageCtx.getOptions() != null && messageCtx.getOptions().getRelatesTo() != null) {
// never take a chance with a NPE at this stage.. so check at each level :-)
Options options = messageCtx.getOptions();
if (options != null) {
RelatesTo relatesTo = options.getRelatesTo();
if (relatesTo != null) {
messageID = relatesTo.getValue();
}
}
} else if (messageCtx.getProperty(SandeshaClientConstants.SEQUENCE_KEY) == null) {
messageID = (String) messageCtx.getProperty(SynapseConstants.RELATES_TO_FOR_POX);
}
if (messageID != null) {
AxisCallback callback = callbackStore.remove(messageID);
if (log.isDebugEnabled()) {
log.debug("Callback removed for request message id : " + messageID +
". Pending callbacks count : " + callbackStore.size());
}
RelatesTo[] relates = messageCtx.getRelationships();
if (relates != null && relates.length > 1) {
// we set a relates to to the response message so that if WSA is not used, we
// could still link back to the original message. But if WSA was used, this
// gets duplicated, and we should remove it
removeDuplicateRelatesTo(messageCtx, relates);
}
if (callback != null) {
handleMessage(messageID, messageCtx, ((AsyncCallback) callback).getSynapseOutMsgCtx());
} else {
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response for the request with message Id : " +
messageID + " But a callback is not registered (anymore) to process this response");
}
} else if (!messageCtx.isPropertyTrue(NhttpConstants.SC_ACCEPTED)){
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response message without a message Id");
}
}
/**
* Handle the response or error (during a failed send) message received for an outgoing request
*
* @param messageID Request message ID
* @param response the Axis2 MessageContext that has been received and has to be handled
* @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
* Axis2 MC, that holds Synapse specific information such as the error
* handler stack and local properties etc.
* @throws AxisFault if the message cannot be processed
*/
private void handleMessage(String messageID ,MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Endpoint endpoint = (Endpoint) synapseOutMsgCtx.getProperty(
SynapseConstants.LAST_ENDPOINT);
if (endpoint instanceof AuditConfigurable) {
StatisticsReporter.report(synapseOutMsgCtx, (AuditConfigurable) endpoint);
}
Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
StatisticsReporter.reportFault(synapseOutMsgCtx);
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
// if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
// it flow with the error details. Else, replace its envelope with the
// fault envelope
try {
synapseOutMsgCtx.getEnvelope().build();
} catch (OMException x) {
synapseOutMsgCtx.setEnvelope(response.getEnvelope());
}
Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
response.getProperty(SynapseConstants.ERROR_CODE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
response.getProperty(SynapseConstants.ERROR_MESSAGE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL,
response.getProperty(SynapseConstants.ERROR_DETAIL));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
if (log.isDebugEnabled()) {
log.debug("[Failed Request Message ID : " + messageID + "]" +
" [New to be Retried Request Message ID : " +
synapseOutMsgCtx.getMessageID() + "]");
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
Endpoint successfulEndpoint = (Endpoint) faultStack.pop();
successfulEndpoint.onSuccess();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (String cid : cids) {
log.debug("Attachment : " + cid);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
//Processes 'Accept-Encoding'
ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(
WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
// when axis2 receives a soap message without addressing headers it users
- // ESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
+ // DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
// headers on the response. this causes a problem for synapse if the original message
// it receivs (from client) has addressing and the synaspse service invocation has not
// engage addressing. in this case when synapse receives the response from the server
// addessing In handler dissable addressing since that response does not have addressing
// headers. synapse sends the response to its orignal client using the same message
// context. Then this response does not have addressing headers since it already
// disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
// property state to original state.
if (axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
} else {
response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
}
// copy the message type property thats used by the out message to the response message
response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE));
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
response.setReplyTo(axisOutMsgCtx.getReplyTo());
response.setFaultTo(axisOutMsgCtx.getFaultTo());
if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// If this response is related to session affinity endpoints -Server initiated session
Dispatcher dispatcher =
(Dispatcher) synapseOutMsgCtx.getProperty(
SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
dispatcher.updateSession(synapseInMessageContext);
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
/**
* It is possible for us (Synapse) to cause the creation of a duplicate relatesTo as we
* try to hold onto the outgoing message ID even for POX messages using the relates to
* Now once we get a response, make sure we remove any trace of this before we proceed any
* further
* @param mc the message context from which a possibly duplicated relatesTo should be removed
* @param relates the existing relatedTo array of the message
*/
private void removeDuplicateRelatesTo(MessageContext mc, RelatesTo[] relates) {
int insertPos = 0;
RelatesTo[] newRelates = new RelatesTo[relates.length];
for (RelatesTo current : relates) {
boolean found = false;
for (int j = 0; j < newRelates.length && j < insertPos; j++) {
if (newRelates[j].equals(current) ||
newRelates[j].getValue().equals(current.getValue())) {
found = true;
break;
}
}
if (!found) {
newRelates[insertPos++] = current;
}
}
RelatesTo[] trimmedRelates = new RelatesTo[insertPos];
System.arraycopy(newRelates, 0, trimmedRelates, 0, insertPos);
mc.setRelationships(trimmedRelates);
}
}
| true | true | private void handleMessage(String messageID ,MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Endpoint endpoint = (Endpoint) synapseOutMsgCtx.getProperty(
SynapseConstants.LAST_ENDPOINT);
if (endpoint instanceof AuditConfigurable) {
StatisticsReporter.report(synapseOutMsgCtx, (AuditConfigurable) endpoint);
}
Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
StatisticsReporter.reportFault(synapseOutMsgCtx);
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
// if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
// it flow with the error details. Else, replace its envelope with the
// fault envelope
try {
synapseOutMsgCtx.getEnvelope().build();
} catch (OMException x) {
synapseOutMsgCtx.setEnvelope(response.getEnvelope());
}
Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
response.getProperty(SynapseConstants.ERROR_CODE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
response.getProperty(SynapseConstants.ERROR_MESSAGE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL,
response.getProperty(SynapseConstants.ERROR_DETAIL));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
if (log.isDebugEnabled()) {
log.debug("[Failed Request Message ID : " + messageID + "]" +
" [New to be Retried Request Message ID : " +
synapseOutMsgCtx.getMessageID() + "]");
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
Endpoint successfulEndpoint = (Endpoint) faultStack.pop();
successfulEndpoint.onSuccess();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (String cid : cids) {
log.debug("Attachment : " + cid);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
//Processes 'Accept-Encoding'
ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(
WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
// when axis2 receives a soap message without addressing headers it users
// ESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
// headers on the response. this causes a problem for synapse if the original message
// it receivs (from client) has addressing and the synaspse service invocation has not
// engage addressing. in this case when synapse receives the response from the server
// addessing In handler dissable addressing since that response does not have addressing
// headers. synapse sends the response to its orignal client using the same message
// context. Then this response does not have addressing headers since it already
// disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
// property state to original state.
if (axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
} else {
response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
}
// copy the message type property thats used by the out message to the response message
response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE));
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
response.setReplyTo(axisOutMsgCtx.getReplyTo());
response.setFaultTo(axisOutMsgCtx.getFaultTo());
if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// If this response is related to session affinity endpoints -Server initiated session
Dispatcher dispatcher =
(Dispatcher) synapseOutMsgCtx.getProperty(
SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
dispatcher.updateSession(synapseInMessageContext);
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
| private void handleMessage(String messageID ,MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Endpoint endpoint = (Endpoint) synapseOutMsgCtx.getProperty(
SynapseConstants.LAST_ENDPOINT);
if (endpoint instanceof AuditConfigurable) {
StatisticsReporter.report(synapseOutMsgCtx, (AuditConfigurable) endpoint);
}
Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
StatisticsReporter.reportFault(synapseOutMsgCtx);
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
// if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
// it flow with the error details. Else, replace its envelope with the
// fault envelope
try {
synapseOutMsgCtx.getEnvelope().build();
} catch (OMException x) {
synapseOutMsgCtx.setEnvelope(response.getEnvelope());
}
Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);
synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
response.getProperty(SynapseConstants.ERROR_CODE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
response.getProperty(SynapseConstants.ERROR_MESSAGE));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL,
response.getProperty(SynapseConstants.ERROR_DETAIL));
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);
if (log.isDebugEnabled()) {
log.debug("[Failed Request Message ID : " + messageID + "]" +
" [New to be Retried Request Message ID : " +
synapseOutMsgCtx.getMessageID() + "]");
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
Endpoint successfulEndpoint = (Endpoint) faultStack.pop();
successfulEndpoint.onSuccess();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (String cid : cids) {
log.debug("Attachment : " + cid);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
//Processes 'Accept-Encoding'
ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.setAxisMessage(axisOutMsgCtx.getAxisOperation().getMessage(
WSDLConstants.MESSAGE_LABEL_OUT_VALUE));
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
// when axis2 receives a soap message without addressing headers it users
// DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
// headers on the response. this causes a problem for synapse if the original message
// it receivs (from client) has addressing and the synaspse service invocation has not
// engage addressing. in this case when synapse receives the response from the server
// addessing In handler dissable addressing since that response does not have addressing
// headers. synapse sends the response to its orignal client using the same message
// context. Then this response does not have addressing headers since it already
// disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
// property state to original state.
if (axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) {
response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
axisOutMsgCtx.getProperty(
AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
} else {
response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
}
// copy the message type property thats used by the out message to the response message
response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE));
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
response.setReplyTo(axisOutMsgCtx.getReplyTo());
response.setFaultTo(axisOutMsgCtx.getFaultTo());
if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// If this response is related to session affinity endpoints -Server initiated session
Dispatcher dispatcher =
(Dispatcher) synapseOutMsgCtx.getProperty(
SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
dispatcher.updateSession(synapseInMessageContext);
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
|
diff --git a/src/main/java/org/osaf/cosmo/acegisecurity/ticket/TicketProcessingFilter.java b/src/main/java/org/osaf/cosmo/acegisecurity/ticket/TicketProcessingFilter.java
index 45ab7a1a2..990daf779 100644
--- a/src/main/java/org/osaf/cosmo/acegisecurity/ticket/TicketProcessingFilter.java
+++ b/src/main/java/org/osaf/cosmo/acegisecurity/ticket/TicketProcessingFilter.java
@@ -1,145 +1,145 @@
/*
* Copyright 2005 Open Source Applications 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 org.osaf.cosmo.acegisecurity.ticket;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import net.sf.acegisecurity.Authentication;
import net.sf.acegisecurity.context.security.SecureContext;
import net.sf.acegisecurity.context.security.SecureContextUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Servlet filter that populates the
* {@link net.sf.acegisecurity.ContextHolder} with a
* {@link TicketAuthenticationToken} if needed.
*
* @see http://www.sharemation.com/%7Emilele/public/dav/draft-ito-dav-ticket-00.txt
*/
public class TicketProcessingFilter implements Filter {
private static final Log log =
LogFactory.getLog(TicketProcessingFilter.class);
/** the request parameter containing a ticket: <code>ticket</code> */
public static final String PARAM_TICKET = "ticket";
/** the request header containing a ticket: <code>Ticket</code> */
public static final String HEADER_TICKET = "Ticket";
private String resourcePathPrefix;
// Filter methods
/**
* Does nothing - we use IoC lifecycle methods instead
*/
public void init(FilterConfig filterConfig)
throws ServletException {
}
/**
* Examines HTTP servlet requests for a ticket, creating a
* {@link TicketAuthenticationToken} if one is found.
*
* Looks first for the request parameter named
* by <code>PARAM_TICKET</code>. If one is not found, then looks
* for the request header named by <code>HEADER_TICKET</code>.
*/
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
if (sc.getAuthentication() == null) {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String id = httpRequest.getParameter(PARAM_TICKET);
if (id == null || id.equals("")) {
id = httpRequest.getHeader(HEADER_TICKET);
}
if (id != null && ! id.equals("")) {
// fix up the path to remove the resource path
// prefix (often the servlet path but not always),
// to remove trailing slashes (used by webdav
// to indicate collections), and to use "/" for
// the root item
String path = httpRequest.getRequestURI();
if (resourcePathPrefix != null &&
path.startsWith(resourcePathPrefix)) {
path = path.substring(resourcePathPrefix.length());
}
if (path == null || path.equals("")) {
path = "/";
}
- else if (path.endsWith("/")) {
+ if (! path.equals("/") && path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
// cadaver for some reason appends a "/" to the
// ticket query param when doing "open
// http://localhost:8080/home/bcm/?ticket=deadbeef"
if (id.endsWith("/")) {
id = id.substring(0, id.length()-1);
}
Authentication token = createAuthentication(path, id);
sc.setAuthentication(token);
if (log.isDebugEnabled()) {
log.debug("Replaced ContextHolder with ticket token: " +
sc.getAuthentication());
}
}
}
}
chain.doFilter(request, response);
}
/**
* Does nothing - we use IoC lifecycle methods instead
*/
public void destroy() {
}
// our methods
/**
* Returns a {@link TicketAuthenticationToken} for the given
* ticket.
*/
protected Authentication createAuthentication(String path, String id) {
return new TicketAuthenticationToken(path, id);
}
/**
*/
public String getResourcePathPrefix() {
return resourcePathPrefix;
}
/**
*/
public void setResourcePathPrefix(String resourcePathPrefix) {
this.resourcePathPrefix = resourcePathPrefix;
}
}
| true | true | public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
if (sc.getAuthentication() == null) {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String id = httpRequest.getParameter(PARAM_TICKET);
if (id == null || id.equals("")) {
id = httpRequest.getHeader(HEADER_TICKET);
}
if (id != null && ! id.equals("")) {
// fix up the path to remove the resource path
// prefix (often the servlet path but not always),
// to remove trailing slashes (used by webdav
// to indicate collections), and to use "/" for
// the root item
String path = httpRequest.getRequestURI();
if (resourcePathPrefix != null &&
path.startsWith(resourcePathPrefix)) {
path = path.substring(resourcePathPrefix.length());
}
if (path == null || path.equals("")) {
path = "/";
}
else if (path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
// cadaver for some reason appends a "/" to the
// ticket query param when doing "open
// http://localhost:8080/home/bcm/?ticket=deadbeef"
if (id.endsWith("/")) {
id = id.substring(0, id.length()-1);
}
Authentication token = createAuthentication(path, id);
sc.setAuthentication(token);
if (log.isDebugEnabled()) {
log.debug("Replaced ContextHolder with ticket token: " +
sc.getAuthentication());
}
}
}
}
chain.doFilter(request, response);
}
| public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
SecureContext sc = SecureContextUtils.getSecureContext();
if (sc.getAuthentication() == null) {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String id = httpRequest.getParameter(PARAM_TICKET);
if (id == null || id.equals("")) {
id = httpRequest.getHeader(HEADER_TICKET);
}
if (id != null && ! id.equals("")) {
// fix up the path to remove the resource path
// prefix (often the servlet path but not always),
// to remove trailing slashes (used by webdav
// to indicate collections), and to use "/" for
// the root item
String path = httpRequest.getRequestURI();
if (resourcePathPrefix != null &&
path.startsWith(resourcePathPrefix)) {
path = path.substring(resourcePathPrefix.length());
}
if (path == null || path.equals("")) {
path = "/";
}
if (! path.equals("/") && path.endsWith("/")) {
path = path.substring(0, path.length()-1);
}
// cadaver for some reason appends a "/" to the
// ticket query param when doing "open
// http://localhost:8080/home/bcm/?ticket=deadbeef"
if (id.endsWith("/")) {
id = id.substring(0, id.length()-1);
}
Authentication token = createAuthentication(path, id);
sc.setAuthentication(token);
if (log.isDebugEnabled()) {
log.debug("Replaced ContextHolder with ticket token: " +
sc.getAuthentication());
}
}
}
}
chain.doFilter(request, response);
}
|
diff --git a/DesktopTimeline/src/org/gephi/desktop/timeline/TimelineTopComponent.java b/DesktopTimeline/src/org/gephi/desktop/timeline/TimelineTopComponent.java
index 9ada762a3..957060760 100644
--- a/DesktopTimeline/src/org/gephi/desktop/timeline/TimelineTopComponent.java
+++ b/DesktopTimeline/src/org/gephi/desktop/timeline/TimelineTopComponent.java
@@ -1,295 +1,293 @@
/*
Copyright 2008-2010 Gephi
Authors : Julian Bilcke <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.desktop.timeline;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import org.gephi.timeline.spi.TimelineDrawer;
import org.gephi.timeline.api.TimelineAnimatorListener;
import org.gephi.timeline.api.TimelineModel;
import org.gephi.timeline.api.TimelineModelEvent;
import org.gephi.timeline.api.TimelineModelListener;
import org.gephi.ui.components.CloseButton;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.Lookup;
/**
* Top component which displays something.
*
* @author Julian Bilcke
*/
@ConvertAsProperties(dtd = "-//org.gephi.desktop.timeline//Timeline//EN",
autostore = false)
public final class TimelineTopComponent extends TopComponent implements TimelineAnimatorListener, TimelineModelListener {
private static TimelineTopComponent instance;
/** path to the icon used by the component and its open action */
static final String ICON_PATH = "org/gephi/desktop/timeline/resources/ui-status-bar.png";
private static final String PREFERRED_ID = "TimelineTopComponent";
private JPanel drawerPanel;
private TimelineAnimatorImpl animator;
private TimelineModel model;
//MinMax
private double min;
private double max;
public TimelineTopComponent() {
initComponents();
setName(NbBundle.getMessage(TimelineTopComponent.class, "CTL_TimelineTopComponent"));
// setToolTipText(NbBundle.getMessage(TimelineTopComponent.class, "HINT_TimelineTopComponent"));
setIcon(ImageUtilities.loadImage(ICON_PATH, true));
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
//Drawer
TimelineDrawer drawer = Lookup.getDefault().lookup(TimelineDrawer.class);
drawerPanel = (JPanel) drawer;
timelinePanel.add(drawerPanel);
drawerPanel.setEnabled(false);
//Animator
animator = new TimelineAnimatorImpl();
animator.addListener(this);
//Button
enableButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TimelineTopComponent.this.setEnabled(enableButton.isSelected());
if (model != null) {
model.setEnabled(enableButton.isSelected());
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TimelineTopComponent.this.close();
}
});
}
public void timelineModelChanged(TimelineModelEvent event) {
setEnabled(event.getSource().isEnabled());
TimelineDrawer drawer = (TimelineDrawer) drawerPanel;
if (drawer.getModel() == null || drawer.getModel() != event.getSource()) {
drawer.setModel(event.getSource());
}
if (model != event.getSource()) {
model = event.getSource();
}
switch (event.getEventType()) {
case MIN_CHANGED:
setMin((Double) event.getData());
break;
case MAX_CHANGED:
setMax((Double) event.getData());
break;
case VISIBLE_INTERVAL:
break;
}
}
private void setMin(double min) {
if (this.min != min) {
this.min = min;
setTimeLineVisible(!Double.isInfinite(min));
}
}
private void setMax(double max) {
if (this.max != max) {
this.max = max;
setTimeLineVisible(!Double.isInfinite(max));
}
}
private void setTimeLineVisible(final boolean visible) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (visible && !TimelineTopComponent.this.isOpened()) {
TimelineTopComponent.this.open();
TimelineTopComponent.this.requestActive();
} else if (!visible && TimelineTopComponent.this.isOpened()) {
TimelineTopComponent.this.close();
}
}
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
enableButton = new javax.swing.JToggleButton();
timelinePanel = new javax.swing.JPanel();
closeButton = new CloseButton();
- setMaximumSize(new java.awt.Dimension(2147483647, 27));
- setMinimumSize(new java.awt.Dimension(128, 16));
- setPreferredSize(new java.awt.Dimension(800, 24));
+ setMaximumSize(new java.awt.Dimension(32767, 48));
setLayout(new java.awt.GridBagLayout());
enableButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/disabled.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(enableButton, org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.enableButton.text")); // NOI18N
enableButton.setFocusable(false);
enableButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
enableButton.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/enabled.png"))); // NOI18N
enableButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
enableButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enableButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(enableButton, gridBagConstraints);
timelinePanel.setEnabled(false);
timelinePanel.setMinimumSize(new java.awt.Dimension(300, 28));
timelinePanel.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(timelinePanel, gridBagConstraints);
closeButton.setToolTipText(org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.closeButton.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(closeButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void enableButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_enableButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
private javax.swing.JToggleButton enableButton;
private javax.swing.JPanel timelinePanel;
// End of variables declaration//GEN-END:variables
/**
* Gets default instance. Do not use directly: reserved for *.settings files only,
* i.e. deserialization routines; otherwise you could get a non-deserialized instance.
* To obtain the singleton instance, use {@link #findInstance}.
*/
public static synchronized TimelineTopComponent getDefault() {
if (instance == null) {
instance = new TimelineTopComponent();
}
return instance;
}
/**
* Obtain the TimelineTopComponent instance. Never call {@link #getDefault} directly!
*/
public static synchronized TimelineTopComponent findInstance() {
TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
if (win == null) {
Logger.getLogger(TimelineTopComponent.class.getName()).warning(
"Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
return getDefault();
}
if (win instanceof TimelineTopComponent) {
return (TimelineTopComponent) win;
}
Logger.getLogger(TimelineTopComponent.class.getName()).warning(
"There seem to be multiple components with the '" + PREFERRED_ID
+ "' ID. That is a potential source of errors and unexpected behavior.");
return getDefault();
}
@Override
public int getPersistenceType() {
return TopComponent.PERSISTENCE_ALWAYS;
}
@Override
public void componentOpened() {
// TODO add custom code on component opening
}
@Override
public void componentClosed() {
// TODO add custom code on component closing
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
Object readProperties(java.util.Properties p) {
if (instance == null) {
instance = this;
}
instance.readPropertiesImpl(p);
return instance;
}
private void readPropertiesImpl(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
@Override
protected String preferredID() {
return PREFERRED_ID;
}
@Override
public void setEnabled(boolean enable) {
drawerPanel.setEnabled(enable);
timelinePanel.setEnabled(enable);
if (enableButton.isSelected() != enable) {
enableButton.setSelected(enable);
}
}
public void timelineAnimatorChanged(ChangeEvent event) {
// check animator value, to update the buttons etc..
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
enableButton = new javax.swing.JToggleButton();
timelinePanel = new javax.swing.JPanel();
closeButton = new CloseButton();
setMaximumSize(new java.awt.Dimension(2147483647, 27));
setMinimumSize(new java.awt.Dimension(128, 16));
setPreferredSize(new java.awt.Dimension(800, 24));
setLayout(new java.awt.GridBagLayout());
enableButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/disabled.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(enableButton, org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.enableButton.text")); // NOI18N
enableButton.setFocusable(false);
enableButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
enableButton.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/enabled.png"))); // NOI18N
enableButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
enableButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enableButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(enableButton, gridBagConstraints);
timelinePanel.setEnabled(false);
timelinePanel.setMinimumSize(new java.awt.Dimension(300, 28));
timelinePanel.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(timelinePanel, gridBagConstraints);
closeButton.setToolTipText(org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.closeButton.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(closeButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
enableButton = new javax.swing.JToggleButton();
timelinePanel = new javax.swing.JPanel();
closeButton = new CloseButton();
setMaximumSize(new java.awt.Dimension(32767, 48));
setLayout(new java.awt.GridBagLayout());
enableButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/disabled.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(enableButton, org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.enableButton.text")); // NOI18N
enableButton.setFocusable(false);
enableButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
enableButton.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/timeline/resources/enabled.png"))); // NOI18N
enableButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
enableButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enableButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(enableButton, gridBagConstraints);
timelinePanel.setEnabled(false);
timelinePanel.setMinimumSize(new java.awt.Dimension(300, 28));
timelinePanel.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(timelinePanel, gridBagConstraints);
closeButton.setToolTipText(org.openide.util.NbBundle.getMessage(TimelineTopComponent.class, "TimelineTopComponent.closeButton.toolTipText")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(closeButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/jlad-trainers/jlad-trainer-wikipedia/src/main/java/com/aperigeek/jlad/trainer/wikipedia/Main.java b/jlad-trainers/jlad-trainer-wikipedia/src/main/java/com/aperigeek/jlad/trainer/wikipedia/Main.java
index 055d097..2828c97 100644
--- a/jlad-trainers/jlad-trainer-wikipedia/src/main/java/com/aperigeek/jlad/trainer/wikipedia/Main.java
+++ b/jlad-trainers/jlad-trainer-wikipedia/src/main/java/com/aperigeek/jlad/trainer/wikipedia/Main.java
@@ -1,106 +1,107 @@
/*
* 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.aperigeek.jlad.trainer.wikipedia;
import com.aperigeek.jlad.trainer.TrainerException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
/**
* Main class responsible for running the Wikipedia trainer.
*
* @author Vivien Barousse
*/
public class Main {
/**
* Runs the application.
*
* Currently, the application takes the input file on the standard input
* and outputs the n-grams repartitions on the standard output, without
* any specific order.
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Properties commandArgs;
try {
commandArgs = parseArguments(args);
} catch (CommandLineArgsParseException ex) {
System.err.println(ex.getMessage());
return;
}
WikipediaTrainer trainer = new WikipediaTrainer(System.in);
try {
trainer.setLimit(Integer.parseInt(commandArgs.getProperty("-n", "0")));
trainer.train();
trainer.dump((OutputStream) System.out);
} catch (TrainerException ex) {
System.err.println("Unexpected error while training.");
ex.printStackTrace(System.err);
} catch (IOException ex) {
System.out.println("Error while writing results.");
ex.printStackTrace(System.err);
}
}
private static Properties parseArguments(String... args) throws CommandLineArgsParseException {
Properties p = new Properties();
int i = 0;
try {
while (i < args.length) {
if (args[i].equals("-n")) {
i++;
// Checks integer validity
int n = Integer.parseInt(args[i]);
p.put("-n", Integer.toString(n));
+ i++;
} else {
throw new CommandLineArgsParseException("Unknown option " + args[i]);
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new CommandLineArgsParseException(
"Missing parameter after" + args[i - 1],
ex);
} catch (NumberFormatException ex) {
throw new CommandLineArgsParseException(
"Invalid number for option " + args[i - 1],
ex);
}
return p;
}
private static class CommandLineArgsParseException extends Exception {
public CommandLineArgsParseException(Throwable cause) {
super(cause);
}
public CommandLineArgsParseException(String message, Throwable cause) {
super(message, cause);
}
public CommandLineArgsParseException(String message) {
super(message);
}
public CommandLineArgsParseException() {
}
}
}
| true | true | private static Properties parseArguments(String... args) throws CommandLineArgsParseException {
Properties p = new Properties();
int i = 0;
try {
while (i < args.length) {
if (args[i].equals("-n")) {
i++;
// Checks integer validity
int n = Integer.parseInt(args[i]);
p.put("-n", Integer.toString(n));
} else {
throw new CommandLineArgsParseException("Unknown option " + args[i]);
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new CommandLineArgsParseException(
"Missing parameter after" + args[i - 1],
ex);
} catch (NumberFormatException ex) {
throw new CommandLineArgsParseException(
"Invalid number for option " + args[i - 1],
ex);
}
return p;
}
| private static Properties parseArguments(String... args) throws CommandLineArgsParseException {
Properties p = new Properties();
int i = 0;
try {
while (i < args.length) {
if (args[i].equals("-n")) {
i++;
// Checks integer validity
int n = Integer.parseInt(args[i]);
p.put("-n", Integer.toString(n));
i++;
} else {
throw new CommandLineArgsParseException("Unknown option " + args[i]);
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
throw new CommandLineArgsParseException(
"Missing parameter after" + args[i - 1],
ex);
} catch (NumberFormatException ex) {
throw new CommandLineArgsParseException(
"Invalid number for option " + args[i - 1],
ex);
}
return p;
}
|
diff --git a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java
index eea6d51a..59b1afa8 100644
--- a/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java
+++ b/libraries/jnaerator/ochafik-util/src/main/java/com/ochafik/util/string/StringUtils.java
@@ -1,310 +1,310 @@
/*
Copyright (c) 2009 Olivier Chafik, All Rights Reserved
This file is part of JNAerator (http://jnaerator.googlecode.com/).
JNAerator 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.
JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ochafik.util.string;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
public static String htmlize(String text) {
return text.startsWith("<?") || text.startsWith("<html>") ?
text : "<html><body>"+
text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\n","<br>")+
"</body></html>";
}
static Pattern spacePattern;
public static List<String> explode(String s) {
if (spacePattern == null) {
spacePattern = Pattern.compile("\\s+");
}
return explode(s, spacePattern);
}
public static List<String> explode(String s, String sep) {
StringTokenizer st=new StringTokenizer(s,sep);
List<String> v = new ArrayList<String>();
for (;st.hasMoreTokens();) {
v.add(st.nextToken());
}
return v;
}
public static String trimUnderscores(String s) {
return trimChar(s, '_');
}
public static String trimChar(String s, char t) {
if (s == null)
return null;
int start = 0, n = s.length(), end = n;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c != t) {
start = i;
break;
}
}
for (int i = n - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c != t) {
end = i + 1;
break;
}
}
return s.substring(start, end);
}
/*
public static final String implode(Object[] strings, String separator) {
return implode(Arrays.asList(strings), separator);
}
*/
public static String implode(double[] array, String separator) {
StringBuffer out = new StringBuffer();
boolean first = true;
for (double v : array) {
if (first) first = false;
else out.append(separator);
out.append(v);
}
return out.toString();
}
public static String implode(Object[] values) {
return implode(values, ", ");
}
public static String implode(Object[] values, Object separator) {
return implode(Arrays.asList(values), separator);
}
public static final <T> String implode(Iterable<T> elements, Object separator) {
String sepStr = separator.toString();
StringBuilder out = new StringBuilder();
boolean first = true;
for (Object s : elements) {
if (s == null)
continue;
if (first)
first = false;
else
out.append(sepStr);
out.append(s);
}
return out.toString();
}
public static final String implode(Iterable<?> strings) {
return implode(strings, ", ");
}
/*
public static final String implode(Collection<?> strings, String separator) {
int size = 0, n = strings.size();
for (Object s : strings)
if (s != null)
size += s.toString().length();
StringBuffer out = new StringBuffer(size + separator.length() * (n == 0 ? 0 : n - 1));
boolean first = true;
for (Object s : strings) {
if (s == null)
continue;
if (first) first = false;
else out.append(separator);
out.append(s);
}
return out.toString();
}
*/
public static final List<String> explode(String string, Pattern separator) {
int lastIndex = 0, len = string.length();
Matcher matcher = separator.matcher(string);
List<String> ret = new LinkedList<String>();
while (matcher.find()) {
String s = string.substring(lastIndex, matcher.start());
if (s.length() > 0) ret.add(s);
lastIndex = matcher.end();
}
String s = string.substring(lastIndex, len);
if (s.length() > 0) ret.add(s);
return ret;
}
public static String replace(String pattern, String replace, String s) {
return concatWithSeparator(explode(s,pattern).toArray(new String[0]),replace);
}
public static final String concat(String[] a) {
StringBuffer b=new StringBuffer();
for (int i=0;i<a.length;i++) b.append(a[i]);
return b.toString();
}
public static final String concatln(String[] a) {
StringBuffer b=new StringBuffer();
int lenm=a.length-1;
for (int i=0;i<lenm;i++) {
b.append(a[i]);
b.append("\n");
}
if (lenm!=-1) b.append(a[lenm]);
return b.toString();
}
public static final String concatSpace(String[] a) {
StringBuffer b=new StringBuffer();
int lenm=a.length-1;
for (int i=0;i<lenm;i++) {
b.append(a[i]);
b.append(" ");
}
if (lenm!=-1) b.append(a[lenm]);
return b.toString();
}
public static final String concatWithSeparator(String[] a,String sep) {
StringBuffer b=new StringBuffer();
int lenm=a.length-1;
for (int i=0;i<lenm;i++) {
b.append(a[i]);
b.append(sep);
}
if (lenm!=-1) b.append(a[lenm]);
return b.toString();
}
public static final String javaEscape(String s) {
if (s == null)
return null;
char c;
int len=s.length();
StringBuffer b=new StringBuffer(len);
for (int i=0;i<len;i++) {
c=s.charAt(i);
switch (c) {
case '\n':
b.append("\\n");
break;
case '\t':
b.append("\\t");
break;
case '\r':
b.append("\\r");
break;
case '"':
- b.append("\"");
+ b.append("\\\"");
break;
case '\\':
b.append("\\\\");
break;
default:
if (c>127||Character.isISOControl(c)) {
b.append("\\u");
String nb=Integer.toString((int)c,16);
int nblen=nb.length();
switch (nblen) {
case 1:
b.append(0);
case 2:
b.append(0);
case 3:
b.append(0);
case 4:
b.append(nb);
break;
default:
throw new IllegalArgumentException("Should not happen !");
}
} else b.append(c);
}
}
return b.toString();
}
public static final String javaUnEscape(String s) {
char c;
int len=s.length();
StringBuffer b=new StringBuffer(len);
for (int i=0;i<len;i++) {
c=s.charAt(i);
if (c=='\\') {
c=s.charAt(++i);
switch (c) {
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 't':
b.append('\t');
break;
case '\\':
b.append('\\');
break;
case '"':
b.append('"');
break;
case '\'':
b.append('\'');
break;
case 'u':
try {
String nb=s.substring(i+1,i+5);
int n=Integer.parseInt(nb,16);
b.append((char)n);
i+=4;
} catch (Exception ex) {
throw new IllegalArgumentException("Illegal unicode escaping in string \"" + s + "\" at index " + i, ex);
}
break;
default:
throw new IllegalArgumentException("Unknown character: \"\\"+String.valueOf(c)+"...\"");
}
} else b.append(c);
}
return b.toString();
}
public static String capitalize(String string) {
return string == null ? null : string.length() == 0 ? "" : Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
public static String capitalize(List<String> strings, String separator) {
List<String> cap = new ArrayList<String>(strings.size());
for (String s : strings)
cap.add(capitalize(s));
return implode(cap, separator);
}
public static String underscoredToCamel(String string) {
String[] a = string.split("_");
for (int i = 0, n = a.length; i < n; i++) {
String s = a[i].trim();
a[i] = capitalize(a[i]);
}
return implode(a, "");
}
public static String uncapitalize(String string) {
return string.length() == 0 ? "" : Character.toLowerCase(string.charAt(0)) + string.substring(1);
}
public static final String LINE_SEPARATOR;
static {
LINE_SEPARATOR = System.getProperty("line.separator");
}
}
| true | true | public static final String javaEscape(String s) {
if (s == null)
return null;
char c;
int len=s.length();
StringBuffer b=new StringBuffer(len);
for (int i=0;i<len;i++) {
c=s.charAt(i);
switch (c) {
case '\n':
b.append("\\n");
break;
case '\t':
b.append("\\t");
break;
case '\r':
b.append("\\r");
break;
case '"':
b.append("\"");
break;
case '\\':
b.append("\\\\");
break;
default:
if (c>127||Character.isISOControl(c)) {
b.append("\\u");
String nb=Integer.toString((int)c,16);
int nblen=nb.length();
switch (nblen) {
case 1:
b.append(0);
case 2:
b.append(0);
case 3:
b.append(0);
case 4:
b.append(nb);
break;
default:
throw new IllegalArgumentException("Should not happen !");
}
} else b.append(c);
}
}
return b.toString();
}
| public static final String javaEscape(String s) {
if (s == null)
return null;
char c;
int len=s.length();
StringBuffer b=new StringBuffer(len);
for (int i=0;i<len;i++) {
c=s.charAt(i);
switch (c) {
case '\n':
b.append("\\n");
break;
case '\t':
b.append("\\t");
break;
case '\r':
b.append("\\r");
break;
case '"':
b.append("\\\"");
break;
case '\\':
b.append("\\\\");
break;
default:
if (c>127||Character.isISOControl(c)) {
b.append("\\u");
String nb=Integer.toString((int)c,16);
int nblen=nb.length();
switch (nblen) {
case 1:
b.append(0);
case 2:
b.append(0);
case 3:
b.append(0);
case 4:
b.append(nb);
break;
default:
throw new IllegalArgumentException("Should not happen !");
}
} else b.append(c);
}
}
return b.toString();
}
|
diff --git a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
index 62599dcf..8c540df4 100644
--- a/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
+++ b/plugins/org.eclipse.m2m.atl.engine/src/org/eclipse/m2m/atl/engine/parser/AtlSourceManager.java
@@ -1,465 +1,465 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.engine.parser;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.m2m.atl.core.ATLCoreException;
import org.eclipse.m2m.atl.engine.compiler.AtlCompiler;
/**
* ATL source inspector, used to catch main file informations. Also allows to update them.
*
* @author <a href="mailto:[email protected]">William Piers</a>
*/
public final class AtlSourceManager {
/** ATL compiler tag. */
public static final String COMPILER_TAG = "atlcompiler"; //$NON-NLS-1$
/** URI tag value. */
public static final String URI_TAG = "nsURI"; //$NON-NLS-1$
/** PATH tag value. */
public static final String PATH_TAG = "path"; //$NON-NLS-1$
// ATL File Type:
/** Undefined. */
public static final int ATL_FILE_TYPE_UNDEFINED = 0;
/** Module. */
public static final int ATL_FILE_TYPE_MODULE = 1;
/** Query. */
public static final int ATL_FILE_TYPE_QUERY = 3;
/** Library. */
public static final int ATL_FILE_TYPE_LIBRARY = 4;
// Metamodel filter types:
/** 0 : input + output metamodels. */
public static final int FILTER_ALL_METAMODELS = 0;
/** 1 : input metamodels. */
public static final int FILTER_INPUT_METAMODELS = 1;
/** 2 : OUTPUT metamodels. */
public static final int FILTER_OUTPUT_METAMODELS = 2;
private static final ResourceSet RESOURCE_SET = new ResourceSetImpl();
/** The detected metamodels Map[id,List[EPackage]]. */
private Map metamodelsPackages;
/** Input models / metamodels names Map. */
private Map inputModels;
/** Output models / metamodels names Map. */
private Map outputModels;
private List librariesImports;
private int atlFileType;
private String atlCompiler;
private boolean initialized;
private boolean isRefining;
private EObject model;
private Map metamodelLocations;
/**
* Creates an atl source manager.
*/
public AtlSourceManager() {
super();
}
/**
* Returns the ATL file type.
*
* @return the ATL file type
*/
public int getATLFileType() {
return atlFileType;
}
public Map getInputModels() {
return inputModels;
}
public Map getOutputModels() {
return outputModels;
}
public List getLibrariesImports() {
return librariesImports;
}
/**
* Update method : parsing and metamodel detection.
*
* @param content
* the content of the atl file
*/
public void updateDataSource(String content) {
parseMetamodels(content);
}
/**
* Update method : parsing and metamodel detection.
*
* @param inputStream
* the atl file input stream
*/
public void updateDataSource(InputStream inputStream) throws IOException {
String content = null;
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
content = new String(bytes);
updateDataSource(content);
}
public boolean isRefining() {
return isRefining;
}
public EObject getModel() {
return model;
}
/**
* Metamodels access method.
*
* @param filter
* the metamodel filter
* @return the map of searched metamodels
*/
public Map getMetamodelPackages(int filter) {
if (inputModels == null && outputModels == null) {
return metamodelsPackages;
}
switch (filter) {
case FILTER_INPUT_METAMODELS:
Map inputres = new HashMap();
for (Iterator iterator = inputModels.values().iterator(); iterator.hasNext();) {
String id = (String)iterator.next();
inputres.put(id, metamodelsPackages.get(id));
}
return inputres;
case FILTER_OUTPUT_METAMODELS:
Map outputres = new HashMap();
for (Iterator iterator = outputModels.values().iterator(); iterator.hasNext();) {
String id = (String)iterator.next();
outputres.put(id, metamodelsPackages.get(id));
}
return outputres;
default:
return metamodelsPackages;
}
}
/**
* Access on a specific metamodel.
*
* @param metamodelId
* the metamodel id
* @return the metamodels list
*/
public List getMetamodelPackages(String metamodelId) {
return (List)metamodelsPackages.get(metamodelId);
}
/**
* Parsing method : detects uris and stores metamodels.
*
* @param text
* the atl file.
* @throws IOException
*/
private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
- if (path.startsWith("file:/")) { //$NON-NLS-1$
+ if (path.startsWith("file:/") || path.startsWith("platform:/plugin")) { //$NON-NLS-1$ //$NON-NLS-2$
resource = load(URI.createURI(path, true), RESOURCE_SET);
} else {
resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
}
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
public String getAtlCompiler() {
return atlCompiler;
}
public Map getMetamodelLocations() {
return metamodelLocations;
}
/**
* Status method.
*
* @return <code>True</code> if the some metamodels have ever been detected , <code>False</code> if not.
*/
public boolean initialized() {
return initialized;
}
/**
* Returns the list of tagged informations (header).
*
* @param buffer
* the input
* @param tag
* the tag to search
* @return the tagged information
*/
public static List getTaggedInformations(byte[] buffer, String tag) {
List res = new ArrayList();
try {
int length = buffer.length;
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer,
0, length)));
while (reader.ready()) {
String line = reader.readLine();
// code begins, checking stops.
if (line == null || line.startsWith("library") //$NON-NLS-1$
|| line.startsWith("module") || line.startsWith("query")) { //$NON-NLS-1$ //$NON-NLS-2$
break;
} else {
if (line.trim().startsWith("-- @" + tag)) { //$NON-NLS-1$
line = line.replaceFirst("^\\p{Space}*--\\p{Space}*@" //$NON-NLS-1$
+ tag + "\\p{Space}+([^\\p{Space}]*)\\p{Space}*$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
res.add(line);
}
}
}
reader.close();
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
return res;
}
/**
* Returns the compiler name, or the default name if null.
*
* @param compilers
* the list of compilers
* @return the compiler name, or the default name if null
*/
public static String getCompilerName(List compilers) {
if (compilers.isEmpty()) {
return AtlCompiler.DEFAULT_COMPILER_NAME;
} else {
return compilers.get(0).toString();
}
}
/**
* Loads a model from an {@link org.eclipse.emf.common.util.URI URI} in a given {@link ResourceSet}.
*
* @param modelURI
* {@link org.eclipse.emf.common.util.URI URI} where the model is stored.
* @param resourceSet
* The {@link ResourceSet} to load the model in.
* @return The packages of the model loaded from the URI.
* @throws IOException
* If the given file does not exist.
*/
private static Resource load(URI modelURI, ResourceSet resourceSet) throws IOException {
String fileExtension = modelURI.fileExtension();
if (fileExtension == null || fileExtension.length() == 0) {
fileExtension = Resource.Factory.Registry.DEFAULT_EXTENSION;
}
final Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
final Object resourceFactory = reg.getExtensionToFactoryMap().get(fileExtension);
if (resourceFactory != null) {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
resourceFactory);
} else {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension,
new XMIResourceFactoryImpl());
}
final Resource modelResource = resourceSet.createResource(modelURI);
final Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, System.getProperty("file.encoding")); //$NON-NLS-1$
modelResource.load(options);
return modelResource;
}
/**
* Returns the value of a feature on an EObject.
*
* @param self
* the EObject
* @param featureName
* the feature name
* @return the feature value
*/
private static Object eGet(EObject self, String featureName) {
if (self != null) {
EStructuralFeature feature = self.eClass().getEStructuralFeature(featureName);
if (feature != null) {
return self.eGet(feature);
}
}
return null;
}
}
| true | true | private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
if (path.startsWith("file:/")) { //$NON-NLS-1$
resource = load(URI.createURI(path, true), RESOURCE_SET);
} else {
resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
}
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
| private void parseMetamodels(String text) {
metamodelsPackages = new HashMap();
metamodelLocations = new HashMap();
inputModels = new LinkedHashMap();
outputModels = new LinkedHashMap();
librariesImports = new ArrayList();
List compilers = getTaggedInformations(text.getBytes(), COMPILER_TAG);
atlCompiler = getCompilerName(compilers);
List uris = getTaggedInformations(text.getBytes(), URI_TAG);
for (Iterator iterator = uris.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String uri = line.split("=")[1].trim(); //$NON-NLS-1$
if (uri != null && uri.length() > 0) {
uri = uri.trim();
// EPackage registration
EPackage regValue = EPackage.Registry.INSTANCE.getEPackage(uri);
if (regValue != null) {
ArrayList list = new ArrayList();
list.add(regValue);
metamodelsPackages.put(name, list);
metamodelLocations.put(name, "uri:" + uri); //$NON-NLS-1$
}
}
}
}
List paths = getTaggedInformations(text.getBytes(), PATH_TAG);
for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
String line = (String)iterator.next();
if (line.split("=").length == 2) { //$NON-NLS-1$
String name = line.split("=")[0].trim(); //$NON-NLS-1$
String path = line.split("=")[1].trim(); //$NON-NLS-1$
if (path != null && path.length() > 0) {
path = path.trim();
Resource resource = null;
try {
if (path.startsWith("file:/") || path.startsWith("platform:/plugin")) { //$NON-NLS-1$ //$NON-NLS-2$
resource = load(URI.createURI(path, true), RESOURCE_SET);
} else {
resource = load(URI.createPlatformResourceURI(path, true), RESOURCE_SET);
}
} catch (IOException e) {
// TODO apply marker on the file
// Exceptions are detected by the compiler
// AtlUIPlugin.log(e);
}
if (resource != null) {
ArrayList list = new ArrayList();
for (Iterator it = resource.getContents().iterator(); it.hasNext();) {
Object object = it.next();
if (object instanceof EPackage) {
list.add(object);
}
}
metamodelsPackages.put(name, list);
metamodelLocations.put(name, path);
}
}
}
}
try {
model = AtlParser.getDefault().parse(new ByteArrayInputStream(text.getBytes()));
} catch (ATLCoreException e) {
// fail silently
}
if (model == null) {
inputModels = null;
outputModels = null;
return;
}
if (model.eClass().getName().equals("Module")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_MODULE;
isRefining = ((Boolean)eGet(model, "isRefining")).booleanValue(); //$NON-NLS-1$
// input models computation
EList inModelsList = (EList)eGet(model, "inModels"); //$NON-NLS-1$
if (inModelsList != null) {
for (Iterator iterator = inModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
inputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// output models computation
EList outModelsList = (EList)eGet(model, "outModels"); //$NON-NLS-1$
if (outModelsList != null) {
for (Iterator iterator = outModelsList.iterator(); iterator.hasNext();) {
EObject me = (EObject)iterator.next();
EObject mm = (EObject)eGet(me, "metamodel"); //$NON-NLS-1$
outputModels.put(eGet(me, "name"), eGet(mm, "name")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else if (model.eClass().getName().equals("Query")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_QUERY;
outputModels = null;
for (Iterator iterator = model.eResource().getAllContents(); iterator.hasNext();) {
EObject eo = (EObject)iterator.next();
if (eo.eClass().getName().equals("OclModel")) { //$NON-NLS-1$
String metamodelName = (String)eGet(eo, "name"); //$NON-NLS-1$
inputModels.put("IN", metamodelName); //$NON-NLS-1$
break;
}
}
} else if (model.eClass().getName().equals("Library")) { //$NON-NLS-1$
atlFileType = ATL_FILE_TYPE_LIBRARY;
}
// libraries computation
EList librariesList = (EList)eGet(model, "libraries"); //$NON-NLS-1$
if (librariesList != null) {
for (Iterator iterator = librariesList.iterator(); iterator.hasNext();) {
EObject lib = (EObject)iterator.next();
librariesImports.add(eGet(lib, "name")); //$NON-NLS-1$
}
}
initialized = true;
}
|
diff --git a/modules/resin/src/com/caucho/quercus/env/CompositeDataValue.java b/modules/resin/src/com/caucho/quercus/env/CompositeDataValue.java
index 56b3192f0..d0eb0615c 100644
--- a/modules/resin/src/com/caucho/quercus/env/CompositeDataValue.java
+++ b/modules/resin/src/com/caucho/quercus/env/CompositeDataValue.java
@@ -1,83 +1,84 @@
/*
* Copyright (c) 1998-2005 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Sam
*/
package com.caucho.quercus.env;
import com.caucho.quercus.env.Value;
import javax.management.Attribute;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.*;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CompositeDataValue extends Value {
private static final Logger log
= Logger.getLogger(CompositeDataValue.class.getName());
private CompositeData _data;
public CompositeDataValue(CompositeData data)
{
_data = data;
}
/**
* Returns an attribute.
*/
@Override
public Value getField(Env env, String attrName)
{
try {
return env.wrapJava(_data.get(attrName));
} catch (InvalidKeyException e) {
env.warning(e);
+ return NullValue.NULL;
}
}
/**
* Convert to java
*/
@Override
public Object toJavaObject()
{
return _data;
}
public String toString()
{
return _data.getCompositeType().toString();
}
}
| true | true | public Value getField(Env env, String attrName)
{
try {
return env.wrapJava(_data.get(attrName));
} catch (InvalidKeyException e) {
env.warning(e);
}
}
| public Value getField(Env env, String attrName)
{
try {
return env.wrapJava(_data.get(attrName));
} catch (InvalidKeyException e) {
env.warning(e);
return NullValue.NULL;
}
}
|
diff --git a/applications/src/main/java/demo/Demo.java b/applications/src/main/java/demo/Demo.java
index f28ead3..5d23e09 100644
--- a/applications/src/main/java/demo/Demo.java
+++ b/applications/src/main/java/demo/Demo.java
@@ -1,58 +1,58 @@
package demo;
import org.rcsb.ks.controllers.app.SlideShow;
import org.rcsb.lx.controllers.app.LigandExplorer;
import org.rcsb.pw.controllers.app.ProteinWorkshop;
import org.rcsb.sv.controllers.app.SimpleViewer;
public class Demo {
public static void main(String[] args){
//showSimpleViewer();
//showProteinWorkshop();
- // showLigandExplorer();
- showKiosk();
+ showLigandExplorer();
+ //showKiosk();
}
public static void showSimpleViewer(){
String[] args = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1STP.xml.gz","-unit_id","1","-standalone"};
final SimpleViewer app = new SimpleViewer(args);
app.initialize(true, true);
}
public static void showProteinWorkshop(){
// String[] pdbIds = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1CDG.xml.gz","-unit_id","1","-standalone"};
String[] pdbIds = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1CDG.xml.gz","-standalone"};
// String[] pdbIds = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1STP.xml.gz","-standalone"};
final ProteinWorkshop app = new ProteinWorkshop(pdbIds);
app.initialize(true, true);
}
public static void showLigandExplorer() {
System.out.println("Showing Ligand Explorer");
String[] args = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1STP.xml.gz","-unit_id","1","-standalone"};
// String[] args = new String[]{"-structure_url","http://www.rcsb.org:80/pdb/files/1HWK.xml.gz","-unit_id","1","-standalone"};
final LigandExplorer app = new LigandExplorer(args);
app.initialize(true);
}
public static void showKiosk() {
String[] pdbIds = new String[]{"-structure_id_list","4hhb,1cdg"};
SlideShow show = new SlideShow(pdbIds);
show.run();
}
}
| true | true | public static void main(String[] args){
//showSimpleViewer();
//showProteinWorkshop();
// showLigandExplorer();
showKiosk();
}
| public static void main(String[] args){
//showSimpleViewer();
//showProteinWorkshop();
showLigandExplorer();
//showKiosk();
}
|
diff --git a/bennu-core/src/myorg/domain/contents/Node.java b/bennu-core/src/myorg/domain/contents/Node.java
index 6c2fbd4a..a3fb753d 100644
--- a/bennu-core/src/myorg/domain/contents/Node.java
+++ b/bennu-core/src/myorg/domain/contents/Node.java
@@ -1,232 +1,234 @@
/*
* @(#)Node.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Bennu Web Application Infrastructure.
*
* The Bennu Web Application Infrastructure 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.*
*
* Bennu 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 Bennu. If not, see <http://www.gnu.org/licenses/>.
*
*/
package myorg.domain.contents;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import myorg.applicationTier.Authenticate.UserView;
import myorg.domain.MyOrg;
import myorg.domain.User;
import myorg.domain.VirtualHost;
import myorg.domain.groups.PersistentGroup;
import myorg.presentationTier.Context;
import myorg.presentationTier.actions.ContextBaseAction;
import pt.ist.fenixWebFramework.services.Service;
import pt.ist.fenixframework.pstm.AbstractDomainObject;
public abstract class Node extends Node_Base implements INode {
public Node() {
super();
setMyOrg(MyOrg.getInstance());
setOjbConcreteClass(getClass().getName());
}
public String getUrl() {
final StringBuilder stringBuilder = new StringBuilder();
appendUrlPrefix(stringBuilder);
stringBuilder.append("&");
stringBuilder.append(ContextBaseAction.CONTEXT_PATH);
stringBuilder.append('=');
appendNodePath(stringBuilder);
return stringBuilder.toString();
}
protected void appendNodePath(final StringBuilder stringBuilder) {
final Node parentNode = getParentNode();
if (parentNode != null) {
parentNode.appendNodePath(stringBuilder);
stringBuilder.append(Context.PATH_PART_SEPERATOR);
}
stringBuilder.append(getExternalId());
}
public String getContextPath() {
final StringBuilder stringBuilder = new StringBuilder();
appendNodePath(stringBuilder);
return stringBuilder.toString();
}
protected abstract void appendUrlPrefix(final StringBuilder stringBuilder);
@Override
public Set<INode> getChildren() {
return (Set) getChildNodesSet();
}
@Override
public Integer getOrder() {
return getNodeOrder();
}
@Override
public INode getParent() {
return getParentNode();
}
public void init(final VirtualHost virtualHost, final Node parentNode, final Integer order) {
if (parentNode == null) {
setNodeOrder(virtualHost.getTopLevelNodesSet(), order);
setVirtualHost(virtualHost);
} else {
setNodeOrder(parentNode.getChildNodesSet(), order);
setParentNode(parentNode);
}
}
private void setNodeOrder(final Set<Node> siblings, final Integer order) {
if (order == null) {
setNodeOrder(siblings.size() + 1);
} else {
final int newNodeOrder = order.intValue();
for (final Node node : siblings) {
final int currentNodeOrder = node.getNodeOrder().intValue();
if (currentNodeOrder >= newNodeOrder) {
node.setNodeOrder(Integer.valueOf(currentNodeOrder + 1));
}
}
}
}
public static Node getFirstTopLevelNode() {
final Set<Node> nodes = VirtualHost.getVirtualHostForThread().getTopLevelNodesSet();
return nodes.isEmpty() ? null : Collections.min(nodes, COMPARATOR_BY_ORDER);
}
public static Node getFirstAvailableTopLevelNode() {
final Set<Node> nodes = VirtualHost.getVirtualHostForThread().getOrderedTopLevelNodes();
for (final Node node : nodes) {
if (node.isAccessible()) {
return node;
}
}
return null;
}
protected void descNodeOrders(final Set<Node> nodes) {
final int threshold = getNodeOrder().intValue();
for (final Node node : nodes) {
final int currentNodeOrder = node.getNodeOrder().intValue();
if (currentNodeOrder >= threshold) {
node.setNodeOrder(Integer.valueOf(currentNodeOrder - 1));
}
}
}
public static SortedSet<Node> getOrderedTopLevelNodes() {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
return virtualHost.getOrderedTopLevelNodes();
}
public Set<INode> getOrderedChildren() {
final Set<INode> nodes = new TreeSet<INode>(COMPARATOR_BY_ORDER);
nodes.addAll(getChildren());
return nodes;
}
@Override
public String asString() {
return getExternalId();
}
public static INode fromString(final String string) {
Node node = AbstractDomainObject.fromExternalId(string);
return node;
}
@Service
public void deleteService() {
delete();
}
public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
+ for (; !getNodeMapping().isEmpty(); getNodeMapping().get(0).delete())
+ ;
deleteDomainObject();
}
@Service
public static void reorderTopLevelNodes(final List<Node> nodes) throws Error {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
for (final Node node : virtualHost.getTopLevelNodesSet()) {
if (!nodes.contains(node)) {
throwError();
}
}
int i = 0;
for (final Node node : nodes) {
if (!virtualHost.hasTopLevelNodes(node)) {
throwError();
}
node.setNodeOrder(Integer.valueOf(i++));
}
}
@Service
public void reorderNodes(final List<Node> nodes) {
for (final Node node : getChildNodesSet()) {
if (!nodes.contains(node)) {
throwError();
}
}
int i = 0;
for (final Node node : nodes) {
if (!hasChildNodes(node)) {
throwError();
}
node.setNodeOrder(Integer.valueOf(i++));
}
}
private static void throwError() {
throw new Error("Nodes changed!");
}
public boolean isAccessible() {
final PersistentGroup persistentGroup = getAccessibilityGroup();
final User user = UserView.getCurrentUser();
return persistentGroup != null && persistentGroup.isMember(user);
}
}
| true | true | public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
deleteDomainObject();
}
| public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
for (; !getNodeMapping().isEmpty(); getNodeMapping().get(0).delete())
;
deleteDomainObject();
}
|
diff --git a/IBFbNursery/src/ibfb/nursery/actions/QuickNurseryCreationAction.java b/IBFbNursery/src/ibfb/nursery/actions/QuickNurseryCreationAction.java
index d78707f..37c3019 100644
--- a/IBFbNursery/src/ibfb/nursery/actions/QuickNurseryCreationAction.java
+++ b/IBFbNursery/src/ibfb/nursery/actions/QuickNurseryCreationAction.java
@@ -1,150 +1,152 @@
package ibfb.nursery.actions;
import ibfb.domain.core.SelectedStudy;
import ibfb.domain.core.Study;
import ibfb.nursery.core.NurseryEditorTopComponent;
import ibfb.nursery.quickcreation.JDQuickCreation;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.HelpCtx;
import org.openide.util.Mutex;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.openide.util.actions.SystemAction;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
@ActionID(category = "File",
id = "ibfb.nursery.actions.QuickCreationAction")
@ActionRegistration(iconBase = "ibfb/nursery/images/quickNursery16.png",
displayName = "#CTL_QuickCreationAction")
@ActionReferences({
@ActionReference(path = "Menu/Study", position = 1243),
@ActionReference(path = "Toolbars/File", position = -312)
})
public final class QuickNurseryCreationAction extends SystemAction implements ActionListener {
private final Study context;
private JDQuickCreation quick;
private ResourceBundle bundle = NbBundle.getBundle(QuickNurseryCreationAction.class);
public QuickNurseryCreationAction() {
putValue(NAME, bundle.getString("QuickNurseryCreationAction.name"));
setEnabled(Boolean.TRUE);
this.context = null;
}
public QuickNurseryCreationAction(Study context) {
this.context = context;
setEnabled(Boolean.TRUE);
}
@Override
public void actionPerformed(ActionEvent ev) {
changeCursorWaitStatus(true);
quick=new JDQuickCreation(null, true);
TopComponent background = WindowManager.getDefault().findTopComponent("BackgroundWindowTopComponent");
if (background.isOpened()) {
background.close();
}
if (existeNursery("Nursery - "+SelectedStudy.selected.getStudy())) {
int opcion = JOptionPane.showConfirmDialog(null, bundle.getString("QuickNurseryCreationAction.alreadyExists"), bundle.getString("QuickNurseryCreationAction.caution"), JOptionPane.YES_NO_OPTION);
if (opcion == 0) {
NurseryEditorTopComponent nurseryEditor = null;
ArrayList<TopComponent> opened = new ArrayList<TopComponent>(WindowManager.getDefault().getRegistry().getOpened());
for (TopComponent t : opened) {
- if (t.getName().equals(SelectedStudy.selected.getStudy())) {
+ String studyname = t.getName();
+ String selectedStudyName = "Nursery - "+SelectedStudy.selected.getStudy();
+ if (studyname.equals(selectedStudyName)) {
nurseryEditor = (NurseryEditorTopComponent) t;
nurseryEditor.close();
}
}
nurseryEditor.setStudy(SelectedStudy.selected);
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
} else {
NurseryEditorTopComponent nurseryEditor = new NurseryEditorTopComponent();
nurseryEditor.setStudy(SelectedStudy.selected);
nurseryEditor.setName("Nursery - "+SelectedStudy.selected.getStudy());
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
changeCursorWaitStatus(false);
}
public boolean existeNursery(String nursery) {
boolean existe = false;
try {
ArrayList<TopComponent> opened = new ArrayList<TopComponent>(WindowManager.getDefault().getRegistry().getOpened());
for (TopComponent t : opened) {
if (t.getName().equals(nursery)) {
existe = true;
}
}
} catch (NullPointerException ex) {
existe = false;
}
return existe;
}
private static void changeCursorWaitStatus(final boolean isWaiting) {
Mutex.EVENT.writeAccess(new Runnable() {
@Override
public void run() {
try {
JFrame mainFrame =
(JFrame) WindowManager.getDefault().getMainWindow();
Component glassPane = mainFrame.getGlassPane();
if (isWaiting) {
glassPane.setVisible(true);
glassPane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
} else {
glassPane.setVisible(false);
glassPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
} catch (Exception e) {
}
}
});
}
@Override
public String getName() {
return "Quick Nursery Creation";
}
@Override
public HelpCtx getHelpCtx() {
return null;
}
}
| true | true | public void actionPerformed(ActionEvent ev) {
changeCursorWaitStatus(true);
quick=new JDQuickCreation(null, true);
TopComponent background = WindowManager.getDefault().findTopComponent("BackgroundWindowTopComponent");
if (background.isOpened()) {
background.close();
}
if (existeNursery("Nursery - "+SelectedStudy.selected.getStudy())) {
int opcion = JOptionPane.showConfirmDialog(null, bundle.getString("QuickNurseryCreationAction.alreadyExists"), bundle.getString("QuickNurseryCreationAction.caution"), JOptionPane.YES_NO_OPTION);
if (opcion == 0) {
NurseryEditorTopComponent nurseryEditor = null;
ArrayList<TopComponent> opened = new ArrayList<TopComponent>(WindowManager.getDefault().getRegistry().getOpened());
for (TopComponent t : opened) {
if (t.getName().equals(SelectedStudy.selected.getStudy())) {
nurseryEditor = (NurseryEditorTopComponent) t;
nurseryEditor.close();
}
}
nurseryEditor.setStudy(SelectedStudy.selected);
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
} else {
NurseryEditorTopComponent nurseryEditor = new NurseryEditorTopComponent();
nurseryEditor.setStudy(SelectedStudy.selected);
nurseryEditor.setName("Nursery - "+SelectedStudy.selected.getStudy());
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
changeCursorWaitStatus(false);
}
| public void actionPerformed(ActionEvent ev) {
changeCursorWaitStatus(true);
quick=new JDQuickCreation(null, true);
TopComponent background = WindowManager.getDefault().findTopComponent("BackgroundWindowTopComponent");
if (background.isOpened()) {
background.close();
}
if (existeNursery("Nursery - "+SelectedStudy.selected.getStudy())) {
int opcion = JOptionPane.showConfirmDialog(null, bundle.getString("QuickNurseryCreationAction.alreadyExists"), bundle.getString("QuickNurseryCreationAction.caution"), JOptionPane.YES_NO_OPTION);
if (opcion == 0) {
NurseryEditorTopComponent nurseryEditor = null;
ArrayList<TopComponent> opened = new ArrayList<TopComponent>(WindowManager.getDefault().getRegistry().getOpened());
for (TopComponent t : opened) {
String studyname = t.getName();
String selectedStudyName = "Nursery - "+SelectedStudy.selected.getStudy();
if (studyname.equals(selectedStudyName)) {
nurseryEditor = (NurseryEditorTopComponent) t;
nurseryEditor.close();
}
}
nurseryEditor.setStudy(SelectedStudy.selected);
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
} else {
NurseryEditorTopComponent nurseryEditor = new NurseryEditorTopComponent();
nurseryEditor.setStudy(SelectedStudy.selected);
nurseryEditor.setName("Nursery - "+SelectedStudy.selected.getStudy());
quick.setNurseryWindow(nurseryEditor);
quick.cleanFields();
quick.setLocationRelativeTo(null);
quick.setVisible(true);
}
changeCursorWaitStatus(false);
}
|
diff --git a/loci/formats/in/BaseTiffReader.java b/loci/formats/in/BaseTiffReader.java
index b342973ff..78d6110f5 100644
--- a/loci/formats/in/BaseTiffReader.java
+++ b/loci/formats/in/BaseTiffReader.java
@@ -1,847 +1,850 @@
//
// BaseTiffReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.text.*;
import java.util.*;
import loci.formats.*;
/**
* BaseTiffReader is the superclass for file format readers compatible with
* or derived from the TIFF 6.0 file format.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/BaseTiffReader.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/BaseTiffReader.java">SVN</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
* @author Melissa Linkert linkert at wisc.edu
*/
public abstract class BaseTiffReader extends FormatReader {
// -- Fields --
/** List of IFDs for the current TIFF. */
protected Hashtable[] ifds;
// -- Constructors --
/** Constructs a new BaseTiffReader. */
public BaseTiffReader(String name, String suffix) { super(name, suffix); }
/** Constructs a new BaseTiffReader. */
public BaseTiffReader(String name, String[] suffixes) {
super(name, suffixes);
}
// -- BaseTiffReader API methods --
/** Gets the dimensions of the given (possibly multi-page) TIFF file. */
public int[] getTiffDimensions() throws FormatException, IOException {
if (ifds == null || ifds.length == 0) return null;
return new int[] {
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_WIDTH, false, -1),
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_LENGTH, false, -1),
core.imageCount[0]
};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return TiffTools.isValidHeader(block);
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
int[] bits = TiffTools.getBitsPerSample(ifds[0]);
if (bits[0] <= 8) {
int[] colorMap =
(int[]) TiffTools.getIFDValue(ifds[0], TiffTools.COLOR_MAP);
if (colorMap == null) return null;
byte[][] table = new byte[3][colorMap.length / 3];
int next = 0;
for (int j=0; j<table.length; j++) {
for (int i=0; i<table[0].length; i++) {
table[j][i] = (byte) ((colorMap[next++] >> 8) & 0xff);
}
}
return table;
}
return null;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
int[] bits = TiffTools.getBitsPerSample(ifds[0]);
if (bits[0] <= 16 && bits[0] > 8) {
int[] colorMap =
(int[]) TiffTools.getIFDValue(ifds[0], TiffTools.COLOR_MAP);
if (colorMap == null || colorMap.length < 65536 * 3) return null;
short[][] table = new short[3][colorMap.length / 3];
int next = 0;
for (int i=0; i<table.length; i++) {
for (int j=0; j<table[0].length; j++) {
if (core.littleEndian[0]) {
table[i][j] = (short) (colorMap[next++] & 0xffff);
}
else {
int n = colorMap[next++];
table[i][j] =
(short) (((n & 0xff0000) >> 8) | ((n & 0xff000000) >> 24));
}
}
}
return table;
}
return null;
}
/* @see loci.formats.IFormatReader#getMetadataValue(String) */
public Object getMetadataValue(String field) {
FormatTools.assertId(currentId, true, 1);
return getMeta(field);
}
/* @see loci.formats.FormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length);
TiffTools.getSamples(ifds[no], in, buf);
return swapIfRequired(buf);
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
ifds = null;
}
// -- Internal BaseTiffReader API methods --
/** Populates the metadata hashtable and metadata store. */
protected void initMetadata() throws FormatException, IOException {
initStandardMetadata();
initMetadataStore();
}
/**
* Parses standard metadata.
*
* NOTE: Absolutely <b>no</b> calls to the metadata store should be made in
* this method or methods that override this method. Data <b>will</b> be
* overwritten if you do so.
*/
protected void initStandardMetadata() throws FormatException, IOException {
Hashtable ifd = ifds[0];
put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH);
put("ImageLength", ifd, TiffTools.IMAGE_LENGTH);
put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE);
int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION);
String compression = null;
switch (comp) {
case TiffTools.UNCOMPRESSED:
compression = "None";
break;
case TiffTools.CCITT_1D:
compression = "CCITT Group 3 1-Dimensional Modified Huffman";
break;
case TiffTools.GROUP_3_FAX:
compression = "CCITT T.4 bilevel encoding";
break;
case TiffTools.GROUP_4_FAX:
compression = "CCITT T.6 bilevel encoding";
break;
case TiffTools.LZW:
compression = "LZW";
break;
case TiffTools.JPEG:
compression = "JPEG";
break;
case TiffTools.PACK_BITS:
compression = "PackBits";
break;
}
put("Compression", compression);
int photo = TiffTools.getIFDIntValue(ifd,
TiffTools.PHOTOMETRIC_INTERPRETATION);
String photoInterp = null;
String metaDataPhotoInterp = null;
switch (photo) {
case TiffTools.WHITE_IS_ZERO:
photoInterp = "WhiteIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.BLACK_IS_ZERO:
photoInterp = "BlackIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.RGB:
photoInterp = "RGB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.RGB_PALETTE:
photoInterp = "Palette";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.TRANSPARENCY_MASK:
photoInterp = "Transparency Mask";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CMYK:
photoInterp = "CMYK";
metaDataPhotoInterp = "CMYK";
break;
case TiffTools.Y_CB_CR:
photoInterp = "YCbCr";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CIE_LAB:
photoInterp = "CIELAB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CFA_ARRAY:
photoInterp = "Color Filter Array";
metaDataPhotoInterp = "RGB";
break;
}
put("PhotometricInterpretation", photoInterp);
put("MetaDataPhotometricInterpretation", metaDataPhotoInterp);
putInt("CellWidth", ifd, TiffTools.CELL_WIDTH);
putInt("CellLength", ifd, TiffTools.CELL_LENGTH);
int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION);
// adjust the width and height if necessary
if (or == 8) {
put("ImageWidth", ifd, TiffTools.IMAGE_LENGTH);
put("ImageLength", ifd, TiffTools.IMAGE_WIDTH);
}
String orientation = null;
// there is no case 0
switch (or) {
case 1:
orientation = "1st row -> top; 1st column -> left";
break;
case 2:
orientation = "1st row -> top; 1st column -> right";
break;
case 3:
orientation = "1st row -> bottom; 1st column -> right";
break;
case 4:
orientation = "1st row -> bottom; 1st column -> left";
break;
case 5:
orientation = "1st row -> left; 1st column -> top";
break;
case 6:
orientation = "1st row -> right; 1st column -> top";
break;
case 7:
orientation = "1st row -> right; 1st column -> bottom";
break;
case 8:
orientation = "1st row -> left; 1st column -> bottom";
break;
}
put("Orientation", orientation);
putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL);
put("Software", ifd, TiffTools.SOFTWARE);
put("Instrument Make", ifd, TiffTools.MAKE);
put("Instrument Model", ifd, TiffTools.MODEL);
put("Document Name", ifd, TiffTools.DOCUMENT_NAME);
put("DateTime", ifd, TiffTools.DATE_TIME);
put("Artist", ifd, TiffTools.ARTIST);
put("HostComputer", ifd, TiffTools.HOST_COMPUTER);
put("Copyright", ifd, TiffTools.COPYRIGHT);
put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE);
int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING);
String threshholding = null;
switch (thresh) {
case 1:
threshholding = "No dithering or halftoning";
break;
case 2:
threshholding = "Ordered dithering or halftoning";
break;
case 3:
threshholding = "Randomized error diffusion";
break;
}
put("Threshholding", threshholding);
int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER);
String fillOrder = null;
switch (fill) {
case 1:
fillOrder = "Pixels with lower column values are stored " +
"in the higher order bits of a byte";
break;
case 2:
fillOrder = "Pixels with lower column values are stored " +
"in the lower order bits of a byte";
break;
}
put("FillOrder", fillOrder);
putInt("Make", ifd, TiffTools.MAKE);
putInt("Model", ifd, TiffTools.MODEL);
putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE);
putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE);
putInt("XResolution", ifd, TiffTools.X_RESOLUTION);
putInt("YResolution", ifd, TiffTools.Y_RESOLUTION);
int planar = TiffTools.getIFDIntValue(ifd,
TiffTools.PLANAR_CONFIGURATION);
String planarConfig = null;
switch (planar) {
case 1:
planarConfig = "Chunky";
break;
case 2:
planarConfig = "Planar";
break;
}
put("PlanarConfiguration", planarConfig);
putInt("XPosition", ifd, TiffTools.X_POSITION);
putInt("YPosition", ifd, TiffTools.Y_POSITION);
putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS);
putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS);
putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT);
putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE);
putInt("T4Options", ifd, TiffTools.T4_OPTIONS);
putInt("T6Options", ifd, TiffTools.T6_OPTIONS);
int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT);
String resUnit = null;
switch (res) {
case 1:
resUnit = "None";
break;
case 2:
resUnit = "Inch";
break;
case 3:
resUnit = "Centimeter";
break;
}
put("ResolutionUnit", resUnit);
putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER);
putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION);
int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR);
String predictor = null;
switch (predict) {
case 1:
predictor = "No prediction scheme";
break;
case 2:
predictor = "Horizontal differencing";
break;
}
put("Predictor", predictor);
putInt("WhitePoint", ifd, TiffTools.WHITE_POINT);
putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES);
putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS);
putInt("TileWidth", ifd, TiffTools.TILE_WIDTH);
putInt("TileLength", ifd, TiffTools.TILE_LENGTH);
putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS);
putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS);
int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET);
String inkSet = null;
switch (ink) {
case 1:
inkSet = "CMYK";
break;
case 2:
inkSet = "Other";
break;
}
put("InkSet", inkSet);
putInt("InkNames", ifd, TiffTools.INK_NAMES);
putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS);
putInt("DotRange", ifd, TiffTools.DOT_RANGE);
put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER);
putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES);
int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT);
String sampleFormat = null;
switch (fmt) {
case 1:
sampleFormat = "unsigned integer";
break;
case 2:
sampleFormat = "two's complement signed integer";
break;
case 3:
sampleFormat = "IEEE floating point";
break;
case 4:
sampleFormat = "undefined";
break;
}
put("SampleFormat", sampleFormat);
putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE);
putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE);
putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE);
int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC);
String jpegProc = null;
switch (jpeg) {
case 1:
jpegProc = "baseline sequential process";
break;
case 14:
jpegProc = "lossless process with Huffman coding";
break;
}
put("JPEGProc", jpegProc);
putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT);
putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL);
putInt("JPEGLosslessPredictors",
ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS);
putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS);
putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES);
putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES);
putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES);
putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS);
int ycbcr = TiffTools.getIFDIntValue(ifd,
TiffTools.Y_CB_CR_SUB_SAMPLING);
String subSampling = null;
switch (ycbcr) {
case 1:
subSampling = "chroma image dimensions = luma image dimensions";
break;
case 2:
subSampling = "chroma image dimensions are " +
"half the luma image dimensions";
break;
case 4:
subSampling = "chroma image dimensions are " +
"1/4 the luma image dimensions";
break;
}
put("YCbCrSubSampling", subSampling);
putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING);
putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE);
// bits per sample and number of channels
Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE);
int bps = -1, numC = 3;
if (bpsObj instanceof int[]) {
int[] q = (int[]) bpsObj;
bps = q[0];
numC = q.length;
}
else if (bpsObj instanceof Number) {
bps = ((Number) bpsObj).intValue();
numC = 1;
}
// numC isn't set properly if we have an indexed color image, so we need
// to reset it here
int p = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION);
if (p == TiffTools.RGB_PALETTE || p == TiffTools.CFA_ARRAY) {
numC = 3;
bps *= 3;
}
put("BitsPerSample", bps);
put("NumberOfChannels", numC);
// TIFF comment
String comment = null;
Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
if (o instanceof String) comment = (String) o;
else if (o instanceof String[]) {
String[] s = (String[]) o;
if (s.length > 0) comment = s[0];
}
else if (o != null) comment = o.toString();
if (comment != null) {
// sanitize comment
comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF
comment = comment.replaceAll("\r", "\n"); // CR to LF
put("Comment", comment);
}
int samples = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLES_PER_PIXEL, false, 1);
core.rgb[0] = samples > 1 || p == TiffTools.RGB;
core.interleaved[0] = false;
core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]);
core.sizeX[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_WIDTH, false, 0);
core.sizeY[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_LENGTH, false, 0);
core.sizeZ[0] = 1;
core.sizeC[0] = core.rgb[0] ? samples : 1;
core.sizeT[0] = ifds.length;
core.metadataComplete[0] = true;
core.indexed[0] = p == TiffTools.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
if (core.sizeC[0] == 1 && !core.indexed[0]) core.rgb[0] = false;
core.falseColor[0] = false;
int bitFormat = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLE_FORMAT);
while (bps % 8 != 0) bps++;
if (bps == 24 || bps == 48) bps /= 3;
- if (bitFormat == 3) core.pixelType[0] = FormatTools.FLOAT;
+ if (bitFormat == 3) {
+ core.pixelType[0] = FormatTools.FLOAT;
+ core.littleEndian[0] = true;
+ }
else if (bitFormat == 2) {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.INT16;
break;
case 32:
core.pixelType[0] = FormatTools.INT32;
break;
default:
core.pixelType[0] = FormatTools.INT8;
}
}
else {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.UINT16;
break;
case 32:
core.pixelType[0] = FormatTools.UINT32;
break;
default:
core.pixelType[0] = FormatTools.UINT8;
}
}
core.currentOrder[0] = "XYCZT";
}
/**
* Populates the metadata store using the data parsed in
* {@link #initStandardMetadata()} along with some further parsing done in
* the method itself.
*
* All calls to the active <code>MetadataStore</code> should be made in this
* method and <b>only</b> in this method. This is especially important for
* sub-classes that override the getters for pixel set array size, etc.
*/
protected void initMetadataStore() {
Hashtable ifd = ifds[0];
try {
// the metadata store we're working with
MetadataStore store = getMetadataStore();
// set the pixel values in the metadata store
FormatTools.populatePixels(store, this);
// populate Experimenter element
String artist = (String) TiffTools.getIFDValue(ifd, TiffTools.ARTIST);
if (artist != null) {
String firstName = null, lastName = null;
int ndx = artist.indexOf(" ");
if (ndx < 0) lastName = artist;
else {
firstName = artist.substring(0, ndx);
lastName = artist.substring(ndx + 1);
}
String email = (String)
TiffTools.getIFDValue(ifd, TiffTools.HOST_COMPUTER);
store.setExperimenter(firstName, lastName, email,
null, null, null, null);
}
// format the creation date to ISO 8061
String creationDate = getImageCreationDate();
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
Date date = parse.parse(creationDate, new ParsePosition(0));
creationDate = sdf.format(date);
}
catch (NullPointerException e) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat parse =
new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
Date date = parse.parse(creationDate, new ParsePosition(0));
creationDate = sdf.format(date);
}
catch (NullPointerException exc) {
if (debug) trace(exc);
creationDate = null;
}
}
// populate Image element
store.setImage(null, creationDate, getImageDescription(), null);
// populate Logical Channel elements
for (int i=0; i<getSizeC(); i++) {
try {
setLogicalChannel(i);
}
catch (FormatException exc) {
if (debug) trace(exc);
}
catch (IOException exc) {
if (debug) trace(exc);
}
}
// set the X and Y pixel dimensions
int resolutionUnit = TiffTools.getIFDIntValue(ifd,
TiffTools.RESOLUTION_UNIT);
TiffRational xResolution = TiffTools.getIFDRationalValue(ifd,
TiffTools.X_RESOLUTION, false);
TiffRational yResolution = TiffTools.getIFDRationalValue(ifd,
TiffTools.Y_RESOLUTION, false);
float pixX = xResolution == null ? 0f : xResolution.floatValue();
float pixY = yResolution == null ? 0f : yResolution.floatValue();
switch (resolutionUnit) {
case 2:
// resolution is expressed in pixels per inch
pixX *= 0.0254;
pixY *= 0.0254;
break;
case 3:
// resolution is expressed in pixels per centimeter
pixX /= 100;
pixY /= 100;
break;
}
store.setDimensions(new Float(pixX), new Float(pixY), null,
null, null, null);
// populate StageLabel element
Object x = TiffTools.getIFDValue(ifd, TiffTools.X_POSITION);
Object y = TiffTools.getIFDValue(ifd, TiffTools.Y_POSITION);
Float stageX;
Float stageY;
if (x instanceof TiffRational) {
stageX = x == null ? null : new Float(((TiffRational) x).floatValue());
stageY = y == null ? null : new Float(((TiffRational) y).floatValue());
}
else {
stageX = x == null ? null : new Float((String) x);
stageY = y == null ? null : new Float((String) y);
}
if (stageX != null || stageY != null) {
store.setStageLabel(null, stageX, stageY, null, null);
}
// populate Instrument element
String model = (String) TiffTools.getIFDValue(ifd, TiffTools.MODEL);
String serialNumber = (String)
TiffTools.getIFDValue(ifd, TiffTools.MAKE);
store.setInstrument(null, model, serialNumber, null, null);
}
catch (FormatException exc) { trace(exc); }
}
/**
* Retrieves the image name from the TIFF.
* @return the image name.
*/
protected String getImageName() { return currentId; }
/**
* Retrieves the image creation date.
* @return the image creation date.
*/
protected String getImageCreationDate() {
Object o = TiffTools.getIFDValue(ifds[0], TiffTools.DATE_TIME);
if (o instanceof String) return (String) o;
if (o instanceof String[]) return ((String[]) o)[0];
return null;
}
/**
* Retrieves the image description.
* @return the image description.
*/
protected String getImageDescription() {
return (String) getMeta("Comment");
}
/**
* Examines a byte array to see if it needs to be byte swapped and modifies
* the byte array directly.
* @param byteArray The byte array to check and modify if required.
* @return the <i>byteArray</i> either swapped or not for convenience.
* @throws IOException if there is an error read from the file.
* @throws FormatException if there is an error during metadata parsing.
*/
protected byte[] swapIfRequired(byte[] byteArray)
throws FormatException, IOException
{
int bitsPerSample = TiffTools.getBitsPerSample(ifds[0])[0];
// We've got nothing to do if the samples are only 8-bits wide or if they
// are floating point.
if (bitsPerSample == 8 || bitsPerSample == 32) return byteArray;
if (isLittleEndian()) {
if (bitsPerSample == 16) { // short
ShortBuffer buf = ByteBuffer.wrap(byteArray).asShortBuffer();
for (int i = 0; i < (byteArray.length / 2); i++) {
buf.put(i, DataTools.swap(buf.get(i)));
}
}
else {
throw new FormatException(
"Unsupported sample bit width: '" + bitsPerSample + "'");
}
}
// We've got a big-endian file with a big-endian byte array.
return byteArray;
}
// -- Internal FormatReader API methods - metadata convenience --
protected void put(String key, Object value) {
if (value == null) return;
if (value instanceof String) value = ((String) value).trim();
addMeta(key, value);
}
protected void put(String key, int value) {
if (value == -1) return; // indicates missing value
addMeta(key, new Integer(value));
}
protected void put(String key, boolean value) {
put(key, new Boolean(value));
}
protected void put(String key, byte value) { put(key, new Byte(value)); }
protected void put(String key, char value) { put(key, new Character(value)); }
protected void put(String key, double value) { put(key, new Double(value)); }
protected void put(String key, float value) { put(key, new Float(value)); }
protected void put(String key, long value) { put(key, new Long(value)); }
protected void put(String key, short value) { put(key, new Short(value)); }
protected void put(String key, Hashtable ifd, int tag) {
put(key, TiffTools.getIFDValue(ifd, tag));
}
protected void putInt(String key, Hashtable ifd, int tag) {
put(key, TiffTools.getIFDIntValue(ifd, tag));
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("BaseTiffReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
in.order(in.readShort() == 0x4949);
status("Reading IFDs");
ifds = TiffTools.getIFDs(in);
if (ifds == null) throw new FormatException("No IFDs found");
status("Populating metadata");
core.imageCount[0] = ifds.length;
initMetadata();
}
// -- Helper methods --
/**
* Sets the logical channel in the metadata store.
* @param i the logical channel number.
* @throws FormatException if there is an error parsing metadata.
* @throws IOException if there is an error reading the file.
*/
private void setLogicalChannel(int i) throws FormatException, IOException {
getMetadataStore().setLogicalChannel(i, getChannelName(i), null, null, null,
null, null, null, null, null, null, null, null,
getPhotometricInterpretation(i), getMode(i), null, null, null, null, null,
getEmWave(i), getExWave(i), null, getNdFilter(i), null);
}
private String getChannelName(int i) { return null; }
private Float getNdFilter(int i) { return null; }
private Integer getEmWave(int i) { return null; }
private Integer getExWave(int i) { return null; }
private String getPhotometricInterpretation(int i)
throws FormatException, IOException
{
return (String) getMetadataValue("metaDataPhotometricInterpretation");
}
private String getMode(int i) { return null; }
}
| true | true | protected void initStandardMetadata() throws FormatException, IOException {
Hashtable ifd = ifds[0];
put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH);
put("ImageLength", ifd, TiffTools.IMAGE_LENGTH);
put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE);
int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION);
String compression = null;
switch (comp) {
case TiffTools.UNCOMPRESSED:
compression = "None";
break;
case TiffTools.CCITT_1D:
compression = "CCITT Group 3 1-Dimensional Modified Huffman";
break;
case TiffTools.GROUP_3_FAX:
compression = "CCITT T.4 bilevel encoding";
break;
case TiffTools.GROUP_4_FAX:
compression = "CCITT T.6 bilevel encoding";
break;
case TiffTools.LZW:
compression = "LZW";
break;
case TiffTools.JPEG:
compression = "JPEG";
break;
case TiffTools.PACK_BITS:
compression = "PackBits";
break;
}
put("Compression", compression);
int photo = TiffTools.getIFDIntValue(ifd,
TiffTools.PHOTOMETRIC_INTERPRETATION);
String photoInterp = null;
String metaDataPhotoInterp = null;
switch (photo) {
case TiffTools.WHITE_IS_ZERO:
photoInterp = "WhiteIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.BLACK_IS_ZERO:
photoInterp = "BlackIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.RGB:
photoInterp = "RGB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.RGB_PALETTE:
photoInterp = "Palette";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.TRANSPARENCY_MASK:
photoInterp = "Transparency Mask";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CMYK:
photoInterp = "CMYK";
metaDataPhotoInterp = "CMYK";
break;
case TiffTools.Y_CB_CR:
photoInterp = "YCbCr";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CIE_LAB:
photoInterp = "CIELAB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CFA_ARRAY:
photoInterp = "Color Filter Array";
metaDataPhotoInterp = "RGB";
break;
}
put("PhotometricInterpretation", photoInterp);
put("MetaDataPhotometricInterpretation", metaDataPhotoInterp);
putInt("CellWidth", ifd, TiffTools.CELL_WIDTH);
putInt("CellLength", ifd, TiffTools.CELL_LENGTH);
int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION);
// adjust the width and height if necessary
if (or == 8) {
put("ImageWidth", ifd, TiffTools.IMAGE_LENGTH);
put("ImageLength", ifd, TiffTools.IMAGE_WIDTH);
}
String orientation = null;
// there is no case 0
switch (or) {
case 1:
orientation = "1st row -> top; 1st column -> left";
break;
case 2:
orientation = "1st row -> top; 1st column -> right";
break;
case 3:
orientation = "1st row -> bottom; 1st column -> right";
break;
case 4:
orientation = "1st row -> bottom; 1st column -> left";
break;
case 5:
orientation = "1st row -> left; 1st column -> top";
break;
case 6:
orientation = "1st row -> right; 1st column -> top";
break;
case 7:
orientation = "1st row -> right; 1st column -> bottom";
break;
case 8:
orientation = "1st row -> left; 1st column -> bottom";
break;
}
put("Orientation", orientation);
putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL);
put("Software", ifd, TiffTools.SOFTWARE);
put("Instrument Make", ifd, TiffTools.MAKE);
put("Instrument Model", ifd, TiffTools.MODEL);
put("Document Name", ifd, TiffTools.DOCUMENT_NAME);
put("DateTime", ifd, TiffTools.DATE_TIME);
put("Artist", ifd, TiffTools.ARTIST);
put("HostComputer", ifd, TiffTools.HOST_COMPUTER);
put("Copyright", ifd, TiffTools.COPYRIGHT);
put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE);
int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING);
String threshholding = null;
switch (thresh) {
case 1:
threshholding = "No dithering or halftoning";
break;
case 2:
threshholding = "Ordered dithering or halftoning";
break;
case 3:
threshholding = "Randomized error diffusion";
break;
}
put("Threshholding", threshholding);
int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER);
String fillOrder = null;
switch (fill) {
case 1:
fillOrder = "Pixels with lower column values are stored " +
"in the higher order bits of a byte";
break;
case 2:
fillOrder = "Pixels with lower column values are stored " +
"in the lower order bits of a byte";
break;
}
put("FillOrder", fillOrder);
putInt("Make", ifd, TiffTools.MAKE);
putInt("Model", ifd, TiffTools.MODEL);
putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE);
putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE);
putInt("XResolution", ifd, TiffTools.X_RESOLUTION);
putInt("YResolution", ifd, TiffTools.Y_RESOLUTION);
int planar = TiffTools.getIFDIntValue(ifd,
TiffTools.PLANAR_CONFIGURATION);
String planarConfig = null;
switch (planar) {
case 1:
planarConfig = "Chunky";
break;
case 2:
planarConfig = "Planar";
break;
}
put("PlanarConfiguration", planarConfig);
putInt("XPosition", ifd, TiffTools.X_POSITION);
putInt("YPosition", ifd, TiffTools.Y_POSITION);
putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS);
putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS);
putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT);
putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE);
putInt("T4Options", ifd, TiffTools.T4_OPTIONS);
putInt("T6Options", ifd, TiffTools.T6_OPTIONS);
int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT);
String resUnit = null;
switch (res) {
case 1:
resUnit = "None";
break;
case 2:
resUnit = "Inch";
break;
case 3:
resUnit = "Centimeter";
break;
}
put("ResolutionUnit", resUnit);
putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER);
putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION);
int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR);
String predictor = null;
switch (predict) {
case 1:
predictor = "No prediction scheme";
break;
case 2:
predictor = "Horizontal differencing";
break;
}
put("Predictor", predictor);
putInt("WhitePoint", ifd, TiffTools.WHITE_POINT);
putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES);
putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS);
putInt("TileWidth", ifd, TiffTools.TILE_WIDTH);
putInt("TileLength", ifd, TiffTools.TILE_LENGTH);
putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS);
putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS);
int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET);
String inkSet = null;
switch (ink) {
case 1:
inkSet = "CMYK";
break;
case 2:
inkSet = "Other";
break;
}
put("InkSet", inkSet);
putInt("InkNames", ifd, TiffTools.INK_NAMES);
putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS);
putInt("DotRange", ifd, TiffTools.DOT_RANGE);
put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER);
putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES);
int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT);
String sampleFormat = null;
switch (fmt) {
case 1:
sampleFormat = "unsigned integer";
break;
case 2:
sampleFormat = "two's complement signed integer";
break;
case 3:
sampleFormat = "IEEE floating point";
break;
case 4:
sampleFormat = "undefined";
break;
}
put("SampleFormat", sampleFormat);
putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE);
putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE);
putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE);
int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC);
String jpegProc = null;
switch (jpeg) {
case 1:
jpegProc = "baseline sequential process";
break;
case 14:
jpegProc = "lossless process with Huffman coding";
break;
}
put("JPEGProc", jpegProc);
putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT);
putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL);
putInt("JPEGLosslessPredictors",
ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS);
putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS);
putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES);
putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES);
putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES);
putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS);
int ycbcr = TiffTools.getIFDIntValue(ifd,
TiffTools.Y_CB_CR_SUB_SAMPLING);
String subSampling = null;
switch (ycbcr) {
case 1:
subSampling = "chroma image dimensions = luma image dimensions";
break;
case 2:
subSampling = "chroma image dimensions are " +
"half the luma image dimensions";
break;
case 4:
subSampling = "chroma image dimensions are " +
"1/4 the luma image dimensions";
break;
}
put("YCbCrSubSampling", subSampling);
putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING);
putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE);
// bits per sample and number of channels
Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE);
int bps = -1, numC = 3;
if (bpsObj instanceof int[]) {
int[] q = (int[]) bpsObj;
bps = q[0];
numC = q.length;
}
else if (bpsObj instanceof Number) {
bps = ((Number) bpsObj).intValue();
numC = 1;
}
// numC isn't set properly if we have an indexed color image, so we need
// to reset it here
int p = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION);
if (p == TiffTools.RGB_PALETTE || p == TiffTools.CFA_ARRAY) {
numC = 3;
bps *= 3;
}
put("BitsPerSample", bps);
put("NumberOfChannels", numC);
// TIFF comment
String comment = null;
Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
if (o instanceof String) comment = (String) o;
else if (o instanceof String[]) {
String[] s = (String[]) o;
if (s.length > 0) comment = s[0];
}
else if (o != null) comment = o.toString();
if (comment != null) {
// sanitize comment
comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF
comment = comment.replaceAll("\r", "\n"); // CR to LF
put("Comment", comment);
}
int samples = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLES_PER_PIXEL, false, 1);
core.rgb[0] = samples > 1 || p == TiffTools.RGB;
core.interleaved[0] = false;
core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]);
core.sizeX[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_WIDTH, false, 0);
core.sizeY[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_LENGTH, false, 0);
core.sizeZ[0] = 1;
core.sizeC[0] = core.rgb[0] ? samples : 1;
core.sizeT[0] = ifds.length;
core.metadataComplete[0] = true;
core.indexed[0] = p == TiffTools.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
if (core.sizeC[0] == 1 && !core.indexed[0]) core.rgb[0] = false;
core.falseColor[0] = false;
int bitFormat = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLE_FORMAT);
while (bps % 8 != 0) bps++;
if (bps == 24 || bps == 48) bps /= 3;
if (bitFormat == 3) core.pixelType[0] = FormatTools.FLOAT;
else if (bitFormat == 2) {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.INT16;
break;
case 32:
core.pixelType[0] = FormatTools.INT32;
break;
default:
core.pixelType[0] = FormatTools.INT8;
}
}
else {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.UINT16;
break;
case 32:
core.pixelType[0] = FormatTools.UINT32;
break;
default:
core.pixelType[0] = FormatTools.UINT8;
}
}
core.currentOrder[0] = "XYCZT";
}
| protected void initStandardMetadata() throws FormatException, IOException {
Hashtable ifd = ifds[0];
put("ImageWidth", ifd, TiffTools.IMAGE_WIDTH);
put("ImageLength", ifd, TiffTools.IMAGE_LENGTH);
put("BitsPerSample", ifd, TiffTools.BITS_PER_SAMPLE);
int comp = TiffTools.getIFDIntValue(ifd, TiffTools.COMPRESSION);
String compression = null;
switch (comp) {
case TiffTools.UNCOMPRESSED:
compression = "None";
break;
case TiffTools.CCITT_1D:
compression = "CCITT Group 3 1-Dimensional Modified Huffman";
break;
case TiffTools.GROUP_3_FAX:
compression = "CCITT T.4 bilevel encoding";
break;
case TiffTools.GROUP_4_FAX:
compression = "CCITT T.6 bilevel encoding";
break;
case TiffTools.LZW:
compression = "LZW";
break;
case TiffTools.JPEG:
compression = "JPEG";
break;
case TiffTools.PACK_BITS:
compression = "PackBits";
break;
}
put("Compression", compression);
int photo = TiffTools.getIFDIntValue(ifd,
TiffTools.PHOTOMETRIC_INTERPRETATION);
String photoInterp = null;
String metaDataPhotoInterp = null;
switch (photo) {
case TiffTools.WHITE_IS_ZERO:
photoInterp = "WhiteIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.BLACK_IS_ZERO:
photoInterp = "BlackIsZero";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.RGB:
photoInterp = "RGB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.RGB_PALETTE:
photoInterp = "Palette";
metaDataPhotoInterp = "Monochrome";
break;
case TiffTools.TRANSPARENCY_MASK:
photoInterp = "Transparency Mask";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CMYK:
photoInterp = "CMYK";
metaDataPhotoInterp = "CMYK";
break;
case TiffTools.Y_CB_CR:
photoInterp = "YCbCr";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CIE_LAB:
photoInterp = "CIELAB";
metaDataPhotoInterp = "RGB";
break;
case TiffTools.CFA_ARRAY:
photoInterp = "Color Filter Array";
metaDataPhotoInterp = "RGB";
break;
}
put("PhotometricInterpretation", photoInterp);
put("MetaDataPhotometricInterpretation", metaDataPhotoInterp);
putInt("CellWidth", ifd, TiffTools.CELL_WIDTH);
putInt("CellLength", ifd, TiffTools.CELL_LENGTH);
int or = TiffTools.getIFDIntValue(ifd, TiffTools.ORIENTATION);
// adjust the width and height if necessary
if (or == 8) {
put("ImageWidth", ifd, TiffTools.IMAGE_LENGTH);
put("ImageLength", ifd, TiffTools.IMAGE_WIDTH);
}
String orientation = null;
// there is no case 0
switch (or) {
case 1:
orientation = "1st row -> top; 1st column -> left";
break;
case 2:
orientation = "1st row -> top; 1st column -> right";
break;
case 3:
orientation = "1st row -> bottom; 1st column -> right";
break;
case 4:
orientation = "1st row -> bottom; 1st column -> left";
break;
case 5:
orientation = "1st row -> left; 1st column -> top";
break;
case 6:
orientation = "1st row -> right; 1st column -> top";
break;
case 7:
orientation = "1st row -> right; 1st column -> bottom";
break;
case 8:
orientation = "1st row -> left; 1st column -> bottom";
break;
}
put("Orientation", orientation);
putInt("SamplesPerPixel", ifd, TiffTools.SAMPLES_PER_PIXEL);
put("Software", ifd, TiffTools.SOFTWARE);
put("Instrument Make", ifd, TiffTools.MAKE);
put("Instrument Model", ifd, TiffTools.MODEL);
put("Document Name", ifd, TiffTools.DOCUMENT_NAME);
put("DateTime", ifd, TiffTools.DATE_TIME);
put("Artist", ifd, TiffTools.ARTIST);
put("HostComputer", ifd, TiffTools.HOST_COMPUTER);
put("Copyright", ifd, TiffTools.COPYRIGHT);
put("NewSubfileType", ifd, TiffTools.NEW_SUBFILE_TYPE);
int thresh = TiffTools.getIFDIntValue(ifd, TiffTools.THRESHHOLDING);
String threshholding = null;
switch (thresh) {
case 1:
threshholding = "No dithering or halftoning";
break;
case 2:
threshholding = "Ordered dithering or halftoning";
break;
case 3:
threshholding = "Randomized error diffusion";
break;
}
put("Threshholding", threshholding);
int fill = TiffTools.getIFDIntValue(ifd, TiffTools.FILL_ORDER);
String fillOrder = null;
switch (fill) {
case 1:
fillOrder = "Pixels with lower column values are stored " +
"in the higher order bits of a byte";
break;
case 2:
fillOrder = "Pixels with lower column values are stored " +
"in the lower order bits of a byte";
break;
}
put("FillOrder", fillOrder);
putInt("Make", ifd, TiffTools.MAKE);
putInt("Model", ifd, TiffTools.MODEL);
putInt("MinSampleValue", ifd, TiffTools.MIN_SAMPLE_VALUE);
putInt("MaxSampleValue", ifd, TiffTools.MAX_SAMPLE_VALUE);
putInt("XResolution", ifd, TiffTools.X_RESOLUTION);
putInt("YResolution", ifd, TiffTools.Y_RESOLUTION);
int planar = TiffTools.getIFDIntValue(ifd,
TiffTools.PLANAR_CONFIGURATION);
String planarConfig = null;
switch (planar) {
case 1:
planarConfig = "Chunky";
break;
case 2:
planarConfig = "Planar";
break;
}
put("PlanarConfiguration", planarConfig);
putInt("XPosition", ifd, TiffTools.X_POSITION);
putInt("YPosition", ifd, TiffTools.Y_POSITION);
putInt("FreeOffsets", ifd, TiffTools.FREE_OFFSETS);
putInt("FreeByteCounts", ifd, TiffTools.FREE_BYTE_COUNTS);
putInt("GrayResponseUnit", ifd, TiffTools.GRAY_RESPONSE_UNIT);
putInt("GrayResponseCurve", ifd, TiffTools.GRAY_RESPONSE_CURVE);
putInt("T4Options", ifd, TiffTools.T4_OPTIONS);
putInt("T6Options", ifd, TiffTools.T6_OPTIONS);
int res = TiffTools.getIFDIntValue(ifd, TiffTools.RESOLUTION_UNIT);
String resUnit = null;
switch (res) {
case 1:
resUnit = "None";
break;
case 2:
resUnit = "Inch";
break;
case 3:
resUnit = "Centimeter";
break;
}
put("ResolutionUnit", resUnit);
putInt("PageNumber", ifd, TiffTools.PAGE_NUMBER);
putInt("TransferFunction", ifd, TiffTools.TRANSFER_FUNCTION);
int predict = TiffTools.getIFDIntValue(ifd, TiffTools.PREDICTOR);
String predictor = null;
switch (predict) {
case 1:
predictor = "No prediction scheme";
break;
case 2:
predictor = "Horizontal differencing";
break;
}
put("Predictor", predictor);
putInt("WhitePoint", ifd, TiffTools.WHITE_POINT);
putInt("PrimaryChromacities", ifd, TiffTools.PRIMARY_CHROMATICITIES);
putInt("HalftoneHints", ifd, TiffTools.HALFTONE_HINTS);
putInt("TileWidth", ifd, TiffTools.TILE_WIDTH);
putInt("TileLength", ifd, TiffTools.TILE_LENGTH);
putInt("TileOffsets", ifd, TiffTools.TILE_OFFSETS);
putInt("TileByteCounts", ifd, TiffTools.TILE_BYTE_COUNTS);
int ink = TiffTools.getIFDIntValue(ifd, TiffTools.INK_SET);
String inkSet = null;
switch (ink) {
case 1:
inkSet = "CMYK";
break;
case 2:
inkSet = "Other";
break;
}
put("InkSet", inkSet);
putInt("InkNames", ifd, TiffTools.INK_NAMES);
putInt("NumberOfInks", ifd, TiffTools.NUMBER_OF_INKS);
putInt("DotRange", ifd, TiffTools.DOT_RANGE);
put("TargetPrinter", ifd, TiffTools.TARGET_PRINTER);
putInt("ExtraSamples", ifd, TiffTools.EXTRA_SAMPLES);
int fmt = TiffTools.getIFDIntValue(ifd, TiffTools.SAMPLE_FORMAT);
String sampleFormat = null;
switch (fmt) {
case 1:
sampleFormat = "unsigned integer";
break;
case 2:
sampleFormat = "two's complement signed integer";
break;
case 3:
sampleFormat = "IEEE floating point";
break;
case 4:
sampleFormat = "undefined";
break;
}
put("SampleFormat", sampleFormat);
putInt("SMinSampleValue", ifd, TiffTools.S_MIN_SAMPLE_VALUE);
putInt("SMaxSampleValue", ifd, TiffTools.S_MAX_SAMPLE_VALUE);
putInt("TransferRange", ifd, TiffTools.TRANSFER_RANGE);
int jpeg = TiffTools.getIFDIntValue(ifd, TiffTools.JPEG_PROC);
String jpegProc = null;
switch (jpeg) {
case 1:
jpegProc = "baseline sequential process";
break;
case 14:
jpegProc = "lossless process with Huffman coding";
break;
}
put("JPEGProc", jpegProc);
putInt("JPEGInterchangeFormat", ifd, TiffTools.JPEG_INTERCHANGE_FORMAT);
putInt("JPEGRestartInterval", ifd, TiffTools.JPEG_RESTART_INTERVAL);
putInt("JPEGLosslessPredictors",
ifd, TiffTools.JPEG_LOSSLESS_PREDICTORS);
putInt("JPEGPointTransforms", ifd, TiffTools.JPEG_POINT_TRANSFORMS);
putInt("JPEGQTables", ifd, TiffTools.JPEG_Q_TABLES);
putInt("JPEGDCTables", ifd, TiffTools.JPEG_DC_TABLES);
putInt("JPEGACTables", ifd, TiffTools.JPEG_AC_TABLES);
putInt("YCbCrCoefficients", ifd, TiffTools.Y_CB_CR_COEFFICIENTS);
int ycbcr = TiffTools.getIFDIntValue(ifd,
TiffTools.Y_CB_CR_SUB_SAMPLING);
String subSampling = null;
switch (ycbcr) {
case 1:
subSampling = "chroma image dimensions = luma image dimensions";
break;
case 2:
subSampling = "chroma image dimensions are " +
"half the luma image dimensions";
break;
case 4:
subSampling = "chroma image dimensions are " +
"1/4 the luma image dimensions";
break;
}
put("YCbCrSubSampling", subSampling);
putInt("YCbCrPositioning", ifd, TiffTools.Y_CB_CR_POSITIONING);
putInt("ReferenceBlackWhite", ifd, TiffTools.REFERENCE_BLACK_WHITE);
// bits per sample and number of channels
Object bpsObj = TiffTools.getIFDValue(ifd, TiffTools.BITS_PER_SAMPLE);
int bps = -1, numC = 3;
if (bpsObj instanceof int[]) {
int[] q = (int[]) bpsObj;
bps = q[0];
numC = q.length;
}
else if (bpsObj instanceof Number) {
bps = ((Number) bpsObj).intValue();
numC = 1;
}
// numC isn't set properly if we have an indexed color image, so we need
// to reset it here
int p = TiffTools.getIFDIntValue(ifd, TiffTools.PHOTOMETRIC_INTERPRETATION);
if (p == TiffTools.RGB_PALETTE || p == TiffTools.CFA_ARRAY) {
numC = 3;
bps *= 3;
}
put("BitsPerSample", bps);
put("NumberOfChannels", numC);
// TIFF comment
String comment = null;
Object o = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
if (o instanceof String) comment = (String) o;
else if (o instanceof String[]) {
String[] s = (String[]) o;
if (s.length > 0) comment = s[0];
}
else if (o != null) comment = o.toString();
if (comment != null) {
// sanitize comment
comment = comment.replaceAll("\r\n", "\n"); // CR-LF to LF
comment = comment.replaceAll("\r", "\n"); // CR to LF
put("Comment", comment);
}
int samples = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLES_PER_PIXEL, false, 1);
core.rgb[0] = samples > 1 || p == TiffTools.RGB;
core.interleaved[0] = false;
core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]);
core.sizeX[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_WIDTH, false, 0);
core.sizeY[0] =
TiffTools.getIFDIntValue(ifds[0], TiffTools.IMAGE_LENGTH, false, 0);
core.sizeZ[0] = 1;
core.sizeC[0] = core.rgb[0] ? samples : 1;
core.sizeT[0] = ifds.length;
core.metadataComplete[0] = true;
core.indexed[0] = p == TiffTools.RGB_PALETTE &&
(get8BitLookupTable() != null || get16BitLookupTable() != null);
if (core.sizeC[0] == 1 && !core.indexed[0]) core.rgb[0] = false;
core.falseColor[0] = false;
int bitFormat = TiffTools.getIFDIntValue(ifds[0],
TiffTools.SAMPLE_FORMAT);
while (bps % 8 != 0) bps++;
if (bps == 24 || bps == 48) bps /= 3;
if (bitFormat == 3) {
core.pixelType[0] = FormatTools.FLOAT;
core.littleEndian[0] = true;
}
else if (bitFormat == 2) {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.INT16;
break;
case 32:
core.pixelType[0] = FormatTools.INT32;
break;
default:
core.pixelType[0] = FormatTools.INT8;
}
}
else {
switch (bps) {
case 16:
core.pixelType[0] = FormatTools.UINT16;
break;
case 32:
core.pixelType[0] = FormatTools.UINT32;
break;
default:
core.pixelType[0] = FormatTools.UINT8;
}
}
core.currentOrder[0] = "XYCZT";
}
|
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/UpToDateStatusTask.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/UpToDateStatusTask.java
index d4c33616..c737c197 100644
--- a/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/UpToDateStatusTask.java
+++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/UpToDateStatusTask.java
@@ -1,187 +1,188 @@
/*
* 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.editor.semantic;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Position;
import javax.swing.text.StyledDocument;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import org.netbeans.api.javafx.lexer.JFXTokenId;
import org.netbeans.api.javafx.source.CancellableTask;
import org.netbeans.api.javafx.source.CompilationController;
import org.netbeans.api.javafx.source.CompilationInfo;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.spi.editor.errorstripe.UpToDateStatus;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.ErrorDescriptionFactory;
import org.netbeans.spi.editor.hints.HintsController;
import org.netbeans.spi.editor.hints.Severity;
import org.openide.filesystems.FileObject;
import org.openide.text.NbDocument;
import org.openide.util.Exceptions;
/**
*
* @author David Strupl
*/
class UpToDateStatusTask implements CancellableTask<CompilationInfo> {
private static final Logger LOGGER = Logger.getLogger(UpToDateStatusTask.class.getName());
private static final boolean LOGGABLE = LOGGER.isLoggable(Level.FINE);
private AtomicBoolean cancel = new AtomicBoolean();
UpToDateStatusTask(FileObject file) {
}
private UpToDateStatusTask() {
}
public void cancel() {
cancel.set(true);
}
public void run(CompilationInfo info) {
cancel.set(false);
process(info);
}
private void process(CompilationInfo info) {
if (LOGGABLE) log("process: " + info.getJavaFXSource().getFileObject());
Document doc = info.getJavaFXSource().getDocument();
if (doc == null) {
if (LOGGABLE) log(" no document for: " + info.getJavaFXSource());
return;
}
List<Diagnostic> diag = info.getDiagnostics();
ArrayList<ErrorDescription> c = new ArrayList<ErrorDescription>();
for (Diagnostic d : diag) {
if (LOGGABLE) log(" diagnostics: " + d);
if (d.getSource() instanceof JavaFileObject) {
JavaFileObject jfo = (JavaFileObject)d.getSource();
if (! jfo.getName().equals(info.getJavaFXSource().getFileObject().getNameExt())) {
if (LOGGABLE) log(" in different file: " + jfo.getName() + " vs.: " + info.getJavaFXSource().getFileObject().getNameExt());
continue;
}
} else {
if (LOGGABLE) log(" source is not JavaFileObject but: " + (d.getSource() != null ? d.getSource().getClass().getName() : "null"));
}
long start = d.getStartPosition();
long end = d.getEndPosition();
if (start != Diagnostic.NOPOS && end != Diagnostic.NOPOS) {
if (LOGGABLE) log(" start == " + start + " end == " + end);
if (start == end) {
end = skipWhiteSpace(info, (int)start);
if (LOGGABLE) log(" after skip start == " + start + " end == " + end);
}
try {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR,
d.getMessage(Locale.getDefault()),
doc,
doc.createPosition((int) start),
doc.createPosition((int) end)
));
continue;
} catch (BadLocationException ex) {
if (LOGGABLE) {
LOGGER.log(Level.INFO, "Problem with error underlining", ex);
}
}
}
// let's use the line number
- int lastLine = NbDocument.findLineNumber((StyledDocument)doc, doc.getEndPosition().getOffset());
- if (LOGGABLE) log(" lastLine == " + lastLine);
- if (d.getLineNumber()-1 <= lastLine) {
+ int lastLine = NbDocument.findLineNumber((StyledDocument)doc, doc.getEndPosition().getOffset());
+ long linu = d.getLineNumber();
+ if (LOGGABLE) log(" lastLine == " + lastLine + " linu == " + linu);
+ if ( (linu>=0) && (linu-1 <= lastLine)) {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR, d.getMessage(Locale.getDefault()),
doc, (int)d.getLineNumber()));
} else {
- if (LOGGABLE) log(" after last line: " + d);
+ if (LOGGABLE) log(" NOT USED (wrong bounds): " + d);
}
}
HintsController.setErrors(doc, "semantic-highlighter", c);
UpToDateStatusProviderImpl p = UpToDateStatusProviderImpl.forDocument(doc);
p.refresh(diag, UpToDateStatus.UP_TO_DATE_OK);
}
private int skipWhiteSpace(CompilationInfo info, int start) {
TokenSequence<JFXTokenId> ts = ((TokenHierarchy<?>) info.getTokenHierarchy()).tokenSequence(JFXTokenId.language());
ts.move(start);
boolean nonWSFound = false;
while (ts.moveNext()) {
if (ts.token().id() != JFXTokenId.WS) {
nonWSFound = true;
break;
}
}
if (!nonWSFound) {
if (LOGGABLE) log("NOT skipping the WS because we are at the very end");
return start;
}
int res = ts.offset();
if (res > start && res < info.getJavaFXSource().getDocument().getLength()) {
if (LOGGABLE) log("skipping the whitespace start == " + start + " res == " + res);
return res;
} else {
if (LOGGABLE) log("NOT skipping the whitespace start == " + start + " res == " + res);
return start;
}
}
private static void log(String s) {
if (LOGGABLE) {
LOGGER.fine(s);
}
}
}
| false | true | private void process(CompilationInfo info) {
if (LOGGABLE) log("process: " + info.getJavaFXSource().getFileObject());
Document doc = info.getJavaFXSource().getDocument();
if (doc == null) {
if (LOGGABLE) log(" no document for: " + info.getJavaFXSource());
return;
}
List<Diagnostic> diag = info.getDiagnostics();
ArrayList<ErrorDescription> c = new ArrayList<ErrorDescription>();
for (Diagnostic d : diag) {
if (LOGGABLE) log(" diagnostics: " + d);
if (d.getSource() instanceof JavaFileObject) {
JavaFileObject jfo = (JavaFileObject)d.getSource();
if (! jfo.getName().equals(info.getJavaFXSource().getFileObject().getNameExt())) {
if (LOGGABLE) log(" in different file: " + jfo.getName() + " vs.: " + info.getJavaFXSource().getFileObject().getNameExt());
continue;
}
} else {
if (LOGGABLE) log(" source is not JavaFileObject but: " + (d.getSource() != null ? d.getSource().getClass().getName() : "null"));
}
long start = d.getStartPosition();
long end = d.getEndPosition();
if (start != Diagnostic.NOPOS && end != Diagnostic.NOPOS) {
if (LOGGABLE) log(" start == " + start + " end == " + end);
if (start == end) {
end = skipWhiteSpace(info, (int)start);
if (LOGGABLE) log(" after skip start == " + start + " end == " + end);
}
try {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR,
d.getMessage(Locale.getDefault()),
doc,
doc.createPosition((int) start),
doc.createPosition((int) end)
));
continue;
} catch (BadLocationException ex) {
if (LOGGABLE) {
LOGGER.log(Level.INFO, "Problem with error underlining", ex);
}
}
}
// let's use the line number
int lastLine = NbDocument.findLineNumber((StyledDocument)doc, doc.getEndPosition().getOffset());
if (LOGGABLE) log(" lastLine == " + lastLine);
if (d.getLineNumber()-1 <= lastLine) {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR, d.getMessage(Locale.getDefault()),
doc, (int)d.getLineNumber()));
} else {
if (LOGGABLE) log(" after last line: " + d);
}
}
HintsController.setErrors(doc, "semantic-highlighter", c);
UpToDateStatusProviderImpl p = UpToDateStatusProviderImpl.forDocument(doc);
p.refresh(diag, UpToDateStatus.UP_TO_DATE_OK);
}
| private void process(CompilationInfo info) {
if (LOGGABLE) log("process: " + info.getJavaFXSource().getFileObject());
Document doc = info.getJavaFXSource().getDocument();
if (doc == null) {
if (LOGGABLE) log(" no document for: " + info.getJavaFXSource());
return;
}
List<Diagnostic> diag = info.getDiagnostics();
ArrayList<ErrorDescription> c = new ArrayList<ErrorDescription>();
for (Diagnostic d : diag) {
if (LOGGABLE) log(" diagnostics: " + d);
if (d.getSource() instanceof JavaFileObject) {
JavaFileObject jfo = (JavaFileObject)d.getSource();
if (! jfo.getName().equals(info.getJavaFXSource().getFileObject().getNameExt())) {
if (LOGGABLE) log(" in different file: " + jfo.getName() + " vs.: " + info.getJavaFXSource().getFileObject().getNameExt());
continue;
}
} else {
if (LOGGABLE) log(" source is not JavaFileObject but: " + (d.getSource() != null ? d.getSource().getClass().getName() : "null"));
}
long start = d.getStartPosition();
long end = d.getEndPosition();
if (start != Diagnostic.NOPOS && end != Diagnostic.NOPOS) {
if (LOGGABLE) log(" start == " + start + " end == " + end);
if (start == end) {
end = skipWhiteSpace(info, (int)start);
if (LOGGABLE) log(" after skip start == " + start + " end == " + end);
}
try {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR,
d.getMessage(Locale.getDefault()),
doc,
doc.createPosition((int) start),
doc.createPosition((int) end)
));
continue;
} catch (BadLocationException ex) {
if (LOGGABLE) {
LOGGER.log(Level.INFO, "Problem with error underlining", ex);
}
}
}
// let's use the line number
int lastLine = NbDocument.findLineNumber((StyledDocument)doc, doc.getEndPosition().getOffset());
long linu = d.getLineNumber();
if (LOGGABLE) log(" lastLine == " + lastLine + " linu == " + linu);
if ( (linu>=0) && (linu-1 <= lastLine)) {
c.add(ErrorDescriptionFactory.createErrorDescription(
Severity.ERROR, d.getMessage(Locale.getDefault()),
doc, (int)d.getLineNumber()));
} else {
if (LOGGABLE) log(" NOT USED (wrong bounds): " + d);
}
}
HintsController.setErrors(doc, "semantic-highlighter", c);
UpToDateStatusProviderImpl p = UpToDateStatusProviderImpl.forDocument(doc);
p.refresh(diag, UpToDateStatus.UP_TO_DATE_OK);
}
|
diff --git a/src/main/java/wicket/contrib/gmap3/GMapHeaderContributor.java b/src/main/java/wicket/contrib/gmap3/GMapHeaderContributor.java
index 198039b..0a1dead 100644
--- a/src/main/java/wicket/contrib/gmap3/GMapHeaderContributor.java
+++ b/src/main/java/wicket/contrib/gmap3/GMapHeaderContributor.java
@@ -1,54 +1,54 @@
package wicket.contrib.gmap3;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.ajax.WicketAjaxReference;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WicketEventReference;
import org.apache.wicket.markup.html.resources.JavascriptResourceReference;
public class GMapHeaderContributor extends HeaderContributor {
private static final long serialVersionUID = 1L;
// URL for Google Maps' API endpoint.
private static final String GMAP_API_URL = "://maps.google.com/maps/api/js?v=3&sensor=false";
private static final String HTTP = "http";
// We have some custom Javascript.
private static final ResourceReference WICKET_GMAP_JS = new JavascriptResourceReference( GMap.class, "wicket-gmap.js" );
protected static final String EMPTY = "";
String _clientId;
public GMapHeaderContributor() {
this( HTTP, null );
}
public GMapHeaderContributor( final String schema, final String clientId ) {
super( new IHeaderContributor() {
private static final long serialVersionUID = 1L;
@Override
public void renderHead( IHeaderResponse response ) {
final String clientParm;
- if ( !EMPTY.equals( clientId ) ) {
+ if ( clientId != null && !EMPTY.equals( clientId ) ) {
clientParm = "&client=" + clientId;
} else {
clientParm = EMPTY;
}
response.renderJavascriptReference( schema + GMAP_API_URL + clientParm );
response.renderJavascriptReference( WicketEventReference.INSTANCE );
response.renderJavascriptReference( WicketAjaxReference.INSTANCE );
response.renderJavascriptReference( WICKET_GMAP_JS );
}
} );
}
String getClientId() {
return _clientId;
}
}
| true | true | public GMapHeaderContributor( final String schema, final String clientId ) {
super( new IHeaderContributor() {
private static final long serialVersionUID = 1L;
@Override
public void renderHead( IHeaderResponse response ) {
final String clientParm;
if ( !EMPTY.equals( clientId ) ) {
clientParm = "&client=" + clientId;
} else {
clientParm = EMPTY;
}
response.renderJavascriptReference( schema + GMAP_API_URL + clientParm );
response.renderJavascriptReference( WicketEventReference.INSTANCE );
response.renderJavascriptReference( WicketAjaxReference.INSTANCE );
response.renderJavascriptReference( WICKET_GMAP_JS );
}
} );
}
| public GMapHeaderContributor( final String schema, final String clientId ) {
super( new IHeaderContributor() {
private static final long serialVersionUID = 1L;
@Override
public void renderHead( IHeaderResponse response ) {
final String clientParm;
if ( clientId != null && !EMPTY.equals( clientId ) ) {
clientParm = "&client=" + clientId;
} else {
clientParm = EMPTY;
}
response.renderJavascriptReference( schema + GMAP_API_URL + clientParm );
response.renderJavascriptReference( WicketEventReference.INSTANCE );
response.renderJavascriptReference( WicketAjaxReference.INSTANCE );
response.renderJavascriptReference( WICKET_GMAP_JS );
}
} );
}
|
diff --git a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/ResourcesUtils.java b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/ResourcesUtils.java
index 292e521c8..fa3d48417 100644
--- a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/ResourcesUtils.java
+++ b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/ResourcesUtils.java
@@ -1,228 +1,229 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.test.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;
import org.jboss.tools.tests.ImportBean;
import org.jboss.tools.tests.ImportProvider;
import org.osgi.framework.Bundle;
/**
* @author eskimo
*
*/
public class ResourcesUtils {
public static IProject importProject(
Bundle bundle, String templLocation,
IProgressMonitor monitor)
throws
IOException, CoreException,
InvocationTargetException, InterruptedException {
String tplPrjLcStr;
tplPrjLcStr = FileLocator.resolve(bundle.getEntry(templLocation))
.getFile();
IProject importedPrj = importProjectIntoWorkspace(tplPrjLcStr, new Path(tplPrjLcStr).lastSegment());
return importedPrj;
}
public static IProject importProject(
Bundle bundle, String templLocation) throws IOException, CoreException, InvocationTargetException, InterruptedException {
return importProject(bundle, templLocation, new NullProgressMonitor());
}
public static IProject createEclipseProject(String projectName,
IProgressMonitor monitor) throws CoreException {
IProject newProjectHandle = ResourcesPlugin.getWorkspace().getRoot()
.getProject(projectName);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IProjectDescription description = workspace
.newProjectDescription(projectName);
newProjectHandle.create(description, new NullProgressMonitor());
newProjectHandle.open(monitor);
return newProjectHandle;
}
public static IProject createEclipseProject(Bundle bundle,
String templateLocation, IProgressMonitor monitor)
throws CoreException, IOException {
IPath tplPrjDescr = new Path(templateLocation)
.append(IProjectDescription.DESCRIPTION_FILE_NAME);
IProjectDescription descr = ResourcesPlugin.getWorkspace()
.loadProjectDescription(tplPrjDescr);
descr.setLocation(null);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(
descr.getName());
project.create(descr, monitor);
project.open(IResource.BACKGROUND_REFRESH, monitor);
return project;
}
public static IProject createEclipseProject(Bundle bundle,
String templateLocation)
throws CoreException, IOException {
return createEclipseProject(bundle,templateLocation, new NullProgressMonitor());
}
public static IProject createEclipseProject(String bundle,
String templateLocation, IProgressMonitor monitor)
throws CoreException, IOException {
return createEclipseProject(
Platform.getBundle(bundle), templateLocation, monitor);
}
public static boolean findLineInFile(IFile file, String pattern) throws CoreException, IOException {
InputStream content = file.getContents(true);
LineNumberReader contentReader = new LineNumberReader(new InputStreamReader(content));
String line;
boolean patternIsFound = false;
do {
line = contentReader.readLine();
if(line!=null && !patternIsFound) {
patternIsFound = line.trim().matches(pattern);
}
} while (line != null && !patternIsFound);
return patternIsFound;
}
/**
* @param string
* @param string2
* @param nullProgressMonitor
* @return
* @throws InterruptedException
* @throws InvocationTargetException
* @throws CoreException
* @throws IOException
*/
public static IProject importProject(String bundleName, String templatePath,
IProgressMonitor monitor) throws IOException, CoreException, InvocationTargetException, InterruptedException {
// TODO Auto-generated method stub
return importProject(Platform.getBundle(bundleName), templatePath, monitor==null?new NullProgressMonitor():monitor);
}
public static IProject importProject(String bundleName, String templatePath) throws IOException, CoreException, InvocationTargetException, InterruptedException {
// TODO Auto-generated method stub
return importProject(Platform.getBundle(bundleName), templatePath, null);
}
public static void deleteProject(String projectName) throws CoreException {
IResource member = ResourcesPlugin.getWorkspace().getRoot().findMember(projectName);
if (member != null) {
member.getProject().delete(true, true, null);
}
}
public static boolean setBuildAutomatically(boolean state) throws CoreException {
boolean oldAutoBuilding;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceDescription description = workspace.getDescription();
oldAutoBuilding = description.isAutoBuilding();
if (state != oldAutoBuilding) {
description.setAutoBuilding(state);
workspace.setDescription(description);
}
return oldAutoBuilding;
}
static public void importProjectIntoWorkspace(ImportBean bean) {
importProjectIntoWorkspace(bean);
}
/**
* Import project into workspace.
*
* @param path the path
* @param projectName the project name
*/
static public IProject importProjectIntoWorkspace(String path, String projectName) {
IProject project = null;
try {
project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
project.create(null);
project.open(null);
JobUtils.waitForIdle();
IOverwriteQuery overwrite = new IOverwriteQuery() {
public String queryOverwrite(String pathString) {
return ALL;
}
};
ImportProvider importProvider = new ImportProvider();
// need to remove from imported project "svn" files
List<String> unimportedFiles = new ArrayList<String>();
unimportedFiles.add(".svn"); //$NON-NLS-1$
importProvider.setUnimportedFiles(unimportedFiles);
// create import operation
ImportOperation importOp = new ImportOperation(project
.getFullPath(), new File(path), importProvider, overwrite);
// import files just to project folder ( without old structure )
importOp.setCreateContainerStructure(false);
importOp.setContext(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell());
// run import
importOp.run(null);
+ JobUtils.waitForIdle();
} catch (InvocationTargetException ite) {
// TePlugin.getDefault().logError(ite.getCause());
} catch (InterruptedException ie) {
// VPETestPlugin.getDefault().logError(ie);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return project;
}
}
| true | true | static public IProject importProjectIntoWorkspace(String path, String projectName) {
IProject project = null;
try {
project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
project.create(null);
project.open(null);
JobUtils.waitForIdle();
IOverwriteQuery overwrite = new IOverwriteQuery() {
public String queryOverwrite(String pathString) {
return ALL;
}
};
ImportProvider importProvider = new ImportProvider();
// need to remove from imported project "svn" files
List<String> unimportedFiles = new ArrayList<String>();
unimportedFiles.add(".svn"); //$NON-NLS-1$
importProvider.setUnimportedFiles(unimportedFiles);
// create import operation
ImportOperation importOp = new ImportOperation(project
.getFullPath(), new File(path), importProvider, overwrite);
// import files just to project folder ( without old structure )
importOp.setCreateContainerStructure(false);
importOp.setContext(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell());
// run import
importOp.run(null);
} catch (InvocationTargetException ite) {
// TePlugin.getDefault().logError(ite.getCause());
} catch (InterruptedException ie) {
// VPETestPlugin.getDefault().logError(ie);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return project;
}
| static public IProject importProjectIntoWorkspace(String path, String projectName) {
IProject project = null;
try {
project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
project.create(null);
project.open(null);
JobUtils.waitForIdle();
IOverwriteQuery overwrite = new IOverwriteQuery() {
public String queryOverwrite(String pathString) {
return ALL;
}
};
ImportProvider importProvider = new ImportProvider();
// need to remove from imported project "svn" files
List<String> unimportedFiles = new ArrayList<String>();
unimportedFiles.add(".svn"); //$NON-NLS-1$
importProvider.setUnimportedFiles(unimportedFiles);
// create import operation
ImportOperation importOp = new ImportOperation(project
.getFullPath(), new File(path), importProvider, overwrite);
// import files just to project folder ( without old structure )
importOp.setCreateContainerStructure(false);
importOp.setContext(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getShell());
// run import
importOp.run(null);
JobUtils.waitForIdle();
} catch (InvocationTargetException ite) {
// TePlugin.getDefault().logError(ite.getCause());
} catch (InterruptedException ie) {
// VPETestPlugin.getDefault().logError(ie);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return project;
}
|
diff --git a/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestRCBP1.java b/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestRCBP1.java
index 41f0974b7..4c843b7d0 100644
--- a/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestRCBP1.java
+++ b/plugins/org.eclipse.tcf.debug/src/org/eclipse/tcf/internal/debug/tests/TestRCBP1.java
@@ -1,1897 +1,1898 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.tests;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.eclipse.tcf.internal.debug.model.TCFMemoryRegion;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IErrorReport;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IBreakpoints;
import org.eclipse.tcf.services.IContextQuery;
import org.eclipse.tcf.services.IDiagnostics;
import org.eclipse.tcf.services.IDisassembly;
import org.eclipse.tcf.services.ILineNumbers;
import org.eclipse.tcf.services.IMemory;
import org.eclipse.tcf.services.IMemoryMap;
import org.eclipse.tcf.services.IPathMap;
import org.eclipse.tcf.services.IRegisters;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.services.ISymbols;
import org.eclipse.tcf.services.IDiagnostics.ISymbol;
import org.eclipse.tcf.services.IDisassembly.IDisassemblyLine;
import org.eclipse.tcf.services.ILineNumbers.CodeArea;
import org.eclipse.tcf.services.IMemory.MemoryContext;
import org.eclipse.tcf.services.IMemory.MemoryError;
import org.eclipse.tcf.services.IMemoryMap.MemoryRegion;
import org.eclipse.tcf.services.IPathMap.PathMapRule;
import org.eclipse.tcf.services.IRegisters.RegistersContext;
import org.eclipse.tcf.services.IRunControl.RunControlContext;
import org.eclipse.tcf.services.ISymbols.Symbol;
class TestRCBP1 implements ITCFTest, IRunControl.RunControlListener {
private final TCFTestSuite test_suite;
private final RunControl test_rc;
private final int channel_id;
private final List<PathMapRule> path_map;
private final Map<String,ArrayList<MemoryRegion>> mem_map;
private final IDiagnostics srv_diag;
private final ISymbols srv_syms;
private final IMemory srv_memory;
private final IRunControl srv_run_ctrl;
private final IRegisters srv_registers;
private final IBreakpoints srv_breakpoints;
private final ILineNumbers srv_line_numbers;
private final IDisassembly srv_disassembly;
private final IPathMap srv_path_map;
private final IMemoryMap srv_memory_map;
private final IContextQuery srv_context_query;
private final Map<String,IRunControl.RunControlContext> threads = new HashMap<String,IRunControl.RunControlContext>();
private final Map<String,SuspendedContext> suspended = new HashMap<String,SuspendedContext>();
private final Map<String,SuspendedContext> suspended_prev = new HashMap<String,SuspendedContext>();
private final Map<String,IDisassemblyLine[]> disassembly_lines = new HashMap<String,IDisassemblyLine[]>();
private final Map<String,Map<String,Object>[]> disassembly_capabilities = new HashMap<String,Map<String,Object>[]>();
private final Set<String> running = new HashSet<String>();
private final Set<IToken> get_state_cmds = new HashSet<IToken>();
private final Set<IToken> bp_change_cmds = new HashSet<IToken>();
private final Map<String,Map<String,IRegisters.RegistersContext>> regs =
new HashMap<String,Map<String,IRegisters.RegistersContext>>();
private final Map<String,Map<String,Object>> bp_list = new HashMap<String,Map<String,Object>>();
private final Map<String,IDiagnostics.ISymbol> sym_list = new HashMap<String,IDiagnostics.ISymbol>();
private final Random rnd = new Random();
private String[] test_list;
private String test_id;
private boolean path_map_done;
private boolean mem_map_done;
private String test_ctx_id; // Test context ID
private IRunControl.RunControlContext test_context;
private String main_thread_id;
private Map<String,Object> bp_capabilities;
private Runnable pending_cancel;
private int bp_cnt;
private boolean done_get_state;
private boolean done_disassembly;
private int resume_cnt = 0;
private IToken cancel_test_cmd;
private boolean bp_reset_done;
private boolean bp_set_done;
private boolean bp_change_done;
private boolean bp_sync_done;
private boolean data_bp_area_done;
private ILineNumbers.CodeArea data_bp_area;
private String data_bp_id;
private String temp_bp_id;
private String inv_bp_id;
private boolean temp_bp_removed;
private int temp_bp_cnt;
private int data_bp_cnt;
private boolean mem_map_test_running;
private boolean mem_map_test_done;
private boolean all_setup_done;
private static int mem_map_region_id = 0;
private static class SuspendedContext {
final String id;
final String pc;
final String reason;
final Map<String,Object> params;
boolean get_state_pending;
boolean ok_to_resume;
SuspendedContext(String id, String pc, String reason, Map<String,Object> params) {
this.id = id;
this.pc = pc;
this.reason = reason;
this.params = params;
}
}
private final IBreakpoints.BreakpointsListener bp_listener = new IBreakpoints.BreakpointsListener() {
@SuppressWarnings("unchecked")
public void breakpointStatusChanged(String id, Map<String,Object> status) {
if (bp_list.get(id) != null && test_context != null && bp_cnt < 40) {
if (bp_change_cmds.size() == 0) {
Map<String,Object> m = bp_list.get(id);
Collection<String> prop_ids = (Collection<String>)m.get(IBreakpoints.PROP_CONTEXT_IDS);
if (prop_ids != null) {
Collection<Map<String,Object>> list = (Collection<Map<String,Object>>)
status.get(IBreakpoints.STATUS_INSTANCES);
if (list != null) {
for (Map<String,Object> map : list) {
String ctx = (String)map.get(IBreakpoints.INSTANCE_CONTEXT);
if (prop_ids.contains(ctx)) continue;
boolean ok = false;
for (String s : prop_ids) {
IRunControl.RunControlContext x = test_rc.getContext(s);
if (x != null && ctx.equals(x.getBPGroup())) ok = true;
}
if (!ok) {
exit(new Error("Breakpoint " + id + ": invalid planting context " + ctx));
return;
}
}
}
}
}
String prs = test_context.getProcessID();
if (prs != null) {
for (ITCFTest test : test_suite.getActiveTests()) {
if (test instanceof TestRCBP1) {
TestRCBP1 rcbp = (TestRCBP1)test;
if (!rcbp.mem_map_test_running) continue;
if (prs.equals(rcbp.test_context.getProcessID())) return;
}
}
}
String err = (String)status.get(IBreakpoints.STATUS_ERROR);
if (err == null) {
Collection<Map<String,Object>> list = (Collection<Map<String,Object>>)
status.get(IBreakpoints.STATUS_INSTANCES);
if (list != null) {
for (Map<String,Object> map : list) {
String ctx = (String)map.get(IBreakpoints.INSTANCE_CONTEXT);
if (test_context.getProcessID().equals(ctx) && map.get(IBreakpoints.INSTANCE_ERROR) != null)
err = (String)map.get(IBreakpoints.INSTANCE_ERROR);
}
}
}
if (err != null) {
if (bp_cnt == 0 && id.equals(data_bp_id)) return;
if (id.equals(inv_bp_id)) return;
exit(new Exception("Invalid BP status: " + err));
}
}
}
public void contextAdded(Map<String,Object>[] bps) {
for (Map<String,Object> m0 : bps) {
String id = (String)m0.get(IBreakpoints.PROP_ID);
Map<String,Object> m1 = bp_list.get(id);
if (!checkBPData(m0, m1)) return;
}
}
public void contextChanged(Map<String,Object>[] bps) {
if (bp_change_cmds.size() > 1) return;
for (Map<String,Object> m0 : bps) {
String id = (String)m0.get(IBreakpoints.PROP_ID);
Map<String,Object> m1 = bp_list.get(id);
if (!checkBPData(m0, m1)) return;
}
}
public void contextRemoved(String[] ids) {
if (!bp_change_done) return;
for (String id : ids) {
if (bp_list.get(id) != null) {
if (id.equals(temp_bp_id)) {
if (bp_cnt != 3 || temp_bp_removed) {
exit(new Exception("Invalid Breakpoints.contextRemoved event for temporary breakpoint"));
return;
}
temp_bp_removed = true;
}
else {
exit(new Exception("Invalid Breakpoints.contextRemoved event"));
return;
}
}
}
}
private boolean checkBPData(Map<String,Object> m0, Map<String,Object> m1) {
if (m1 == null) return true;
m0 = new HashMap<String,Object>(m0);
if (m0.get(IBreakpoints.PROP_ENABLED) == null) m0.put(IBreakpoints.PROP_ENABLED, false);
if (m1.get(IBreakpoints.PROP_ENABLED) == null) m1.put(IBreakpoints.PROP_ENABLED, false);
if (!m1.equals(m0)) {
exit(new Exception("Invalid data in Breakpoints event: " + m0 + " != " + m1));
return false;
}
return true;
}
};
TestRCBP1(TCFTestSuite test_suite, RunControl test_rc, IChannel channel, int channel_id,
List<PathMapRule> path_map, Map<String,ArrayList<MemoryRegion>> mem_map) {
this.test_suite = test_suite;
this.test_rc = test_rc;
this.channel_id = channel_id;
this.path_map = path_map;
this.mem_map = mem_map;
srv_diag = channel.getRemoteService(IDiagnostics.class);
srv_syms = channel.getRemoteService(ISymbols.class);
srv_memory = channel.getRemoteService(IMemory.class);
srv_run_ctrl = channel.getRemoteService(IRunControl.class);
srv_registers = channel.getRemoteService(IRegisters.class);
srv_breakpoints = channel.getRemoteService(IBreakpoints.class);
srv_line_numbers = channel.getRemoteService(ILineNumbers.class);
srv_disassembly = channel.getRemoteService(IDisassembly.class);
srv_path_map = channel.getRemoteService(IPathMap.class);
srv_memory_map = channel.getRemoteService(IMemoryMap.class);
srv_context_query = channel.getRemoteService(IContextQuery.class);
}
public void start() {
if (srv_run_ctrl == null) {
test_suite.done(this, null);
}
else {
if (srv_breakpoints != null) srv_breakpoints.addListener(bp_listener);
runTest();
}
}
private void runTest() {
if (!test_suite.isActive(this)) return;
if (!path_map_done) {
setPathMap();
return;
}
if (!mem_map_done) {
setMemMap();
return;
}
if (test_list == null) {
getTestList();
return;
}
if (!bp_reset_done) {
resetBreakpoints();
return;
}
if (test_id != null) {
if (test_ctx_id == null) {
startTestContext();
return;
}
if (test_context == null) {
getTestContext();
return;
}
if (sym_list.isEmpty()) {
getSymbols();
return;
}
if (!data_bp_area_done) {
getDataBPFile();
return;
}
if (bp_capabilities == null) {
getBreakpointCapabilities();
return;
}
if (!bp_set_done) {
iniBreakpoints();
return;
}
}
if (!done_get_state) {
assert get_state_cmds.isEmpty();
assert threads.isEmpty();
assert running.isEmpty();
assert suspended.isEmpty();
getContextState(test_ctx_id);
return;
}
if (srv_disassembly != null && !done_disassembly) {
assert get_state_cmds.isEmpty();
assert disassembly_lines.isEmpty();
getDisassemlyLines();
return;
}
if (test_id != null) {
if (!bp_change_done) {
changeBreakpoint5();
return;
}
if (!mem_map_test_done) {
runMemoryMapTest();
return;
}
assert resume_cnt == 0;
assert !all_setup_done;
all_setup_done = true;
for (SuspendedContext s : suspended.values()) resume(s.id);
}
else if (suspended.size() > 0) {
final int test_cnt = suspended.size();
Runnable done = new Runnable() {
int done_cnt;
public void run() {
done_cnt++;
if (done_cnt == test_cnt) {
exit(null);
}
}
};
for (SuspendedContext sc : suspended.values()) runRegistersTest(sc, done);
}
else {
exit(null);
}
}
private void getTestList() {
if (srv_diag == null) {
test_list = new String[0];
runTest();
return;
}
srv_diag.getTestList(new IDiagnostics.DoneGetTestList() {
public void doneGetTestList(IToken token, Throwable error, String[] list) {
if (error != null) {
exit(error);
}
else {
if (list == null) list = new String[0];
if (list.length > 0) test_id = list[rnd.nextInt(list.length)];
test_list = list;
runTest();
}
}
});
}
private void setPathMap() {
if (srv_path_map == null || path_map == null) {
path_map_done = true;
runTest();
return;
}
srv_path_map.set(path_map.toArray(new PathMapRule[path_map.size()]), new IPathMap.DoneSet() {
public void doneSet(IToken token, Exception error) {
if (error != null) {
exit(error);
}
else {
path_map_done = true;
runTest();
}
}
});
}
private void setMemMap() {
if (mem_map == null || mem_map.size() == 0) {
mem_map_done = true;
runTest();
return;
}
final Set<IToken> cmds = new HashSet<IToken>();
for (String id : mem_map.keySet()) {
ArrayList<MemoryRegion> l = mem_map.get(id);
cmds.add(srv_memory_map.set(id, l.toArray(new MemoryRegion[l.size()]), new IMemoryMap.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (error instanceof IErrorReport) {
IErrorReport e = (IErrorReport)error;
if (e.getErrorCode() == IErrorReport.TCF_ERROR_INV_CONTEXT) error = null;
}
if (error != null) {
exit(error);
}
else if (cmds.size() == 0) {
mem_map_done = true;
runTest();
}
}
}));
}
assert cmds.size() > 0;
}
private void resetBreakpoints() {
if (srv_breakpoints == null) {
bp_reset_done = true;
runTest();
return;
}
// Reset breakpoint list (previous tests might left breakpoints)
srv_breakpoints.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) {
exit(error);
return;
}
bp_reset_done = true;
runTest();
}
});
}
private void getBreakpointCapabilities() {
if (srv_breakpoints == null) {
bp_capabilities = new HashMap<String,Object>();
runTest();
return;
}
srv_breakpoints.getCapabilities(test_ctx_id, new IBreakpoints.DoneGetCapabilities() {
public void doneGetCapabilities(IToken token, Exception error, Map<String,Object> capabilities) {
if (!test_suite.isActive(TestRCBP1.this)) return;
if (error != null) {
exit(error);
return;
}
Boolean l = (Boolean)capabilities.get(IBreakpoints.CAPABILITY_LOCATION);
Boolean c = (Boolean)capabilities.get(IBreakpoints.CAPABILITY_CONDITION);
if (l == null || !l) {
exit(new Exception("Breakpoints service does not support \"Location\" attribute"));
return;
}
if (c == null || !c) {
exit(new Exception("Breakpoints service does not support \"Condition\" attribute"));
return;
}
bp_capabilities = capabilities;
runTest();
}
});
}
private void startTestContext() {
srv_diag.runTest(test_id, new IDiagnostics.DoneRunTest() {
public void doneRunTest(IToken token, Throwable error, String context_id) {
if (error != null) {
exit(error);
}
else if (test_suite.isActive(TestRCBP1.this)) {
assert test_ctx_id == null;
test_ctx_id = context_id;
if (pending_cancel != null) {
exit(null);
}
else {
runTest();
}
}
}
});
}
private void getTestContext() {
srv_run_ctrl.getContext(test_ctx_id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, RunControlContext context) {
if (test_suite.cancel) return;
if (error != null) {
exit(error);
return;
}
test_context = context;
assert test_ctx_id.equals(context.getID());
srv_run_ctrl.addListener(TestRCBP1.this);
runTest();
}
});
}
private void getSymbols() {
final HashMap<IToken,String> cmds = new HashMap<IToken,String>();
IDiagnostics.DoneGetSymbol done = new IDiagnostics.DoneGetSymbol() {
public void doneGetSymbol(IToken token, Throwable error, ISymbol symbol) {
String name = cmds.remove(token);
if (error != null) {
exit(error);
return;
}
if (!test_suite.isActive(TestRCBP1.this)) return;
assert test_ctx_id != null;
if (symbol == null) {
exit(new Exception("Symbol must not be NULL: " + name));
}
else if (!symbol.isAbs()) {
exit(new Exception("Symbol must be absolute: " + name));
}
else if (symbol.getValue() == null || symbol.getValue().longValue() == 0) {
exit(new Exception("Symbol value must not be NULL: " + name));
}
else {
sym_list.put(name, symbol);
if (cmds.isEmpty()) runTest();
}
}
};
String[] syms = {
"tcf_test_func0",
"tcf_test_func1",
"tcf_test_func2",
"tcf_test_func3",
"tcf_test_array"
};
String prs = test_context.getProcessID();
for (String name : syms) cmds.put(srv_diag.getSymbol(prs, name, done), name);
}
private void getDataBPFile() {
ISymbol sym = sym_list.get("tcf_test_func3");
if (sym == null || srv_line_numbers == null) {
data_bp_area_done = true;
runTest();
return;
}
srv_line_numbers.mapToSource(test_ctx_id, sym.getValue(), sym.getValue().longValue() + 1, new ILineNumbers.DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, CodeArea[] areas) {
if (error != null) {
exit(error);
}
else {
if (areas != null && areas.length > 0) data_bp_area = areas[0];
data_bp_area_done = true;
runTest();
}
}
});
}
@SuppressWarnings("unchecked")
private void iniBreakpoints() {
assert !bp_set_done;
assert bp_list.isEmpty();
Map<String,Object> m[] = new Map[10];
for (int i = 0; i < m.length; i++) {
m[i] = new HashMap<String,Object>();
m[i].put(IBreakpoints.PROP_ID, "TcfTestBP" + i + "" + channel_id);
m[i].put(IBreakpoints.PROP_ENABLED, true);
switch (i) {
case 0:
m[i].put(IBreakpoints.PROP_LOCATION, sym_list.get("tcf_test_func0").getValue().toString());
// Condition is always true
m[i].put(IBreakpoints.PROP_CONDITION, "$thread!=\"\"");
break;
case 1:
m[i].put(IBreakpoints.PROP_LOCATION, sym_list.get("tcf_test_func0").getValue().toString());
// Condition is always false
m[i].put(IBreakpoints.PROP_CONDITION, "$thread==\"\"");
break;
case 2:
// Second breakpoint at same address
m[i].put(IBreakpoints.PROP_LOCATION, "tcf_test_func0");
break;
case 3:
// Location is an expression
m[i].put(IBreakpoints.PROP_LOCATION, "(31+1)/16+tcf_test_func1-2");
// Condition is always true
m[i].put(IBreakpoints.PROP_CONDITION, "tcf_test_func0!=tcf_test_func1");
break;
case 4:
// Disabled breakpoint
m[i].put(IBreakpoints.PROP_LOCATION, "tcf_test_func2");
m[i].put(IBreakpoints.PROP_ENABLED, false);
break;
case 5:
// Breakpoint that will be enabled with "enable" command
m[i].put(IBreakpoints.PROP_LOCATION, "tcf_test_func2");
m[i].put(IBreakpoints.PROP_ENABLED, false);
break;
case 6:
m[i].put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
break;
case 7:
// Data breakpoint
m[i].put(IBreakpoints.PROP_LOCATION, "&tcf_test_char");
m[i].put(IBreakpoints.PROP_ACCESS_MODE, IBreakpoints.ACCESSMODE_WRITE);
Number ca = (Number)bp_capabilities.get(IBreakpoints.CAPABILITY_ACCESS_MODE);
if (data_bp_area != null && ca != null && (ca.intValue() & IBreakpoints.ACCESSMODE_WRITE) != 0) {
m[i].put(IBreakpoints.PROP_FILE, data_bp_area.file);
m[i].put(IBreakpoints.PROP_LINE, data_bp_area.start_line);
data_bp_id = (String)m[i].get(IBreakpoints.PROP_ID);
}
else {
m[i].put(IBreakpoints.PROP_ENABLED, false);
}
break;
case 8:
// Temporary breakpoint
// It will be enabled when we get main thread ID
m[i].put(IBreakpoints.PROP_LOCATION, "tcf_test_func3");
m[i].put(IBreakpoints.PROP_ENABLED, false);
Boolean ct = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_TEMPORARY);
if (ct != null && ct.booleanValue()) {
m[i].put(IBreakpoints.PROP_TEMPORARY, true);
temp_bp_id = (String)m[i].get(IBreakpoints.PROP_ID);
}
break;
case 9:
// Invalid breakpoint that should not be planted
m[i].put("Unknown property", "Unknown value");
inv_bp_id = (String)m[i].get(IBreakpoints.PROP_ID);
break;
}
bp_list.put((String)m[i].get(IBreakpoints.PROP_ID), m[i]);
}
srv_breakpoints.set(m, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
assert !bp_set_done;
bp_set_done = true;
if (error != null) {
exit(error);
return;
}
runTest();
}
});
}
private void getContextState(final String id) {
get_state_cmds.add(srv_run_ctrl.getChildren(id, new IRunControl.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] contexts) {
get_state_cmds.remove(token);
if (test_suite.cancel) return;
if (error != null) {
exit(error);
return;
}
for (String s : contexts) getContextState(s);
if (get_state_cmds.isEmpty()) doneContextState();
}
}));
if (id == null) return;
get_state_cmds.add(srv_run_ctrl.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, RunControlContext ctx) {
get_state_cmds.remove(token);
if (test_suite.cancel) return;
if (error != null) {
exit(error);
return;
}
if (test_id != null) {
assert test_ctx_id != null;
assert isMyContext(ctx);
for (ITCFTest t : test_suite.getActiveTests()) {
if (t != TestRCBP1.this && t instanceof TestRCBP1 && ((TestRCBP1)t).threads.get(id) != null) {
exit(new Exception("Invalid or missing 'CreatorID' context attribute.\nContext: " + ctx));
return;
}
}
}
if (ctx.hasState()) {
threads.put(id, ctx);
get_state_cmds.add(ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error,
boolean susp, String pc, String reason,
Map<String, Object> params) {
get_state_cmds.remove(token);
if (test_suite.cancel) return;
if (error != null) {
exit(new Exception("Cannot get context state", error));
return;
}
if (!susp) {
if (suspended.get(id) != null) {
exit(new Exception("Invalid result of getState command"));
return;
}
running.add(id);
}
else {
assert threads.get(id) != null;
if (running.contains(id)) {
exit(new Exception("Invalid result of getState command"));
return;
}
SuspendedContext sc = suspended.get(id);
if (sc != null && sc.pc != null && !sc.pc.equals(pc)) {
exit(new Exception("Invalid result of getState command: invalid PC. Context: " + id));
return;
}
if (sc != null && sc.reason != null && !sc.reason.equals(reason)) {
exit(new Exception("Invalid result of getState command: invalid suspend reason. Context: " + id));
return;
}
if (test_id != null && "Breakpoint".equals(reason)) {
exit(new Exception("Invalid suspend reason of main thread " +
id + " after test start: " + reason + " " + pc));
return;
}
assert !done_get_state;
suspended.put(id, new SuspendedContext(id, pc, reason, params));
}
if (get_state_cmds.isEmpty()) doneContextState();
}
}));
}
if (get_state_cmds.isEmpty()) doneContextState();
}
}));
}
private void doneContextState() {
assert !done_get_state;
assert get_state_cmds.isEmpty();
assert resume_cnt == 0;
assert threads.size() == suspended.size() + running.size();
done_get_state = true;
runTest();
}
private void getDisassemlyLines() {
for (final String id : suspended.keySet()) {
SuspendedContext sc = suspended.get(id);
get_state_cmds.add(srv_disassembly.getCapabilities(id, new IDisassembly.DoneGetCapabilities() {
public void doneGetCapabilities(IToken token, Throwable error, Map<String,Object>[] arr) {
get_state_cmds.remove(token);
if (error != null) {
exit(error);
}
else {
disassembly_capabilities.put(id, arr);
if (get_state_cmds.isEmpty()) doneDisassembly();
}
}
}));
if (sc.pc == null) {
disassembly_lines.put(id, new IDisassemblyLine[0]);
continue;
}
BigInteger pc = new BigInteger(sc.pc);
get_state_cmds.add(srv_disassembly.disassemble(id, pc, 1, null, new IDisassembly.DoneDisassemble() {
public void doneDisassemble(IToken token, Throwable error, IDisassemblyLine[] arr) {
get_state_cmds.remove(token);
if (error != null) {
exit(error);
}
else {
disassembly_lines.put(id, arr);
if (get_state_cmds.isEmpty()) doneDisassembly();
}
}
}));
}
if (get_state_cmds.isEmpty()) doneDisassembly();
}
private void doneDisassembly() {
assert !done_disassembly;
assert get_state_cmds.isEmpty();
if (!test_suite.isActive(TestRCBP1.this)) return;
assert suspended.size() == disassembly_lines.size();
done_disassembly = true;
runTest();
}
private void changeBreakpoint5() {
assert !bp_change_done;
final String bp_id = "TcfTestBP5" + channel_id;
final Map<String,Object> m = bp_list.get(bp_id);
ArrayList<String> l = new ArrayList<String>();
l.add(test_context.getProcessID());
Boolean ci = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_CONTEXT_IDS);
if (ci != null && ci) m.put(IBreakpoints.PROP_CONTEXT_IDS, l);
Boolean sg = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_STOP_GROUP);
if (sg != null && sg) m.put(IBreakpoints.PROP_STOP_GROUP, l);
StringBuffer bf = new StringBuffer();
for (String id : threads.keySet()) {
if (bf.length() > 0) bf.append(" || ");
bf.append("$thread==\"");
bf.append(id);
bf.append('"');
}
m.put(IBreakpoints.PROP_CONDITION, bf.toString());
bp_change_cmds.add(srv_breakpoints.change(m, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
bp_change_cmds.remove(token);
bp_change_done = true;
if (error != null) exit(error);
}
}));
srv_breakpoints.getIDs(new IBreakpoints.DoneGetIDs() {
public void doneGetIDs(IToken token, Exception error, String[] ids) {
if (error != null) {
exit(error);
return;
}
if (!bp_change_done) {
exit(new Exception("Invalid responce order"));
return;
}
HashSet<String> s = new HashSet<String>();
for (String id : ids) s.add(id);
if (ids.length != s.size()) {
exit(new Exception("Invalis BP list: " + ids));
return;
}
for (String id : bp_list.keySet()) {
if (!s.contains(id)) {
exit(new Exception("BP is not listed by Breakpoints.getIDs: " + id));
return;
}
}
}
});
for (final String id : bp_list.keySet()) {
srv_breakpoints.getProperties(id, new IBreakpoints.DoneGetProperties() {
public void doneGetProperties(IToken token, Exception error, Map<String,Object> properties) {
if (error != null) {
exit(error);
return;
}
HashMap<String,Object> m0 = new HashMap<String,Object>(properties);
HashMap<String,Object> m1 = (HashMap<String,Object>)bp_list.get(id);
if (m0.get(IBreakpoints.PROP_ENABLED) == null) m0.put(IBreakpoints.PROP_ENABLED, false);
if (m1.get(IBreakpoints.PROP_ENABLED) == null) m1.put(IBreakpoints.PROP_ENABLED, false);
if (!m1.equals(m0)) {
exit(new Exception("Invalid data returned by Breakpoints.getProperties: " + m0 + " != " + m1));
return;
}
}
});
srv_breakpoints.getStatus(id, new IBreakpoints.DoneGetStatus() {
public void doneGetStatus(IToken token, Exception error, Map<String,Object> status) {
if (error != null) {
exit(error);
return;
}
}
});
}
Protocol.sync(new Runnable() {
public void run() {
if (!test_suite.isActive(TestRCBP1.this)) return;
if (!bp_change_done) {
exit(new Exception("Protocol.sync() test failed"));
return;
}
m.put(IBreakpoints.PROP_ENABLED, true);
srv_breakpoints.enable(new String[]{ bp_id }, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) exit(error);
}
});
bp_sync_done = true;
runTest();
}
});
}
private void changeBreakpoint6() {
assert bp_change_done;
if (threads.size() < 5) return;
final String bp_id = "TcfTestBP6" + channel_id;
final Map<String,Object> m = bp_list.get(bp_id);
ArrayList<String> l = new ArrayList<String>();
for (String id : threads.keySet()) l.add(id);
m.remove(IBreakpoints.PROP_CONTEXT_IDS);
m.remove(IBreakpoints.PROP_STOP_GROUP);
m.remove(IBreakpoints.PROP_CONTEXT_QUERY);
m.remove(IBreakpoints.PROP_CONDITION);
if (rnd.nextBoolean()) {
Boolean b = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_CONTEXT_IDS);
if (b != null && b) m.put(IBreakpoints.PROP_CONTEXT_IDS, l);
}
if (rnd.nextBoolean()) {
Boolean b = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_STOP_GROUP);
if (b != null && b) m.put(IBreakpoints.PROP_STOP_GROUP, l);
}
if (rnd.nextBoolean()) {
Boolean b = (Boolean)bp_capabilities.get(IBreakpoints.CAPABILITY_CONTEXT_QUERY);
if (b != null && b) {
String q = "ID=\"" + test_context.getProcessID() + "\"/HasState=true";
m.put(IBreakpoints.PROP_CONTEXT_QUERY, q);
}
}
if (rnd.nextBoolean()) {
StringBuffer bf = new StringBuffer();
for (String id : threads.keySet()) {
if (bf.length() > 0) bf.append(" || ");
bf.append("$thread==\"");
bf.append(id);
bf.append('"');
}
m.put(IBreakpoints.PROP_CONDITION, bf.toString());
}
bp_change_cmds.add(srv_breakpoints.change(m, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
bp_change_cmds.remove(token);
if (error != null) exit(error);
}
}));
}
public void containerResumed(String[] context_ids) {
for (String id : context_ids) contextResumed(id);
}
public void containerSuspended(String context, String pc,
String reason, Map<String, Object> params,
String[] suspended_ids) {
for (String id : suspended_ids) {
if (id.equals(context)) continue;
contextSuspended(id, null, null, null);
}
contextSuspended(context, pc, reason, params);
}
public void contextAdded(RunControlContext[] contexts) {
for (RunControlContext ctx : contexts) {
final String id = ctx.getID();
if (threads.get(id) != null) {
exit(new Exception("Invalid contextAdded event:\nContext: " + ctx));
return;
}
if (isMyContext(ctx)) {
for (ITCFTest t : test_suite.getActiveTests()) {
if (t instanceof TestRCBP1 && ((TestRCBP1)t).threads.get(id) != null) {
exit(new Exception("Invalid or missing 'CreatorID' context attribute.\nContext: " + ctx));
return;
}
}
if (threads.size() > 0 && !all_setup_done) {
assert !canResume(id);
exit(new Exception("Unexpected contextAdded event\nContext: " + ctx));
return;
}
if (srv_context_query != null) {
srv_context_query.getAttrNames(new IContextQuery.DoneGetAttrNames() {
public void doneGetAttrNames(IToken token, Exception error, String[] names) {
if (error instanceof IErrorReport &&
((IErrorReport)error).getErrorCode() == IErrorReport.TCF_ERROR_INV_COMMAND) {
// Ignore
}
else if (error != null) {
exit(error);
}
else {
StringBuffer bf = new StringBuffer();
bf.append('"');
int l = id.length();
for (int i = 0; i < l; i++) {
char ch = id.charAt(i);
if (ch == '"' || ch == '\\') bf.append('\\');
bf.append(ch);
}
bf.append('"');
String v = bf.toString();
for (String nm : names) {
if (nm.equals("ID")) {
String s = null;
switch (rnd.nextInt(4)) {
case 0: s = "ID=" + v; break;
case 1: s = "**/ID=" + v; break;
case 2: s = "/**/ID=" + v; break;
case 3: s = "ID=" + v + ",id=" + v; break;
}
srv_context_query.query(s, new IContextQuery.DoneQuery() {
public void doneQuery(IToken token, Exception error, String[] contexts) {
if (error != null) {
exit(error);
}
else if (contexts == null || contexts.length != 1) {
exit(new Exception("Invalid result length of ContextQuery.query command"));
}
else if (!id.equals(contexts[0])) {
exit(new Exception("Invalid ID returned by ContextQuery.query command"));
}
}
});
switch (rnd.nextInt(2)) {
case 0: s = "ID=ID="; break;
case 1: s = "ID=ID=ID"; break;
}
srv_context_query.query(s, new IContextQuery.DoneQuery() {
public void doneQuery(IToken token, Exception error, String[] contexts) {
if (error == null) {
exit(new Exception("Invalid ContextQuery.query responce: error expected"));
}
}
});
return;
}
}
exit(new Exception("ContextQuery.getAttrNames result must include 'ID'"));
}
}
});
}
if (ctx.hasState()) {
threads.put(id, ctx);
if (!done_get_state) {
getContextState(id);
}
else {
running.add(id);
}
}
}
}
}
public void contextChanged(RunControlContext[] contexts) {
for (RunControlContext ctx : contexts) {
String id = ctx.getID();
if (id.equals(test_ctx_id)) test_context = ctx;
if (threads.get(id) != null) {
assert isMyContext(ctx);
threads.put(id, ctx);
}
}
}
public void contextException(String id, String msg) {
RunControlContext ctx = threads.get(id);
if (ctx != null) {
assert isMyContext(ctx);
exit(new Exception("Context exception: " + msg));
}
}
public void contextRemoved(String[] contexts) {
for (String id : contexts) {
if (suspended.get(id) != null) {
exit(new Exception("Invalid contextRemoved event"));
return;
}
running.remove(id);
if (threads.remove(id) != null && threads.isEmpty()) {
if (bp_cnt != 40) {
exit(new Exception("Test main thread breakpoint count = " + bp_cnt + ", expected 40"));
}
if (data_bp_id != null && data_bp_cnt != 10) {
exit(new Exception("Test main thread data breakpoint count = " + data_bp_cnt + ", expected 10"));
}
if (temp_bp_id != null && temp_bp_cnt != 1) {
exit(new Exception("Temporary breakpoint count = " + temp_bp_cnt + ", expected 1"));
}
srv_run_ctrl.removeListener(this);
// Reset breakpoint list
bp_list.clear();
srv_breakpoints.set(null, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
exit(error);
}
});
}
}
}
public void contextResumed(String id) {
IRunControl.RunControlContext ctx = threads.get(id);
if (ctx == null) return;
assert isMyContext(ctx);
if (!ctx.hasState()) {
exit(new Exception("Resumed event for context that HasState = false"));
return;
}
SuspendedContext sc = suspended.remove(id);
if (!done_get_state || sc == null || !sc.ok_to_resume || sc.get_state_pending && ctx.getRCGroup() == null) {
assert !canResume(id);
exit(new Exception("Unexpected contextResumed event: " + id));
return;
}
if (isMyBreakpoint(sc)) suspended_prev.put(id, sc);
running.add(id);
}
private long getSymAddr(String sym) {
return sym_list.get(sym).getValue().longValue();
}
private String toSymName(long addr) {
for (String name : sym_list.keySet()) {
if (getSymAddr(name) == addr) return name;
}
return "0x" + Long.toHexString(addr);
}
private void checkSuspendedContext(SuspendedContext sc, String sym) {
long pc = Long.parseLong(sc.pc);
long ss = getSymAddr(sym);
if (pc != ss || !"Breakpoint".equals(sc.reason)) {
exit(new Exception("Invalid contextSuspended event: " +
sc.id + " '" + toSymName(pc) + "' " + sc.pc + " " + sc.reason +
", expected breakpoint at '" + sym + "' " + ss));
}
String bp_id = null;
if (sc.params != null) {
Object ids = sc.params.get(IRunControl.STATE_BREAKPOINT_IDS);
if (ids != null) {
@SuppressWarnings("unchecked")
Collection<String> c = (Collection<String>)ids;
HashSet<String> set = new HashSet<String>();
for (String id : c) {
if (!set.add(id)) {
exit(new Exception("Invalid value of 'BPs' attribute: duplicate items"));
return;
}
if (bp_list.get(id) != null) {
bp_id = id;
break;
}
}
if (bp_id == null) {
exit(new Exception("Invalid value of 'BPs' attribute in a context state"));
}
}
}
}
private void checkSuspendedContext(final SuspendedContext sc) {
boolean my_breakpoint = isMyBreakpoint(sc);
if (main_thread_id == null && my_breakpoint) {
// Process main thread should be the first to hit a breakpoint in the test
if (!done_get_state) {
exit(new Exception("Unexpeceted breakpoint hit"));
return;
}
main_thread_id = sc.id;
if (temp_bp_id != null) {
final Map<String,Object> m = bp_list.get(temp_bp_id);
ArrayList<String> l = new ArrayList<String>();
l.add(main_thread_id);
m.put(IBreakpoints.PROP_CONTEXT_IDS, l);
m.put(IBreakpoints.PROP_ENABLED, true);
bp_change_cmds.add(srv_breakpoints.change(m, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
bp_change_cmds.remove(token);
if (error != null) exit(error);
}
}));
}
}
if (main_thread_id == null) {
if (all_setup_done) resume(sc.id);
return;
}
if (my_breakpoint) {
if (sc.id.equals(main_thread_id)) bp_cnt++;
SuspendedContext sp = suspended_prev.get(sc.id);
String sp_sym = sp == null ? null : toSymName(Long.parseLong(sp.pc));
if (sp == null) {
checkSuspendedContext(sc, "tcf_test_func0");
}
else if ("tcf_test_func0".equals(sp_sym)) {
checkSuspendedContext(sc, "tcf_test_func1");
}
else if ("tcf_test_func1".equals(sp_sym)) {
if (sc.id.equals(main_thread_id)) {
checkSuspendedContext(sc, "tcf_test_func2");
}
else {
checkSuspendedContext(sc, "tcf_test_func3");
}
}
else if ("tcf_test_func2".equals(sp_sym)) {
checkSuspendedContext(sc, "tcf_test_func3");
}
else if ("tcf_test_func3".equals(sp_sym)) {
checkSuspendedContext(sc, "tcf_test_func0");
}
if (isMyTempBreakpoint(sc)) temp_bp_cnt++;
}
else if (isMyDataBreakpoint(sc)) {
if (sc.id.equals(main_thread_id)) data_bp_cnt++;
}
if (!all_setup_done) return;
if (!test_suite.isActive(this)) return;
Runnable done = new Runnable() {
public void run() {
if (suspended.get(sc.id) == sc) resume(sc.id);
}
};
if (my_breakpoint) {
switch (rnd.nextInt(6)) {
case 0:
runMemoryTest(sc, done);
break;
case 1:
runRegistersTest(sc, done);
break;
case 2:
runLineNumbersTest(sc, done);
break;
case 3:
runSymbolsTest(sc, done);
break;
case 4:
changeBreakpoint6();
done.run();
break;
default:
done.run();
break;
}
}
else {
done.run();
}
}
private boolean isMyContext(IRunControl.RunControlContext ctx) {
// Check if the context was created by this test
if (test_ctx_id == null) return false;
return test_ctx_id.equals(ctx.getID()) ||
test_ctx_id.equals(ctx.getParentID()) ||
test_ctx_id.equals(ctx.getCreatorID());
}
private boolean isMyBreakpoint(SuspendedContext sc) {
// Check if the context is suspended by one of our breakpoints
if (!"Breakpoint".equals(sc.reason)) return false;
long pc = Long.parseLong(sc.pc);
for (IDiagnostics.ISymbol sym : sym_list.values()) {
if (pc == sym.getValue().longValue()) return true;
}
return false;
}
private boolean isMyDataBreakpoint(SuspendedContext sc) {
// Check if the context is suspended by our data breakpoints
if (data_bp_id == null) return false;
if (!"Breakpoint".equals(sc.reason)) return false;
if (sc.params == null) return false;
Object ids = sc.params.get(IRunControl.STATE_BREAKPOINT_IDS);
if (ids != null) {
@SuppressWarnings("unchecked")
Collection<String> c = (Collection<String>)ids;
if (c.contains(data_bp_id)) return true;
}
return false;
}
private boolean isMyTempBreakpoint(SuspendedContext sc) {
// Check if the context is suspended by our temporary breakpoint
if (temp_bp_id == null) return false;
if (!"Breakpoint".equals(sc.reason)) return false;
if (sc.params == null) return false;
Object ids = sc.params.get(IRunControl.STATE_BREAKPOINT_IDS);
if (ids != null) {
@SuppressWarnings("unchecked")
Collection<String> c = (Collection<String>)ids;
if (c.contains(temp_bp_id)) return true;
}
return false;
}
public void contextSuspended(final String id, String pc, String reason, Map<String, Object> params) {
IRunControl.RunControlContext ctx = threads.get(id);
if (ctx == null) return;
assert isMyContext(ctx);
if (!ctx.hasState()) {
exit(new Exception("Suspended event for context that HasState = false"));
return;
}
running.remove(id);
SuspendedContext sc = suspended.get(id);
if (sc != null) {
if (done_get_state || pc != null && !sc.pc.equals(pc) || reason != null && !sc.reason.equals(reason)) {
exit(new Exception("Invalid contextSuspended event"));
return;
}
}
else {
sc = new SuspendedContext(id, pc, reason, params);
assert !done_get_state || done_disassembly || srv_disassembly == null;
suspended.put(id, sc);
}
if (!all_setup_done) return;
assert get_state_cmds.size() == 0;
assert suspended.get(id) == sc;
assert !sc.get_state_pending;
sc.get_state_pending = true;
final SuspendedContext sc0 = sc;
ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean susp,
String pc, String reason, Map<String, Object> params) {
if (error != null) {
exit(new Exception("Cannot get context state", error));
}
else if (suspended.get(id) != sc0) {
exit(new Exception("Context resumed before RunControl.getState result"));
}
else if (!susp) {
exit(new Exception("Invalid RunControl.getState result"));
}
else if (pc == null || pc.equals("0")) {
exit(new Exception("Invalid PC returned by RunControl.getState"));
}
else if (test_suite.isActive(TestRCBP1.this)) {
SuspendedContext sc = suspended.get(id);
assert sc.get_state_pending;
sc.get_state_pending = false;
if (sc.pc == null || sc.reason == null) {
sc = new SuspendedContext(id, pc, reason, params);
assert !done_get_state || done_disassembly || srv_disassembly == null;
suspended.put(id, sc);
}
else if (!sc.pc.equals(pc) || !sc.reason.equals(reason)) {
exit(new Exception("Invalid RunControl.getState result"));
return;
}
checkSuspendedContext(sc);
}
}
});
}
public boolean canResume(String id) {
if (test_ctx_id != null && threads.size() == 0)
// Don't know yet neither my thread IDs nor my RC group.
return false;
IRunControl.RunControlContext ctx = test_rc.getContext(id);
if (ctx == null) return false;
if (isMyContext(ctx) && (!all_setup_done || threads.get(id) == null))
// My threads should stay suspended until all_setup_done
return false;
String grp = ctx.getRCGroup();
for (IRunControl.RunControlContext x : threads.values()) {
if (x.getID().equals(id) || grp != null && grp.equals(x.getRCGroup())) {
SuspendedContext sc = suspended.get(x.getID());
if (sc == null) return false;
if (!sc.ok_to_resume) return false;
}
}
return true;
}
private void resume(String id) {
assert done_get_state || resume_cnt == 0;
assert bp_sync_done;
assert mem_map_test_done;
resume_cnt++;
SuspendedContext sc = suspended.get(id);
IRunControl.RunControlContext ctx = threads.get(id);
if (ctx != null && sc != null) {
assert !sc.get_state_pending;
assert !sc.ok_to_resume;
sc.ok_to_resume = true;
int rm = IRunControl.RM_RESUME;
if (isMyBreakpoint(sc)) {
rm = rnd.nextInt(6);
if (!ctx.canResume(rm)) rm = IRunControl.RM_RESUME;
}
test_rc.resume(id, rm);
}
}
private void runMemoryTest(final SuspendedContext sc, final Runnable done) {
if (srv_memory == null || test_suite.target_lock) {
Protocol.invokeLater(done);
return;
}
test_suite.target_lock = true;
srv_memory.getContext(test_context.getProcessID(), new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, final MemoryContext mem_ctx) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
if (!test_context.getProcessID().equals(mem_ctx.getID())) {
exit(new Exception("Bad memory context data: invalid ID"));
}
final boolean big_endian = mem_ctx.isBigEndian();
final int addr_size = mem_ctx.getAddressSize();
final byte[] buf = new byte[0x1000];
mem_ctx.get(sym_list.get("tcf_test_array").getValue(), 1, buf, 0, addr_size, 0, new IMemory.DoneMemory() {
public void doneMemory(IToken token, MemoryError error) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
byte[] tmp = new byte[addr_size + 1];
tmp[0] = 0; // Extra byte to avoid sign extension by BigInteger
if (big_endian) {
System.arraycopy(buf, 0, tmp, 1, addr_size);
}
else {
for (int i = 0; i < addr_size; i++) {
tmp[i + 1] = buf[addr_size - i - 1];
}
}
Number mem_address = new BigInteger(tmp);
if (mem_address.longValue() == 0) {
exit(new Exception("Bad value of 'tcf_test_array': " + mem_address));
}
testSetMemoryCommand(sc, mem_ctx, mem_address, buf, done);
}
});
}
});
}
private void testSetMemoryCommand(final SuspendedContext sc,
final IMemory.MemoryContext mem_ctx,
final Number addr, final byte[] buf,
final Runnable done) {
final byte[] data = new byte[buf.length];
rnd.nextBytes(data);
mem_ctx.set(addr, 1, data, 0, data.length, 0, new IMemory.DoneMemory() {
public void doneMemory(IToken token, MemoryError error) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
mem_ctx.get(addr, 1, buf, 0, buf.length, 0, new IMemory.DoneMemory() {
public void doneMemory(IToken token, MemoryError error) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
for (int i = 0; i < data.length; i++) {
if (data[i] != buf[i]) {
exit(new Exception(
"Invalid Memory.get responce: wrong data at offset " + i +
", expected " + data[i] + ", actual " + buf[i]));
return;
}
}
testFillMemoryCommand(sc, mem_ctx, addr, buf, done);
}
});
}
});
}
private void testFillMemoryCommand(final SuspendedContext sc,
final IMemory.MemoryContext mem_ctx,
final Number addr, final byte[] buf,
final Runnable done) {
final byte[] data = new byte[buf.length / 7];
rnd.nextBytes(data);
mem_ctx.fill(addr, 1, data, buf.length, 0, new IMemory.DoneMemory() {
public void doneMemory(IToken token, MemoryError error) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
mem_ctx.get(addr, 1, buf, 0, buf.length, 0, new IMemory.DoneMemory() {
public void doneMemory(IToken token, MemoryError error) {
if (suspended.get(sc.id) != sc) {
test_suite.target_lock = false;
return;
}
if (error != null) {
exit(error);
return;
}
for (int i = 0; i < data.length; i++) {
if (data[i % data.length] != buf[i]) {
exit(new Exception(
"Invalid Memory.get responce: wrong data at offset " + i +
", expected " + data[i % data.length] + ", actual " + buf[i]));
return;
}
}
test_suite.target_lock = false;
done.run();
}
});
}
});
}
private void runRegistersTest(final SuspendedContext sc, final Runnable done) {
if (srv_registers == null) {
Protocol.invokeLater(done);
return;
}
if (regs.get(sc.id) == null) {
final Map<String,IRegisters.RegistersContext> reg_map =
new HashMap<String,IRegisters.RegistersContext>();
regs.put(sc.id, reg_map);
final Set<IToken> cmds = new HashSet<IToken>();
cmds.add(srv_registers.getChildren(sc.id, new IRegisters.DoneGetChildren() {
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) {
regs.remove(sc.id);
return;
}
if (error != null) {
exit(error);
return;
}
for (final String id : context_ids) {
cmds.add(srv_registers.getChildren(id, this));
cmds.add(srv_registers.getContext(id, new IRegisters.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, RegistersContext context) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) {
regs.remove(sc.id);
return;
}
if (error != null) {
exit(error);
return;
}
reg_map.put(id, context);
if (cmds.isEmpty()) {
testGetSetRegisterCommands(sc, done);
}
}
}));
}
}
}));
}
else {
testGetSetRegisterCommands(sc, done);
}
}
private void testGetSetRegisterCommands(final SuspendedContext sc, final Runnable done) {
Map<String,IRegisters.RegistersContext> reg_map = regs.get(sc.id);
final Set<IToken> cmds = new HashSet<IToken>();
if (reg_map.size() > 0) {
String[] ids = reg_map.keySet().toArray(new String[reg_map.size()]);
for (int n = 0; n < 10000 && cmds.size() < 100; n++) {
if (rnd.nextBoolean()) {
String id = ids[rnd.nextInt(ids.length)];
final IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (ctx.isReadOnce()) continue;
+ if (ctx.getSize() == 0) continue;
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, final byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (ctx.getSize() != value.length) {
exit(new Exception("Invalid register value size"));
return;
}
if (ctx.isWriteable() && !ctx.isWriteOnce()) {
cmds.add(ctx.set(value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value1) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
for (int i = 0; i < value.length; i++) {
if (value[i] != value1[i]) {
exit(new Exception("Invalid register value"));
return;
}
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
else {
int data_size = 0;
int l = rnd.nextInt(32);
List<IRegisters.Location> locs = new ArrayList<IRegisters.Location>();
for (int i = 0; i < l; i++) {
String id = ids[rnd.nextInt(ids.length)];
IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (!ctx.isWriteable()) continue;
if (ctx.isReadOnce()) continue;
if (ctx.isWriteOnce()) continue;
if (ctx.getSize() == 0) continue;
int offs = rnd.nextInt(ctx.getSize());
int size = rnd.nextInt(ctx.getSize() - offs) + 1;
locs.add(new IRegisters.Location(id, offs, size));
data_size += size;
}
final int total_size = data_size;
final IRegisters.Location[] loc_arr = locs.toArray(new IRegisters.Location[locs.size()]);
cmds.add(srv_registers.getm(loc_arr, new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error == null && value.length != total_size) {
error = new Exception("Invalid data size in Registers.getm reply");
}
if (error != null) {
exit(error);
return;
}
cmds.add(srv_registers.setm(loc_arr, value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
}
}
if (cmds.isEmpty()) {
done.run();
}
}
private void runLineNumbersTest(SuspendedContext sc, final Runnable done) {
if (srv_line_numbers != null && sc.pc != null) {
BigInteger x = new BigInteger(sc.pc);
BigInteger y = x.add(BigInteger.valueOf(1));
srv_line_numbers.mapToSource(sc.id, x, y, new ILineNumbers.DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, CodeArea[] areas) {
if (error != null) {
exit(error);
return;
}
done.run();
}
});
}
else {
done.run();
}
}
private void runSymbolsTest(final SuspendedContext sc, final Runnable done) {
if (srv_syms != null && sc.pc != null) {
final BigInteger x = new BigInteger(sc.pc);
srv_syms.findByAddr(sc.id, x, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error != null) {
int code = IErrorReport.TCF_ERROR_OTHER;
if (error instanceof IErrorReport) code = ((IErrorReport)error).getErrorCode();
switch (code) {
case IErrorReport.TCF_ERROR_INV_COMMAND:
case IErrorReport.TCF_ERROR_SYM_NOT_FOUND:
done.run();
return;
default:
exit(error);
return;
}
}
srv_syms.getContext(symbol_id, new ISymbols.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, Symbol context) {
if (error != null) {
exit(error);
return;
}
Number addr = context.getAddress();
int size = context.getSize();
if (addr == null) {
exit(new Exception("Missing symbol address attribute"));
return;
}
if (size <= 0) {
exit(new Exception("Invalid symbol size attribute"));
return;
}
BigInteger y = JSON.toBigInteger(addr);
BigInteger z = y.add(BigInteger.valueOf(size));
if (x.compareTo(y) < 0 || x.compareTo(z) >= 0) {
exit(new Exception("Invalid symbol address attribute"));
return;
}
String name = context.getName();
if (name == null) {
done.run();
return;
}
srv_syms.find(sc.id, 0, name, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
if (error != null) {
exit(error);
return;
}
done.run();
}
});
}
});
}
});
}
else {
done.run();
}
}
private String getRandomString() {
int l = rnd.nextInt(512) + 1;
StringBuffer bf = new StringBuffer(l);
for (int i = 0; i < l; i++) {
bf.append((char)(rnd.nextInt(0xffff) + 1));
}
return bf.toString();
}
private void runMemoryMapTest() {
assert !mem_map_test_running;
if (srv_memory_map == null || test_context == null || test_context.getProcessID() == null) {
mem_map_test_done = true;
runTest();
return;
}
mem_map_test_running = true;
final String prs_id = test_context.getProcessID();
srv_memory_map.get(prs_id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, MemoryRegion[] map) {
if (error != null) {
exit(error);
return;
}
final Map<String,Object> props = new HashMap<String,Object>();
final String test_id = "TestRCBP1." + mem_map_region_id++ + "." + prs_id;
props.put(IMemoryMap.PROP_ID, test_id);
if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_ADDRESS, rnd.nextInt(0x10000000));
if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_SIZE, rnd.nextInt(0x10000000));
if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_FLAGS, rnd.nextInt(0x7));
if (rnd.nextBoolean()) {
props.put(IMemoryMap.PROP_FILE_NAME, getRandomString());
if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_SECTION_NAME, getRandomString());
else if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_OFFSET, rnd.nextInt(0x10000000));
if (rnd.nextBoolean()) props.put(IMemoryMap.PROP_BSS, true);
}
List<MemoryRegion> list = new ArrayList<MemoryRegion>();
for (MemoryRegion r : map) {
String id = (String)r.getProperties().get(IMemoryMap.PROP_ID);
if (id != null) list.add(r);
}
final List<MemoryRegion> org_list = new ArrayList<MemoryRegion>(list);
list.add(new TCFMemoryRegion(props));
srv_memory_map.set(prs_id, list.toArray(new MemoryRegion[list.size()]), new IMemoryMap.DoneSet() {
public void doneSet(IToken token, Exception error) {
if (error != null) {
exit(error);
return;
}
srv_memory_map.get(prs_id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, MemoryRegion[] map) {
if (error != null) {
exit(error);
return;
}
int cnt = 0;
for (MemoryRegion r : map) {
String id = (String)r.getProperties().get(IMemoryMap.PROP_ID);
if (!test_id.equals(id)) continue;
for (String p : props.keySet()) {
if (!props.get(p).equals(r.getProperties().get(p))) {
exit(new Error("Invalid value returned for Memory Map region property " + p));
return;
}
}
cnt++;
}
if (cnt != 1) {
exit(new Error("Error adding memory map entry with MemoryMap.set command"));
return;
}
srv_memory_map.set(prs_id, org_list.toArray(new MemoryRegion[org_list.size()]), new IMemoryMap.DoneSet() {
public void doneSet(IToken token, Exception error) {
if (error != null) {
exit(error);
return;
}
mem_map_test_running = false;
mem_map_test_done = true;
runTest();
}
});
}
});
}
});
}
});
}
void cancel(final Runnable done) {
if (srv_run_ctrl != null) srv_run_ctrl.removeListener(this);
if (test_ctx_id == null) {
if (pending_cancel != null) {
exit(null);
}
else {
pending_cancel = done;
}
}
else if (cancel_test_cmd == null) {
cancel_test_cmd = srv_diag.cancelTest(test_ctx_id, new IDiagnostics.DoneCancelTest() {
public void doneCancelTest(IToken token, Throwable error) {
cancel_test_cmd = null;
exit(error);
done.run();
}
});
}
else {
exit(new Exception("Cannot terminate remote test process"));
done.run();
}
}
private void exit(Throwable x) {
if (!test_suite.isActive(this)) return;
if (pending_cancel != null) {
Protocol.invokeLater(pending_cancel);
pending_cancel = null;
}
else {
if (srv_run_ctrl != null) srv_run_ctrl.removeListener(this);
}
if (srv_breakpoints != null) srv_breakpoints.removeListener(bp_listener);
test_suite.done(this, x);
}
}
| true | true | private void testGetSetRegisterCommands(final SuspendedContext sc, final Runnable done) {
Map<String,IRegisters.RegistersContext> reg_map = regs.get(sc.id);
final Set<IToken> cmds = new HashSet<IToken>();
if (reg_map.size() > 0) {
String[] ids = reg_map.keySet().toArray(new String[reg_map.size()]);
for (int n = 0; n < 10000 && cmds.size() < 100; n++) {
if (rnd.nextBoolean()) {
String id = ids[rnd.nextInt(ids.length)];
final IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (ctx.isReadOnce()) continue;
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, final byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (ctx.getSize() != value.length) {
exit(new Exception("Invalid register value size"));
return;
}
if (ctx.isWriteable() && !ctx.isWriteOnce()) {
cmds.add(ctx.set(value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value1) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
for (int i = 0; i < value.length; i++) {
if (value[i] != value1[i]) {
exit(new Exception("Invalid register value"));
return;
}
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
else {
int data_size = 0;
int l = rnd.nextInt(32);
List<IRegisters.Location> locs = new ArrayList<IRegisters.Location>();
for (int i = 0; i < l; i++) {
String id = ids[rnd.nextInt(ids.length)];
IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (!ctx.isWriteable()) continue;
if (ctx.isReadOnce()) continue;
if (ctx.isWriteOnce()) continue;
if (ctx.getSize() == 0) continue;
int offs = rnd.nextInt(ctx.getSize());
int size = rnd.nextInt(ctx.getSize() - offs) + 1;
locs.add(new IRegisters.Location(id, offs, size));
data_size += size;
}
final int total_size = data_size;
final IRegisters.Location[] loc_arr = locs.toArray(new IRegisters.Location[locs.size()]);
cmds.add(srv_registers.getm(loc_arr, new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error == null && value.length != total_size) {
error = new Exception("Invalid data size in Registers.getm reply");
}
if (error != null) {
exit(error);
return;
}
cmds.add(srv_registers.setm(loc_arr, value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
}
}
if (cmds.isEmpty()) {
done.run();
}
}
| private void testGetSetRegisterCommands(final SuspendedContext sc, final Runnable done) {
Map<String,IRegisters.RegistersContext> reg_map = regs.get(sc.id);
final Set<IToken> cmds = new HashSet<IToken>();
if (reg_map.size() > 0) {
String[] ids = reg_map.keySet().toArray(new String[reg_map.size()]);
for (int n = 0; n < 10000 && cmds.size() < 100; n++) {
if (rnd.nextBoolean()) {
String id = ids[rnd.nextInt(ids.length)];
final IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (ctx.isReadOnce()) continue;
if (ctx.getSize() == 0) continue;
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, final byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (ctx.getSize() != value.length) {
exit(new Exception("Invalid register value size"));
return;
}
if (ctx.isWriteable() && !ctx.isWriteOnce()) {
cmds.add(ctx.set(value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
cmds.add(ctx.get(new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value1) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
for (int i = 0; i < value.length; i++) {
if (value[i] != value1[i]) {
exit(new Exception("Invalid register value"));
return;
}
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
else {
int data_size = 0;
int l = rnd.nextInt(32);
List<IRegisters.Location> locs = new ArrayList<IRegisters.Location>();
for (int i = 0; i < l; i++) {
String id = ids[rnd.nextInt(ids.length)];
IRegisters.RegistersContext ctx = reg_map.get(id);
if (!ctx.isReadable()) continue;
if (!ctx.isWriteable()) continue;
if (ctx.isReadOnce()) continue;
if (ctx.isWriteOnce()) continue;
if (ctx.getSize() == 0) continue;
int offs = rnd.nextInt(ctx.getSize());
int size = rnd.nextInt(ctx.getSize() - offs) + 1;
locs.add(new IRegisters.Location(id, offs, size));
data_size += size;
}
final int total_size = data_size;
final IRegisters.Location[] loc_arr = locs.toArray(new IRegisters.Location[locs.size()]);
cmds.add(srv_registers.getm(loc_arr, new IRegisters.DoneGet() {
public void doneGet(IToken token, Exception error, byte[] value) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error == null && value.length != total_size) {
error = new Exception("Invalid data size in Registers.getm reply");
}
if (error != null) {
exit(error);
return;
}
cmds.add(srv_registers.setm(loc_arr, value, new IRegisters.DoneSet() {
public void doneSet(IToken token, Exception error) {
cmds.remove(token);
if (suspended.get(sc.id) != sc) return;
if (error != null) {
exit(error);
return;
}
if (cmds.isEmpty()) {
done.run();
}
}
}));
}
}));
}
}
}
if (cmds.isEmpty()) {
done.run();
}
}
|
diff --git a/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/InitializeCache.java b/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/InitializeCache.java
index dff3461..1aa30d1 100644
--- a/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/InitializeCache.java
+++ b/chunchun/src/jbossas/java/com/jboss/datagrid/chunchun/jsf/InitializeCache.java
@@ -1,231 +1,231 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.jboss.datagrid.chunchun.jsf;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.faces.application.Application;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;
import javax.imageio.ImageIO;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;
import org.infinispan.api.BasicCache;
import com.jboss.datagrid.chunchun.model.Post;
import com.jboss.datagrid.chunchun.model.PostKey;
import com.jboss.datagrid.chunchun.model.User;
import com.jboss.datagrid.chunchun.session.CacheContainerProvider;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
/**
* A JSF listener used to populate the cache with users, posts and user watchers/watching
* people.
*
* @author Martin Gencur
*
*/
public class InitializeCache implements SystemEventListener {
public static final int USER_COUNT = 200;
private static final int SEVEN_DAYS_IN_MILLISECONDS = 7 * 24 * 3600 * 1000;
private Random randomNumber = new Random();
private Logger log = Logger.getLogger(this.getClass().getName());
private CacheContainerProvider provider;
private UserTransaction utx;
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
provider = getContextualInstance(getBeanManagerFromJNDI(), CacheContainerProvider.class);
startup();
}
public void startup() {
BasicCache<String, Object> users = provider.getCacheContainer().getCache("userCache");
BasicCache<PostKey, Object> posts = provider.getCacheContainer().getCache("postCache");
utx = getUserTransactionFromJNDI();
try {
utx.begin();
- for (int i = 1; i != USER_COUNT; i++) {
+ for (int i = 1; i <= USER_COUNT; i++) {
User u = null;
if (i % 2 == 1) {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "user1.jpg"));
} else {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "nophoto.jpg"));
}
String encryptedPass = hashPassword("pass" + i);
u.setPassword(encryptedPass);
// GENERATE POSTS FOR EACH USER
int numGeneratedPosts = 100;
TreeSet<Long> randomTimesSorted = new TreeSet<Long>();
for (int j = 1; j != numGeneratedPosts; j++) {
randomTimesSorted.add(getRandomTime());
}
for (int j = 1; j != numGeneratedPosts; j++) {
long randomTime = randomTimesSorted.pollFirst();
Post t = new Post(u.getUsername(), "Post number " + j + " for user "
+ u.getName() + " at " + new Date(randomTime), randomTime);
// store the post in a cache
posts.put(t.getKey(), t);
u.getPosts().add(t.getKey());
}
// store the user in a cache
users.put(u.getUsername(), u);
}
// GENERATE RANDOM WATCHERS AND WATCHING FOR EACH USER
for (int i = 1; i != USER_COUNT; i++) {
User u = (User) users.get("user" + i);
for (User watcher : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatchers().add(watcher.getUsername());
}
for (User watching : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatching().add(watching.getUsername());
}
users.replace("user" + i, u);
}
utx.commit();
log.info("Successfully imported data!");
} catch (Exception e) {
log.warning("An exception occured while populating the datagrid! Rolling back the transaction");
e.printStackTrace();
if (utx != null) {
try {
utx.rollback();
} catch (Exception e1) {
}
}
}
}
private BufferedImage loadImageFromFile(String fileName) {
BufferedImage image = null;
try {
image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream(fileName));
return image;
} catch (IOException e) {
throw new RuntimeException("Unable to load image from file " + fileName);
}
}
private long getRandomTime() {
// get random time at most 7 days old
return Calendar.getInstance().getTimeInMillis()
- randomNumber.nextInt(SEVEN_DAYS_IN_MILLISECONDS);
}
private Set<User> generateRandomUsers(User forWhom, int count, int outOf) {
BasicCache<String, Object> users = provider.getCacheContainer().getCache("userCache");
Random r = new Random(getRandomTime());
Set<User> result = new HashSet<User>();
while (result.size() != count) {
int id = (r.nextInt(outOf - 1)) + 1; // do not return 0
User u = (User) users.get("user" + id);
if (u != null && u.equals(forWhom))
continue;
result.add(u);
}
return result;
}
public static String hashPassword(String password) {
String hashword = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
BigInteger hash = new BigInteger(1, md5.digest());
hashword = hash.toString(16);
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException("No MD5 algorithm found for password encryption!");
}
return hashword;
}
private BeanManager getBeanManagerFromJNDI() {
InitialContext context;
Object result;
try {
context = new InitialContext();
result = context.lookup("java:comp/BeanManager");
} catch (NamingException e) {
throw new RuntimeException("BeanManager could not be found in JNDI", e);
}
return (BeanManager) result;
}
private UserTransaction getUserTransactionFromJNDI() {
InitialContext context;
Object result;
try {
context = new InitialContext();
result = context.lookup("java:comp/UserTransaction");
} catch (NamingException ex) {
throw new RuntimeException("UserTransaction could not be found in JNDI", ex);
}
return (UserTransaction) result;
}
@SuppressWarnings("unchecked")
public <T> T getContextualInstance(final BeanManager manager, final Class<T> type) {
T result = null;
Bean<T> bean = (Bean<T>) manager.resolve(manager.getBeans(type));
if (bean != null) {
CreationalContext<T> context = manager.createCreationalContext(bean);
if (context != null) {
result = (T) manager.getReference(bean, type, context);
}
}
return result;
}
@Override
public boolean isListenerForSource(Object source) {
return source instanceof Application;
}
}
| true | true | public void startup() {
BasicCache<String, Object> users = provider.getCacheContainer().getCache("userCache");
BasicCache<PostKey, Object> posts = provider.getCacheContainer().getCache("postCache");
utx = getUserTransactionFromJNDI();
try {
utx.begin();
for (int i = 1; i != USER_COUNT; i++) {
User u = null;
if (i % 2 == 1) {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "user1.jpg"));
} else {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "nophoto.jpg"));
}
String encryptedPass = hashPassword("pass" + i);
u.setPassword(encryptedPass);
// GENERATE POSTS FOR EACH USER
int numGeneratedPosts = 100;
TreeSet<Long> randomTimesSorted = new TreeSet<Long>();
for (int j = 1; j != numGeneratedPosts; j++) {
randomTimesSorted.add(getRandomTime());
}
for (int j = 1; j != numGeneratedPosts; j++) {
long randomTime = randomTimesSorted.pollFirst();
Post t = new Post(u.getUsername(), "Post number " + j + " for user "
+ u.getName() + " at " + new Date(randomTime), randomTime);
// store the post in a cache
posts.put(t.getKey(), t);
u.getPosts().add(t.getKey());
}
// store the user in a cache
users.put(u.getUsername(), u);
}
// GENERATE RANDOM WATCHERS AND WATCHING FOR EACH USER
for (int i = 1; i != USER_COUNT; i++) {
User u = (User) users.get("user" + i);
for (User watcher : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatchers().add(watcher.getUsername());
}
for (User watching : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatching().add(watching.getUsername());
}
users.replace("user" + i, u);
}
utx.commit();
log.info("Successfully imported data!");
} catch (Exception e) {
log.warning("An exception occured while populating the datagrid! Rolling back the transaction");
e.printStackTrace();
if (utx != null) {
try {
utx.rollback();
} catch (Exception e1) {
}
}
}
}
| public void startup() {
BasicCache<String, Object> users = provider.getCacheContainer().getCache("userCache");
BasicCache<PostKey, Object> posts = provider.getCacheContainer().getCache("postCache");
utx = getUserTransactionFromJNDI();
try {
utx.begin();
for (int i = 1; i <= USER_COUNT; i++) {
User u = null;
if (i % 2 == 1) {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "user1.jpg"));
} else {
u = new User("user" + i, "Name" + i, "Surname" + i, "tmpPasswd",
"Description of person " + i, loadImageFromFile("images" + File.separator + "nophoto.jpg"));
}
String encryptedPass = hashPassword("pass" + i);
u.setPassword(encryptedPass);
// GENERATE POSTS FOR EACH USER
int numGeneratedPosts = 100;
TreeSet<Long> randomTimesSorted = new TreeSet<Long>();
for (int j = 1; j != numGeneratedPosts; j++) {
randomTimesSorted.add(getRandomTime());
}
for (int j = 1; j != numGeneratedPosts; j++) {
long randomTime = randomTimesSorted.pollFirst();
Post t = new Post(u.getUsername(), "Post number " + j + " for user "
+ u.getName() + " at " + new Date(randomTime), randomTime);
// store the post in a cache
posts.put(t.getKey(), t);
u.getPosts().add(t.getKey());
}
// store the user in a cache
users.put(u.getUsername(), u);
}
// GENERATE RANDOM WATCHERS AND WATCHING FOR EACH USER
for (int i = 1; i != USER_COUNT; i++) {
User u = (User) users.get("user" + i);
for (User watcher : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatchers().add(watcher.getUsername());
}
for (User watching : generateRandomUsers(u, 50, USER_COUNT)) {
u.getWatching().add(watching.getUsername());
}
users.replace("user" + i, u);
}
utx.commit();
log.info("Successfully imported data!");
} catch (Exception e) {
log.warning("An exception occured while populating the datagrid! Rolling back the transaction");
e.printStackTrace();
if (utx != null) {
try {
utx.rollback();
} catch (Exception e1) {
}
}
}
}
|
diff --git a/src/mediateka/db/History.java b/src/mediateka/db/History.java
index ec57889..5171c71 100644
--- a/src/mediateka/db/History.java
+++ b/src/mediateka/db/History.java
@@ -1,86 +1,86 @@
package mediateka.db;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import mediateka.datamanagers.Condition;
import mediateka.datamanagers.Managers;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;
/**
* Класс, представляющий таблицу истории
* @author Alexandr
*/
public class History extends Table {
public History() {
tableName = "history";
}
public boolean load(String fileName) throws LoadException {
try {
DefaultElement root = super.getRootElement(fileName);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
for (Iterator<Element> it = root.elements().iterator(); it.hasNext();) {
DefaultElement elem = (DefaultElement) it.next();
recordsList.add(new HistoryRecord(
Integer.parseInt(elem.attribute("id").getValue()),
(Disc) Managers.getInstance().getDiscsManager().find(Integer.parseInt(elem.node(0).getText())),
(Person) Managers.getInstance().getPersManager().find(Integer.parseInt(elem.node(1).getText())),
format.parse(elem.node(3).getText()),
format.parse(elem.node(5).getText()),
format.parse(elem.node(4).getText()),
elem.node(2).getText()));
}
return true;
} catch (Exception ex) {
throw new LoadException("История не загружена!");
}
}
public Records find(Record record) {
History retVal = new History();
HashMap<String, String> map = new HashMap<String, String>();
HistoryRecord rec;
try {
rec = (HistoryRecord) record;
} catch (Exception e) {
return null;
}
if (rec.getID() > 0) {
map.put("id", Integer.toString(rec.getID()));
} else {
if (rec.getDisc() != null) {
map.put("discID", Integer.toString(rec.getDisc().getID()));
}
if (rec.getPerson() != null) {
map.put("personID", Integer.toString(rec.getPerson().getID()));
}
if (!rec.getComment().equals("")) {
map.put("comment", rec.getComment());
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
if (rec.getGiveDate() != null) {
map.put("dateOfIssue", formatter.format(rec.getGiveDate()));
}
if (rec.getReturnDate() != null) {
map.put("dateOfReturn", formatter.format(rec.getReturnDate()));
}
if (rec.getPromisedDate() != null) {
map.put("promisingDate", formatter.format(rec.getPromisedDate()));
}
}
- Condition cond = new Condition(map, Managers.mode);
+ Condition cond = new Condition(map);
for (Record historyRecord : recordsList) {
if (cond.isEquals(historyRecord)) {
retVal.add(historyRecord);
}
}
return retVal.size() > 0 ? retVal : null;
}
protected Record createRecord(int id) {
return new HistoryRecord(id);
}
}
| true | true | public Records find(Record record) {
History retVal = new History();
HashMap<String, String> map = new HashMap<String, String>();
HistoryRecord rec;
try {
rec = (HistoryRecord) record;
} catch (Exception e) {
return null;
}
if (rec.getID() > 0) {
map.put("id", Integer.toString(rec.getID()));
} else {
if (rec.getDisc() != null) {
map.put("discID", Integer.toString(rec.getDisc().getID()));
}
if (rec.getPerson() != null) {
map.put("personID", Integer.toString(rec.getPerson().getID()));
}
if (!rec.getComment().equals("")) {
map.put("comment", rec.getComment());
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
if (rec.getGiveDate() != null) {
map.put("dateOfIssue", formatter.format(rec.getGiveDate()));
}
if (rec.getReturnDate() != null) {
map.put("dateOfReturn", formatter.format(rec.getReturnDate()));
}
if (rec.getPromisedDate() != null) {
map.put("promisingDate", formatter.format(rec.getPromisedDate()));
}
}
Condition cond = new Condition(map, Managers.mode);
for (Record historyRecord : recordsList) {
if (cond.isEquals(historyRecord)) {
retVal.add(historyRecord);
}
}
return retVal.size() > 0 ? retVal : null;
}
| public Records find(Record record) {
History retVal = new History();
HashMap<String, String> map = new HashMap<String, String>();
HistoryRecord rec;
try {
rec = (HistoryRecord) record;
} catch (Exception e) {
return null;
}
if (rec.getID() > 0) {
map.put("id", Integer.toString(rec.getID()));
} else {
if (rec.getDisc() != null) {
map.put("discID", Integer.toString(rec.getDisc().getID()));
}
if (rec.getPerson() != null) {
map.put("personID", Integer.toString(rec.getPerson().getID()));
}
if (!rec.getComment().equals("")) {
map.put("comment", rec.getComment());
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
if (rec.getGiveDate() != null) {
map.put("dateOfIssue", formatter.format(rec.getGiveDate()));
}
if (rec.getReturnDate() != null) {
map.put("dateOfReturn", formatter.format(rec.getReturnDate()));
}
if (rec.getPromisedDate() != null) {
map.put("promisingDate", formatter.format(rec.getPromisedDate()));
}
}
Condition cond = new Condition(map);
for (Record historyRecord : recordsList) {
if (cond.isEquals(historyRecord)) {
retVal.add(historyRecord);
}
}
return retVal.size() > 0 ? retVal : null;
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/panels/testcase/AlertSitePanel.java b/src/java/com/eviware/soapui/impl/wsdl/panels/testcase/AlertSitePanel.java
index ccb4fce58..4f7a5c65e 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/panels/testcase/AlertSitePanel.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/panels/testcase/AlertSitePanel.java
@@ -1,112 +1,113 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.panels.testcase;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import com.eviware.soapui.impl.support.actions.ShowOnlineHelpAction;
import com.eviware.soapui.impl.wsdl.support.HelpUrls;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.components.BrowserComponent;
import com.eviware.soapui.support.components.JXToolBar;
/**
*
* Panel for displaying a AlertSite report
*
*/
public class AlertSitePanel extends JPanel
{
private JComboBox locations;
private BrowserComponent browser;
private static String[] locationsCache = getListOfLocations();
public AlertSitePanel()
{
super( new BorderLayout() );
setBackground( Color.WHITE );
setOpaque( true );
add( buildToolbar(), BorderLayout.NORTH );
}
private Component buildToolbar()
{
JXToolBar toolbar = UISupport.createToolbar();
toolbar.addFixed( UISupport.createToolbarButton( new RunAction() ) );
+ toolbar.addRelatedGap();
toolbar.addFixed( buildLocationsComboBox() );
toolbar.addGlue();
toolbar.addFixed( UISupport.createToolbarButton( new ShowOnlineHelpAction( HelpUrls.ALERT_SITE_HELP_URL ) ) );
return toolbar;
}
private JComboBox buildLocationsComboBox()
{
JComboBox cb = new JComboBox( locationsCache );
return cb;
}
private static String[] getListOfLocations()
{
String[] arr = { new Location( "1", "name1" ).getName(), new Location( "2", "name2" ).getName() };
return arr;
}
private static class Location
{
private String code;
private String name;
public Location( String code, String name )
{
this.code = code;
this.name = name;
}
public String getCode()
{
return this.code;
}
public String getName()
{
return this.name;
}
}
private class RunAction extends AbstractAction
{
public RunAction()
{
putValue( SMALL_ICON, UISupport.createImageIcon( "/run.gif" ) );
putValue( Action.SHORT_DESCRIPTION, "Run Test On Demand report" );
}
public void actionPerformed( ActionEvent arg0 )
{
}
}
}
| true | true | private Component buildToolbar()
{
JXToolBar toolbar = UISupport.createToolbar();
toolbar.addFixed( UISupport.createToolbarButton( new RunAction() ) );
toolbar.addFixed( buildLocationsComboBox() );
toolbar.addGlue();
toolbar.addFixed( UISupport.createToolbarButton( new ShowOnlineHelpAction( HelpUrls.ALERT_SITE_HELP_URL ) ) );
return toolbar;
}
| private Component buildToolbar()
{
JXToolBar toolbar = UISupport.createToolbar();
toolbar.addFixed( UISupport.createToolbarButton( new RunAction() ) );
toolbar.addRelatedGap();
toolbar.addFixed( buildLocationsComboBox() );
toolbar.addGlue();
toolbar.addFixed( UISupport.createToolbarButton( new ShowOnlineHelpAction( HelpUrls.ALERT_SITE_HELP_URL ) ) );
return toolbar;
}
|
diff --git a/src/java/davmail/exchange/dav/DavExchangeSession.java b/src/java/davmail/exchange/dav/DavExchangeSession.java
index ef3d925..280f78f 100644
--- a/src/java/davmail/exchange/dav/DavExchangeSession.java
+++ b/src/java/davmail/exchange/dav/DavExchangeSession.java
@@ -1,2620 +1,2620 @@
/*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2010 Mickael Guessant
*
* 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 davmail.exchange.dav;
import davmail.BundleMessage;
import davmail.Settings;
import davmail.exception.*;
import davmail.exchange.*;
import davmail.http.DavGatewayHttpClientFacade;
import davmail.ui.tray.DavGatewayTray;
import davmail.util.IOUtil;
import davmail.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.CopyMethod;
import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.w3c.dom.Node;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimePart;
import javax.mail.util.SharedByteArrayInputStream;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
/**
* Webdav Exchange adapter.
* Compatible with Exchange 2003 and 2007 with webdav available.
*/
public class DavExchangeSession extends ExchangeSession {
protected static enum FolderQueryTraversal {
Shallow, Deep
}
protected static final DavPropertyNameSet WELL_KNOWN_FOLDERS = new DavPropertyNameSet();
static {
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("inbox"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("deleteditems"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("sentitems"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("sendmsg"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("drafts"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("calendar"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("contacts"));
WELL_KNOWN_FOLDERS.add(Field.getPropertyName("outbox"));
}
/**
* Various standard mail boxes Urls
*/
protected String inboxUrl;
protected String deleteditemsUrl;
protected String sentitemsUrl;
protected String sendmsgUrl;
protected String draftsUrl;
protected String calendarUrl;
protected String contactsUrl;
protected String outboxUrl;
protected String inboxName;
protected String deleteditemsName;
protected String sentitemsName;
protected String sendmsgName;
protected String draftsName;
protected String calendarName;
protected String contactsName;
protected String outboxName;
protected static final String USERS = "/users/";
/**
* Convert logical or relative folder path to exchange folder path.
*
* @param folderPath folder name
* @return folder path
*/
public String getFolderPath(String folderPath) {
String exchangeFolderPath;
// IMAP path
if (folderPath.startsWith(INBOX)) {
exchangeFolderPath = mailPath + inboxName + folderPath.substring(INBOX.length());
} else if (folderPath.startsWith(TRASH)) {
exchangeFolderPath = mailPath + deleteditemsName + folderPath.substring(TRASH.length());
} else if (folderPath.startsWith(DRAFTS)) {
exchangeFolderPath = mailPath + draftsName + folderPath.substring(DRAFTS.length());
} else if (folderPath.startsWith(SENT)) {
exchangeFolderPath = mailPath + sentitemsName + folderPath.substring(SENT.length());
} else if (folderPath.startsWith(SENDMSG)) {
exchangeFolderPath = mailPath + sendmsgName + folderPath.substring(SENDMSG.length());
} else if (folderPath.startsWith(CONTACTS)) {
exchangeFolderPath = mailPath + contactsName + folderPath.substring(CONTACTS.length());
} else if (folderPath.startsWith(CALENDAR)) {
exchangeFolderPath = mailPath + calendarName + folderPath.substring(CALENDAR.length());
} else if (folderPath.startsWith("public")) {
exchangeFolderPath = publicFolderUrl + folderPath.substring("public".length());
// caldav path
} else if (folderPath.startsWith(USERS)) {
// get requested principal
String principal;
String localPath;
int principalIndex = folderPath.indexOf('/', USERS.length());
if (principalIndex >= 0) {
principal = folderPath.substring(USERS.length(), principalIndex);
localPath = folderPath.substring(USERS.length() + principal.length() + 1);
if (localPath.startsWith(LOWER_CASE_INBOX) || localPath.startsWith(INBOX)) {
localPath = inboxName + localPath.substring(LOWER_CASE_INBOX.length());
} else if (localPath.startsWith(CALENDAR)) {
localPath = calendarName + localPath.substring(CALENDAR.length());
} else if (localPath.startsWith(CONTACTS)) {
localPath = contactsName + localPath.substring(CONTACTS.length());
} else if (localPath.startsWith(ADDRESSBOOK)) {
localPath = contactsName + localPath.substring(ADDRESSBOOK.length());
}
} else {
principal = folderPath.substring(USERS.length());
localPath = "";
}
if (principal.length() == 0) {
exchangeFolderPath = rootPath;
} else if (alias.equalsIgnoreCase(principal) || email.equalsIgnoreCase(principal)) {
exchangeFolderPath = mailPath + localPath;
} else {
LOGGER.debug("Detected shared path for principal " + principal + ", user principal is " + email);
exchangeFolderPath = rootPath + principal + '/' + localPath;
}
// absolute folder path
} else if (folderPath.startsWith("/")) {
exchangeFolderPath = folderPath;
} else {
exchangeFolderPath = mailPath + folderPath;
}
return exchangeFolderPath;
}
/**
* Test if folderPath is inside user mailbox.
*
* @param folderPath absolute folder path
* @return true if folderPath is a public or shared folder
*/
@Override
public boolean isSharedFolder(String folderPath) {
return !getFolderPath(folderPath).toLowerCase().startsWith(mailPath.toLowerCase());
}
/**
* LDAP to Exchange Criteria Map
*/
static final HashMap<String, String> GALFIND_CRITERIA_MAP = new HashMap<String, String>();
static {
GALFIND_CRITERIA_MAP.put("imapUid", "AN");
GALFIND_CRITERIA_MAP.put("smtpemail1", "EM");
GALFIND_CRITERIA_MAP.put("cn", "DN");
GALFIND_CRITERIA_MAP.put("givenName", "FN");
GALFIND_CRITERIA_MAP.put("sn", "LN");
GALFIND_CRITERIA_MAP.put("title", "TL");
GALFIND_CRITERIA_MAP.put("o", "CP");
GALFIND_CRITERIA_MAP.put("l", "OF");
GALFIND_CRITERIA_MAP.put("department", "DP");
}
static final HashSet<String> GALLOOKUP_ATTRIBUTES = new HashSet<String>();
static {
GALLOOKUP_ATTRIBUTES.add("givenName");
GALLOOKUP_ATTRIBUTES.add("initials");
GALLOOKUP_ATTRIBUTES.add("sn");
GALLOOKUP_ATTRIBUTES.add("street");
GALLOOKUP_ATTRIBUTES.add("st");
GALLOOKUP_ATTRIBUTES.add("postalcode");
GALLOOKUP_ATTRIBUTES.add("co");
GALLOOKUP_ATTRIBUTES.add("departement");
GALLOOKUP_ATTRIBUTES.add("mobile");
}
/**
* Exchange to LDAP attribute map
*/
static final HashMap<String, String> GALFIND_ATTRIBUTE_MAP = new HashMap<String, String>();
static {
GALFIND_ATTRIBUTE_MAP.put("uid", "AN");
GALFIND_ATTRIBUTE_MAP.put("smtpemail1", "EM");
GALFIND_ATTRIBUTE_MAP.put("cn", "DN");
GALFIND_ATTRIBUTE_MAP.put("displayName", "DN");
GALFIND_ATTRIBUTE_MAP.put("telephoneNumber", "PH");
GALFIND_ATTRIBUTE_MAP.put("l", "OFFICE");
GALFIND_ATTRIBUTE_MAP.put("o", "CP");
GALFIND_ATTRIBUTE_MAP.put("title", "TL");
GALFIND_ATTRIBUTE_MAP.put("givenName", "first");
GALFIND_ATTRIBUTE_MAP.put("initials", "initials");
GALFIND_ATTRIBUTE_MAP.put("sn", "last");
GALFIND_ATTRIBUTE_MAP.put("street", "street");
GALFIND_ATTRIBUTE_MAP.put("st", "state");
GALFIND_ATTRIBUTE_MAP.put("postalcode", "zip");
GALFIND_ATTRIBUTE_MAP.put("co", "country");
GALFIND_ATTRIBUTE_MAP.put("department", "department");
GALFIND_ATTRIBUTE_MAP.put("mobile", "mobile");
GALFIND_ATTRIBUTE_MAP.put("roomnumber", "office");
}
boolean disableGalFind;
protected Map<String, Map<String, String>> galFind(String query) throws IOException {
Map<String, Map<String, String>> results;
String path = getCmdBasePath() + "?Cmd=galfind" + query;
GetMethod getMethod = new GetMethod(path);
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, getMethod, true);
results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "item", "AN");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(path + ": " + results.size() + " result(s)");
}
} catch (IOException e) {
LOGGER.debug("GET " + path + " failed: " + e + ' ' + e.getMessage());
disableGalFind = true;
throw e;
} finally {
getMethod.releaseConnection();
}
return results;
}
@Override
public Map<String, ExchangeSession.Contact> galFind(Condition condition, Set<String> returningAttributes, int sizeLimit) throws IOException {
Map<String, ExchangeSession.Contact> contacts = new HashMap<String, ExchangeSession.Contact>();
if (disableGalFind) {
// do nothing
} else if (condition instanceof MultiCondition) {
List<Condition> conditions = ((ExchangeSession.MultiCondition) condition).getConditions();
Operator operator = ((ExchangeSession.MultiCondition) condition).getOperator();
if (operator == Operator.Or) {
for (Condition innerCondition : conditions) {
contacts.putAll(galFind(innerCondition, returningAttributes, sizeLimit));
}
} else if (operator == Operator.And && !conditions.isEmpty()) {
Map<String, ExchangeSession.Contact> innerContacts = galFind(conditions.get(0), returningAttributes, sizeLimit);
for (ExchangeSession.Contact contact : innerContacts.values()) {
if (condition.isMatch(contact)) {
contacts.put(contact.getName().toLowerCase(), contact);
}
}
}
} else if (condition instanceof AttributeCondition) {
String searchAttributeName = ((ExchangeSession.AttributeCondition) condition).getAttributeName();
String searchAttribute = GALFIND_CRITERIA_MAP.get(searchAttributeName);
if (searchAttribute != null) {
String searchValue = ((ExchangeSession.AttributeCondition) condition).getValue();
StringBuilder query = new StringBuilder();
if ("EM".equals(searchAttribute)) {
// mail search, split
int atIndex = searchValue.indexOf('@');
// remove suffix
if (atIndex >= 0) {
searchValue = searchValue.substring(0, atIndex);
}
// split firstname.lastname
int dotIndex = searchValue.indexOf('.');
if (dotIndex >= 0) {
// assume mail starts with firstname
query.append("&FN=").append(URIUtil.encodeWithinQuery(searchValue.substring(0, dotIndex)));
query.append("&LN=").append(URIUtil.encodeWithinQuery(searchValue.substring(dotIndex + 1)));
} else {
query.append("&FN=").append(URIUtil.encodeWithinQuery(searchValue));
}
} else {
query.append('&').append(searchAttribute).append('=').append(URIUtil.encodeWithinQuery(searchValue));
}
Map<String, Map<String, String>> results = galFind(query.toString());
for (Map<String, String> result : results.values()) {
Contact contact = new Contact();
contact.setName(result.get("AN"));
contact.put("imapUid", result.get("AN"));
buildGalfindContact(contact, result);
if (needGalLookup(searchAttributeName, returningAttributes)) {
galLookup(contact);
// iCal fix to suit both iCal 3 and 4: move cn to sn, remove cn
} else if (returningAttributes.contains("apple-serviceslocator")) {
if (contact.get("cn") != null && returningAttributes.contains("sn")) {
contact.put("sn", contact.get("cn"));
contact.remove("cn");
}
}
if (condition.isMatch(contact)) {
contacts.put(contact.getName().toLowerCase(), contact);
}
}
}
}
return contacts;
}
protected boolean needGalLookup(String searchAttributeName, Set<String> returningAttributes) {
// return all attributes => call gallookup
if (returningAttributes == null || returningAttributes.isEmpty()) {
return true;
// iCal search, do not call gallookup
} else if (returningAttributes.contains("apple-serviceslocator")) {
return false;
// Lightning search, no need to gallookup
} else if ("sn".equals(searchAttributeName)) {
return returningAttributes.contains("sn");
// search attribute is gallookup attribute, need to fetch value for isMatch
} else if (GALLOOKUP_ATTRIBUTES.contains(searchAttributeName)) {
return true;
}
for (String attributeName : GALLOOKUP_ATTRIBUTES) {
if (returningAttributes.contains(attributeName)) {
return true;
}
}
return false;
}
private boolean disableGalLookup;
/**
* Get extended address book information for person with gallookup.
* Does not work with Exchange 2007
*
* @param contact galfind contact
*/
public void galLookup(Contact contact) {
if (!disableGalLookup) {
LOGGER.debug("galLookup(" + contact.get("smtpemail1") + ')');
GetMethod getMethod = null;
try {
getMethod = new GetMethod(URIUtil.encodePathQuery(getCmdBasePath() + "?Cmd=gallookup&ADDR=" + contact.get("smtpemail1")));
DavGatewayHttpClientFacade.executeGetMethod(httpClient, getMethod, true);
Map<String, Map<String, String>> results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "person", "alias");
// add detailed information
if (!results.isEmpty()) {
Map<String, String> personGalLookupDetails = results.get(contact.get("uid").toLowerCase());
if (personGalLookupDetails != null) {
buildGalfindContact(contact, personGalLookupDetails);
}
}
} catch (IOException e) {
LOGGER.warn("Unable to gallookup person: " + contact + ", disable GalLookup");
disableGalLookup = true;
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
}
}
}
}
protected void buildGalfindContact(Contact contact, Map<String, String> response) {
for (Map.Entry<String, String> entry : GALFIND_ATTRIBUTE_MAP.entrySet()) {
String attributeValue = response.get(entry.getValue());
if (attributeValue != null) {
contact.put(entry.getKey(), attributeValue);
}
}
}
@Override
protected String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException {
String freebusyUrl = publicFolderUrl + "/?cmd=freebusy" +
"&start=" + start +
"&end=" + end +
"&interval=" + interval +
"&u=SMTP:" + attendee;
GetMethod getMethod = new GetMethod(freebusyUrl);
getMethod.setRequestHeader("Content-Type", "text/xml");
String fbdata = null;
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, getMethod, true);
fbdata = StringUtil.getLastToken(getMethod.getResponseBodyAsString(), "<a:fbdata>", "</a:fbdata>");
} finally {
getMethod.releaseConnection();
}
return fbdata;
}
/**
* @inheritDoc
*/
public DavExchangeSession(String url, String userName, String password) throws IOException {
super(url, userName, password);
}
@Override
protected void buildSessionInfo(HttpMethod method) throws DavMailException {
buildMailPath(method);
// get base http mailbox http urls
getWellKnownFolders();
}
static final String BASE_HREF = "<base href=\"";
/**
* Exchange 2003: get mailPath from welcome page
*
* @param method current http method
* @return mail path from body
*/
protected String getMailpathFromWelcomePage(HttpMethod method) {
String welcomePageMailPath = null;
// get user mail URL from html body (multi frame)
BufferedReader mainPageReader = null;
try {
mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
//noinspection StatementWithEmptyBody
String line;
while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) {
}
if (line != null) {
// Exchange 2003
int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length();
int end = line.indexOf('\"', start);
String mailBoxBaseHref = line.substring(start, end);
URL baseURL = new URL(mailBoxBaseHref);
welcomePageMailPath = baseURL.getPath();
LOGGER.debug("Base href found in body, mailPath is " + welcomePageMailPath);
}
} catch (IOException e) {
LOGGER.error("Error parsing main page at " + method.getPath(), e);
} finally {
if (mainPageReader != null) {
try {
mainPageReader.close();
} catch (IOException e) {
LOGGER.error("Error parsing main page at " + method.getPath());
}
}
method.releaseConnection();
}
return welcomePageMailPath;
}
protected void buildMailPath(HttpMethod method) throws DavMailAuthenticationException {
// get mailPath from welcome page on Exchange 2003
mailPath = getMailpathFromWelcomePage(method);
//noinspection VariableNotUsedInsideIf
if (mailPath != null) {
// Exchange 2003
serverVersion = "Exchange2003";
try {
buildEmail(method.getURI().getHost());
} catch (URIException uriException) {
LOGGER.warn(uriException);
}
} else {
// Exchange 2007 : get alias and email from options page
serverVersion = "Exchange2007";
// Gallookup is an Exchange 2003 only feature
disableGalLookup = true;
getEmailAndAliasFromOptions();
// failover: try to get email through Webdav and Galfind
if (alias == null || email == null) {
try {
buildEmail(method.getURI().getHost());
} catch (URIException uriException) {
LOGGER.warn(uriException);
}
}
// build standard mailbox link with email
mailPath = "/exchange/" + email + '/';
}
if (mailPath == null || email == null) {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED");
}
LOGGER.debug("Current user email is " + email + ", alias is " + alias + ", mailPath is " + mailPath);
rootPath = mailPath.substring(0, mailPath.lastIndexOf('/', mailPath.length() - 2) + 1);
}
/**
* Determine user email through various means.
*
* @param hostName Exchange server host name for last failover
*/
public void buildEmail(String hostName) {
String mailBoxPath = getMailboxPath();
// mailPath contains either alias or email
if (mailBoxPath != null && mailBoxPath.indexOf('@') >= 0) {
email = mailBoxPath;
alias = getAliasFromMailboxDisplayName();
if (alias == null) {
alias = getAliasFromLogin();
}
} else {
// use mailbox name as alias
alias = mailBoxPath;
email = getEmail(alias);
if (email == null) {
// failover: try to get email from login name
alias = getAliasFromLogin();
email = getEmail(alias);
}
// another failover : get alias from mailPath display name
if (email == null) {
alias = getAliasFromMailboxDisplayName();
email = getEmail(alias);
}
if (email == null) {
LOGGER.debug("Unable to get user email with alias " + mailBoxPath
+ " or " + getAliasFromLogin()
+ " or " + alias
);
// last failover: build email from domain name and mailbox display name
StringBuilder buffer = new StringBuilder();
// most reliable alias
alias = mailBoxPath;
buffer.append(alias);
if (alias.indexOf('@') < 0) {
buffer.append('@');
int dotIndex = hostName.indexOf('.');
if (dotIndex >= 0) {
buffer.append(hostName.substring(dotIndex + 1));
}
}
email = buffer.toString();
}
}
}
/**
* Get user alias from mailbox display name over Webdav.
*
* @return user alias
*/
public String getAliasFromMailboxDisplayName() {
if (mailPath == null) {
return null;
}
String displayName = null;
try {
Folder rootFolder = getFolder("");
if (rootFolder == null) {
LOGGER.warn(new BundleMessage("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath));
} else {
displayName = rootFolder.displayName;
}
} catch (IOException e) {
LOGGER.warn(new BundleMessage("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath));
}
return displayName;
}
/**
* Get current Exchange alias name from mailbox name
*
* @return user name
*/
protected String getMailboxPath() {
if (mailPath == null) {
return null;
}
int index = mailPath.lastIndexOf('/', mailPath.length() - 2);
if (index >= 0 && mailPath.endsWith("/")) {
return mailPath.substring(index + 1, mailPath.length() - 1);
} else {
LOGGER.warn(new BundleMessage("EXCEPTION_INVALID_MAIL_PATH", mailPath));
return null;
}
}
/**
* Get user email from global address list (galfind).
*
* @param alias user alias
* @return user email
*/
public String getEmail(String alias) {
String emailResult = null;
if (alias != null && !disableGalFind) {
try {
Map<String, Map<String, String>> results = galFind("&AN=" + URIUtil.encodeWithinQuery(alias));
Map<String, String> result = results.get(alias.toLowerCase());
if (result != null) {
emailResult = result.get("EM");
}
} catch (IOException e) {
// galfind not available
disableGalFind = true;
LOGGER.debug("getEmail(" + alias + ") failed");
}
}
return emailResult;
}
protected String getURIPropertyIfExists(DavPropertySet properties, String alias) throws URIException {
DavProperty property = properties.get(Field.getPropertyName(alias));
if (property == null) {
return null;
} else {
return URIUtil.decode((String) property.getValue());
}
}
// return last folder name from url
protected String getFolderName(String url) {
if (url != null) {
if (url.endsWith("/")) {
return url.substring(url.lastIndexOf('/', url.length() - 2) + 1, url.length() - 1);
} else if (url.indexOf('/') > 0) {
return url.substring(url.lastIndexOf('/') + 1);
} else {
return null;
}
} else {
return null;
}
}
protected void getWellKnownFolders() throws DavMailException {
// Retrieve well known URLs
MultiStatusResponse[] responses;
try {
responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(mailPath), 0, WELL_KNOWN_FOLDERS);
if (responses.length == 0) {
throw new WebdavNotAvailableException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath);
}
DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK);
inboxUrl = getURIPropertyIfExists(properties, "inbox");
inboxName = getFolderName(inboxUrl);
deleteditemsUrl = getURIPropertyIfExists(properties, "deleteditems");
deleteditemsName = getFolderName(deleteditemsUrl);
sentitemsUrl = getURIPropertyIfExists(properties, "sentitems");
sentitemsName = getFolderName(sentitemsUrl);
sendmsgUrl = getURIPropertyIfExists(properties, "sendmsg");
sendmsgName = getFolderName(sendmsgUrl);
draftsUrl = getURIPropertyIfExists(properties, "drafts");
draftsName = getFolderName(draftsUrl);
calendarUrl = getURIPropertyIfExists(properties, "calendar");
calendarName = getFolderName(calendarUrl);
contactsUrl = getURIPropertyIfExists(properties, "contacts");
contactsName = getFolderName(contactsUrl);
outboxUrl = getURIPropertyIfExists(properties, "outbox");
outboxName = getFolderName(outboxUrl);
// junk folder not available over webdav
// default public folder path
publicFolderUrl = PUBLIC_ROOT;
Cookie[] currentCookies = httpClient.getState().getCookies();
// check public folder access
try {
if (inboxUrl != null) {
// try to build full public URI from inboxUrl
URI publicUri = new URI(inboxUrl, false);
publicUri.setPath(PUBLIC_ROOT);
publicFolderUrl = publicUri.getURI();
}
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
davPropertyNameSet.add(Field.getPropertyName("displayname"));
PropFindMethod propFindMethod = new PropFindMethod(publicFolderUrl, davPropertyNameSet, 0);
try {
DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
} catch (IOException e) {
// workaround for NTLM authentication only on /public
if (!DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
DavGatewayHttpClientFacade.addNTLM(httpClient);
DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
}
}
// update public folder URI
publicFolderUrl = propFindMethod.getURI().getURI();
} catch (IOException e) {
// restore cookies on error
httpClient.getState().addCookies(currentCookies);
LOGGER.warn("Public folders not available: " + (e.getMessage() == null ? e : e.getMessage()));
publicFolderUrl = "/public";
}
LOGGER.debug("Inbox URL: " + inboxUrl +
" Trash URL: " + deleteditemsUrl +
" Sent URL: " + sentitemsUrl +
" Send URL: " + sendmsgUrl +
" Drafts URL: " + draftsUrl +
" Calendar URL: " + calendarUrl +
" Contacts URL: " + contactsUrl +
" Outbox URL: " + outboxUrl +
" Public folder URL: " + publicFolderUrl
);
} catch (IOException e) {
LOGGER.error(e.getMessage());
throw new WebdavNotAvailableException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER", mailPath);
}
}
protected static class MultiCondition extends ExchangeSession.MultiCondition {
protected MultiCondition(Operator operator, Condition... condition) {
super(operator, condition);
}
public void appendTo(StringBuilder buffer) {
boolean first = true;
for (Condition condition : conditions) {
if (condition != null && !condition.isEmpty()) {
if (first) {
buffer.append('(');
first = false;
} else {
buffer.append(' ').append(operator).append(' ');
}
condition.appendTo(buffer);
}
}
// at least one non empty condition
if (!first) {
buffer.append(')');
}
}
}
protected static class NotCondition extends ExchangeSession.NotCondition {
protected NotCondition(Condition condition) {
super(condition);
}
public void appendTo(StringBuilder buffer) {
buffer.append("(Not ");
condition.appendTo(buffer);
buffer.append(')');
}
}
static final Map<Operator, String> operatorMap = new HashMap<Operator, String>();
static {
operatorMap.put(Operator.IsEqualTo, " = ");
operatorMap.put(Operator.IsGreaterThanOrEqualTo, " >= ");
operatorMap.put(Operator.IsGreaterThan, " > ");
operatorMap.put(Operator.IsLessThanOrEqualTo, " <= ");
operatorMap.put(Operator.IsLessThan, " < ");
operatorMap.put(Operator.Like, " like ");
operatorMap.put(Operator.IsNull, " is null");
operatorMap.put(Operator.IsFalse, " = false");
operatorMap.put(Operator.IsTrue, " = true");
operatorMap.put(Operator.StartsWith, " = ");
operatorMap.put(Operator.Contains, " = ");
}
protected static class AttributeCondition extends ExchangeSession.AttributeCondition {
protected boolean isIntValue;
protected AttributeCondition(String attributeName, Operator operator, String value) {
super(attributeName, operator, value);
}
protected AttributeCondition(String attributeName, Operator operator, int value) {
super(attributeName, operator, String.valueOf(value));
isIntValue = true;
}
public void appendTo(StringBuilder buffer) {
Field field = Field.get(attributeName);
buffer.append('"').append(field.getUri()).append('"');
buffer.append(operatorMap.get(operator));
//noinspection VariableNotUsedInsideIf
if (field.cast != null) {
buffer.append("CAST (\"");
} else if (!isIntValue && !field.isIntValue()) {
buffer.append('\'');
}
if (Operator.Like == operator) {
buffer.append('%');
}
if ("urlcompname".equals(field.alias)) {
buffer.append(StringUtil.encodeUrlcompname(StringUtil.davSearchEncode(value)));
} else if (field.isIntValue()) {
// check value
try {
Integer.parseInt(value);
buffer.append(value);
} catch (NumberFormatException e) {
// invalid value, replace with 0
buffer.append('0');
}
} else {
buffer.append(StringUtil.davSearchEncode(value));
}
if (Operator.Like == operator || Operator.StartsWith == operator) {
buffer.append('%');
}
if (field.cast != null) {
buffer.append("\" as '").append(field.cast).append("')");
} else if (!isIntValue && !field.isIntValue()) {
buffer.append('\'');
}
}
public boolean isMatch(ExchangeSession.Contact contact) {
String lowerCaseValue = value.toLowerCase();
String actualValue = contact.get(attributeName);
Operator actualOperator = operator;
// patch for iCal or Lightning search without galLookup
if (actualValue == null && ("givenName".equals(attributeName) || "sn".equals(attributeName))) {
actualValue = contact.get("cn");
actualOperator = Operator.Like;
}
if (actualValue == null) {
return false;
}
actualValue = actualValue.toLowerCase();
return (actualOperator == Operator.IsEqualTo && actualValue.equals(lowerCaseValue)) ||
(actualOperator == Operator.Like && actualValue.contains(lowerCaseValue)) ||
(actualOperator == Operator.StartsWith && actualValue.startsWith(lowerCaseValue));
}
}
protected static class HeaderCondition extends AttributeCondition {
protected HeaderCondition(String attributeName, Operator operator, String value) {
super(attributeName, operator, value);
}
@Override
public void appendTo(StringBuilder buffer) {
buffer.append('"').append(Field.getHeader(attributeName).getUri()).append('"');
buffer.append(operatorMap.get(operator));
buffer.append('\'');
if (Operator.Like == operator) {
buffer.append('%');
}
buffer.append(value);
if (Operator.Like == operator) {
buffer.append('%');
}
buffer.append('\'');
}
}
protected static class MonoCondition extends ExchangeSession.MonoCondition {
protected MonoCondition(String attributeName, Operator operator) {
super(attributeName, operator);
}
public void appendTo(StringBuilder buffer) {
buffer.append('"').append(Field.get(attributeName).getUri()).append('"');
buffer.append(operatorMap.get(operator));
}
}
@Override
public ExchangeSession.MultiCondition and(Condition... condition) {
return new MultiCondition(Operator.And, condition);
}
@Override
public ExchangeSession.MultiCondition or(Condition... condition) {
return new MultiCondition(Operator.Or, condition);
}
@Override
public Condition not(Condition condition) {
if (condition == null) {
return null;
} else {
return new NotCondition(condition);
}
}
@Override
public Condition isEqualTo(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, value);
}
@Override
public Condition isEqualTo(String attributeName, int value) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, value);
}
@Override
public Condition headerIsEqualTo(String headerName, String value) {
return new HeaderCondition(headerName, Operator.IsEqualTo, value);
}
@Override
public Condition gte(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsGreaterThanOrEqualTo, value);
}
@Override
public Condition lte(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsLessThanOrEqualTo, value);
}
@Override
public Condition lt(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsLessThan, value);
}
@Override
public Condition gt(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsGreaterThan, value);
}
@Override
public Condition contains(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.Like, value);
}
@Override
public Condition startsWith(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.StartsWith, value);
}
@Override
public Condition isNull(String attributeName) {
return new MonoCondition(attributeName, Operator.IsNull);
}
@Override
public Condition isTrue(String attributeName) {
return new MonoCondition(attributeName, Operator.IsTrue);
}
@Override
public Condition isFalse(String attributeName) {
return new MonoCondition(attributeName, Operator.IsFalse);
}
/**
* @inheritDoc
*/
public class Message extends ExchangeSession.Message {
@Override
public String getPermanentId() {
return permanentUrl;
}
}
/**
* @inheritDoc
*/
public class Contact extends ExchangeSession.Contact {
/**
* Build Contact instance from multistatusResponse info
*
* @param multiStatusResponse response
* @throws URIException on error
* @throws DavMailException on error
*/
public Contact(MultiStatusResponse multiStatusResponse) throws URIException, DavMailException {
setHref(URIUtil.decode(multiStatusResponse.getHref()));
DavPropertySet properties = multiStatusResponse.getProperties(HttpStatus.SC_OK);
permanentUrl = getPropertyIfExists(properties, "permanenturl");
etag = getPropertyIfExists(properties, "etag");
displayName = getPropertyIfExists(properties, "displayname");
for (String attributeName : CONTACT_ATTRIBUTES) {
String value = getPropertyIfExists(properties, attributeName);
if (value != null) {
if ("bday".equals(attributeName) || "anniversary".equals(attributeName)
|| "lastmodified".equals(attributeName) || "datereceived".equals(attributeName)) {
value = convertDateFromExchange(value);
} else if ("haspicture".equals(attributeName) || "private".equals(attributeName)) {
value = "1".equals(value) ? "true" : "false";
}
put(attributeName, value);
}
}
}
/**
* @inheritDoc
*/
public Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
super(folderPath, itemName, properties, etag, noneMatch);
}
/**
* Default constructor for galFind
*/
public Contact() {
}
protected Set<PropertyValue> buildProperties() {
Set<PropertyValue> propertyValues = new HashSet<PropertyValue>();
for (Map.Entry<String, String> entry : entrySet()) {
String key = entry.getKey();
if (!"photo".equals(key)) {
propertyValues.add(Field.createPropertyValue(key, entry.getValue()));
}
}
return propertyValues;
}
protected ExchangePropPatchMethod internalCreateOrUpdate(String encodedHref) throws IOException {
ExchangePropPatchMethod propPatchMethod = new ExchangePropPatchMethod(encodedHref, buildProperties());
propPatchMethod.setRequestHeader("Translate", "f");
if (etag != null) {
propPatchMethod.setRequestHeader("If-Match", etag);
}
if (noneMatch != null) {
propPatchMethod.setRequestHeader("If-None-Match", noneMatch);
}
try {
httpClient.executeMethod(propPatchMethod);
} finally {
propPatchMethod.releaseConnection();
}
return propPatchMethod;
}
/**
* Create or update contact
*
* @return action result
* @throws IOException on error
*/
public ItemResult createOrUpdate() throws IOException {
String encodedHref = URIUtil.encodePath(getHref());
ExchangePropPatchMethod propPatchMethod = internalCreateOrUpdate(encodedHref);
int status = propPatchMethod.getStatusCode();
if (status == HttpStatus.SC_MULTI_STATUS) {
status = propPatchMethod.getResponseStatusCode();
//noinspection VariableNotUsedInsideIf
if (status == HttpStatus.SC_CREATED) {
LOGGER.debug("Created contact " + encodedHref);
} else {
LOGGER.debug("Updated contact " + encodedHref);
}
} else if (status == HttpStatus.SC_NOT_FOUND) {
LOGGER.debug("Contact not found at " + encodedHref + ", searching permanenturl by urlcompname");
// failover, search item by urlcompname
MultiStatusResponse[] responses = searchItems(folderPath, EVENT_REQUEST_PROPERTIES, DavExchangeSession.this.isEqualTo("urlcompname", convertItemNameToEML(itemName)), FolderQueryTraversal.Shallow, 1);
if (responses.length == 1) {
encodedHref = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "permanenturl");
LOGGER.warn("Contact found, permanenturl is " + encodedHref);
propPatchMethod = internalCreateOrUpdate(encodedHref);
status = propPatchMethod.getStatusCode();
if (status == HttpStatus.SC_MULTI_STATUS) {
status = propPatchMethod.getResponseStatusCode();
LOGGER.debug("Updated contact " + encodedHref);
} else {
LOGGER.warn("Unable to create or update contact " + status + ' ' + propPatchMethod.getStatusLine());
}
}
} else {
LOGGER.warn("Unable to create or update contact " + status + ' ' + propPatchMethod.getStatusLine());
}
ItemResult itemResult = new ItemResult();
// 440 means forbidden on Exchange
if (status == 440) {
status = HttpStatus.SC_FORBIDDEN;
}
itemResult.status = status;
if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
String contactPictureUrl = URIUtil.encodePath(getHref() + "/ContactPicture.jpg");
String photo = get("photo");
if (photo != null) {
// need to update photo
byte[] resizedImageBytes = IOUtil.resizeImage(Base64.decodeBase64(photo.getBytes()), 90);
final PutMethod putmethod = new PutMethod(contactPictureUrl);
putmethod.setRequestHeader("Overwrite", "t");
putmethod.setRequestHeader("Content-Type", "image/jpeg");
putmethod.setRequestEntity(new ByteArrayRequestEntity(resizedImageBytes, "image/jpeg"));
try {
status = httpClient.executeMethod(putmethod);
if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED) {
throw new IOException("Unable to update contact picture: " + status + ' ' + putmethod.getStatusLine());
}
} catch (IOException e) {
LOGGER.error("Error in contact photo create or update", e);
throw e;
} finally {
putmethod.releaseConnection();
}
Set<PropertyValue> picturePropertyValues = new HashSet<PropertyValue>();
picturePropertyValues.add(Field.createPropertyValue("attachmentContactPhoto", "true"));
// picturePropertyValues.add(Field.createPropertyValue("renderingPosition", "-1"));
picturePropertyValues.add(Field.createPropertyValue("attachExtension", ".jpg"));
final ExchangePropPatchMethod attachmentPropPatchMethod = new ExchangePropPatchMethod(contactPictureUrl, picturePropertyValues);
try {
status = httpClient.executeMethod(attachmentPropPatchMethod);
if (status != HttpStatus.SC_MULTI_STATUS) {
LOGGER.error("Error in contact photo create or update: " + attachmentPropPatchMethod.getStatusCode());
throw new IOException("Unable to update contact picture");
}
} finally {
attachmentPropPatchMethod.releaseConnection();
}
} else {
// try to delete picture
DeleteMethod deleteMethod = new DeleteMethod(contactPictureUrl);
try {
status = httpClient.executeMethod(deleteMethod);
if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) {
LOGGER.error("Error in contact photo delete: " + status);
throw new IOException("Unable to delete contact picture");
}
} finally {
deleteMethod.releaseConnection();
}
}
// need to retrieve new etag
HeadMethod headMethod = new HeadMethod(URIUtil.encodePath(getHref()));
try {
httpClient.executeMethod(headMethod);
if (headMethod.getResponseHeader("ETag") != null) {
itemResult.etag = headMethod.getResponseHeader("ETag").getValue();
}
} finally {
headMethod.releaseConnection();
}
}
return itemResult;
}
}
/**
* @inheritDoc
*/
public class Event extends ExchangeSession.Event {
/**
* Build Event instance from response info.
*
* @param multiStatusResponse response
* @throws URIException on error
*/
public Event(MultiStatusResponse multiStatusResponse) throws URIException {
setHref(URIUtil.decode(multiStatusResponse.getHref()));
DavPropertySet properties = multiStatusResponse.getProperties(HttpStatus.SC_OK);
permanentUrl = getPropertyIfExists(properties, "permanenturl");
etag = getPropertyIfExists(properties, "etag");
displayName = getPropertyIfExists(properties, "displayname");
subject = getPropertyIfExists(properties, "subject");
}
protected String getPermanentUrl() {
return permanentUrl;
}
/**
* @inheritDoc
*/
public Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) throws IOException {
super(folderPath, itemName, contentClass, itemBody, etag, noneMatch);
}
protected static final String TEXT_CALENDAR = "text/calendar";
protected static final String APPLICATION_ICS = "application/ics";
protected boolean isCalendarContentType(String contentType) {
return TEXT_CALENDAR.regionMatches(true, 0, contentType, 0, TEXT_CALENDAR.length()) ||
APPLICATION_ICS.regionMatches(true, 0, contentType, 0, APPLICATION_ICS.length());
}
protected MimePart getCalendarMimePart(MimeMultipart multiPart) throws IOException, MessagingException {
MimePart bodyPart = null;
for (int i = 0; i < multiPart.getCount(); i++) {
String contentType = multiPart.getBodyPart(i).getContentType();
if (isCalendarContentType(contentType)) {
bodyPart = (MimePart) multiPart.getBodyPart(i);
break;
} else if (contentType.startsWith("multipart")) {
Object content = multiPart.getBodyPart(i).getContent();
if (content instanceof MimeMultipart) {
bodyPart = getCalendarMimePart((MimeMultipart) content);
}
}
}
return bodyPart;
}
/**
* Load ICS content from MIME message input stream
*
* @param mimeInputStream mime message input stream
* @return mime message ics attachment body
* @throws IOException on error
* @throws MessagingException on error
*/
protected byte[] getICS(InputStream mimeInputStream) throws IOException, MessagingException {
byte[] result;
MimeMessage mimeMessage = new MimeMessage(null, mimeInputStream);
Object mimeBody = mimeMessage.getContent();
MimePart bodyPart = null;
if (mimeBody instanceof MimeMultipart) {
bodyPart = getCalendarMimePart((MimeMultipart) mimeBody);
} else if (isCalendarContentType(mimeMessage.getContentType())) {
// no multipart, single body
bodyPart = mimeMessage;
}
if (bodyPart != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bodyPart.getDataHandler().writeTo(baos);
baos.close();
result = baos.toByteArray();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.writeTo(baos);
baos.close();
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", new String(baos.toByteArray(), "UTF-8"));
}
return result;
}
protected byte[] getICSFromInternetContentProperty() throws IOException, DavException, MessagingException {
byte[] result = null;
// PropFind PR_INTERNET_CONTENT
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
davPropertyNameSet.add(Field.getPropertyName("internetContent"));
PropFindMethod propFindMethod = new PropFindMethod(URIUtil.encodePath(permanentUrl), davPropertyNameSet, 0);
try {
DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propFindMethod);
MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
if (responses.getResponses().length > 0) {
DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
String propertyValue = getPropertyIfExists(properties, "internetContent");
if (propertyValue != null) {
byte[] byteArray = Base64.decodeBase64(propertyValue.getBytes());
result = getICS(new ByteArrayInputStream(byteArray));
}
}
} finally {
propFindMethod.releaseConnection();
}
return result;
}
/**
* Load ICS content from Exchange server.
* User Translate: f header to get MIME event content and get ICS attachment from it
*
* @return ICS (iCalendar) event
* @throws HttpException on error
*/
@Override
public byte[] getEventContent() throws IOException {
byte[] result = null;
LOGGER.debug("Get event subject: " + subject + " permanentUrl: " + permanentUrl);
// try to get PR_INTERNET_CONTENT
try {
result = getICSFromInternetContentProperty();
if (result == null) {
GetMethod method = new GetMethod(permanentUrl);
method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
method.setRequestHeader("Translate", "f");
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true);
result = getICS(method.getResponseBodyAsStream());
} finally {
method.releaseConnection();
}
}
} catch (DavException e) {
throw buildHttpException(e);
} catch (IOException e) {
LOGGER.warn(e.getMessage());
} catch (MessagingException e) {
throw buildHttpException(e);
}
// failover: rebuild event from MAPI properties
if (result == null) {
try {
result = getICSFromItemProperties();
} catch (HttpException e) {
deleteBroken();
throw e;
}
}
// debug code
/*if (new String(result).indexOf("VTODO") < 0) {
LOGGER.debug("Original body: " + new String(result));
result = getICSFromItemProperties();
LOGGER.debug("Rebuilt body: " + new String(result));
}*/
return result;
}
private byte[] getICSFromItemProperties() throws IOException {
byte[] result = null;
// experimental: build VCALENDAR from properties
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
davPropertyNameSet.add(Field.getPropertyName("method"));
davPropertyNameSet.add(Field.getPropertyName("created"));
davPropertyNameSet.add(Field.getPropertyName("calendarlastmodified"));
davPropertyNameSet.add(Field.getPropertyName("dtstamp"));
davPropertyNameSet.add(Field.getPropertyName("calendaruid"));
davPropertyNameSet.add(Field.getPropertyName("subject"));
davPropertyNameSet.add(Field.getPropertyName("dtstart"));
davPropertyNameSet.add(Field.getPropertyName("dtend"));
davPropertyNameSet.add(Field.getPropertyName("transparent"));
davPropertyNameSet.add(Field.getPropertyName("organizer"));
davPropertyNameSet.add(Field.getPropertyName("to"));
davPropertyNameSet.add(Field.getPropertyName("description"));
davPropertyNameSet.add(Field.getPropertyName("rrule"));
davPropertyNameSet.add(Field.getPropertyName("exdate"));
davPropertyNameSet.add(Field.getPropertyName("sensitivity"));
davPropertyNameSet.add(Field.getPropertyName("alldayevent"));
davPropertyNameSet.add(Field.getPropertyName("busystatus"));
davPropertyNameSet.add(Field.getPropertyName("reminderset"));
davPropertyNameSet.add(Field.getPropertyName("reminderdelta"));
PropFindMethod propFindMethod = new PropFindMethod(permanentUrl, davPropertyNameSet, 0);
try {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
if (responses.length == 0) {
throw new HttpNotFoundException(permanentUrl + " not found");
}
DavPropertySet davPropertySet = responses[0].getProperties(HttpStatus.SC_OK);
VCalendar localVCalendar = new VCalendar();
localVCalendar.setPropertyValue("PRODID", "-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN");
localVCalendar.setPropertyValue("VERSION", "2.0");
localVCalendar.setPropertyValue("METHOD", getPropertyIfExists(davPropertySet, "method"));
VObject vEvent = new VObject();
vEvent.type = "VEVENT";
vEvent.setPropertyValue("CREATED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "created")));
vEvent.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "calendarlastmodified")));
vEvent.setPropertyValue("DTSTAMP", convertDateFromExchange(getPropertyIfExists(davPropertySet, "dtstamp")));
vEvent.setPropertyValue("UID", getPropertyIfExists(davPropertySet, "calendaruid"));
vEvent.setPropertyValue("SUMMARY", getPropertyIfExists(davPropertySet, "subject"));
// check mandatory dtstart value
String dtstart = getPropertyIfExists(davPropertySet, "dtstart");
if (dtstart != null) {
vEvent.setPropertyValue("DTSTART", convertDateFromExchange(dtstart));
} else {
LOGGER.warn("missing dtstart on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTSTART", "20000101T000000Z");
deleteBroken();
}
// same on DTEND
String dtend = getPropertyIfExists(davPropertySet, "dtend");
if (dtend != null) {
- vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtstart));
+ vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtend));
} else {
LOGGER.warn("missing dtend on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTEND", "20000101T010000Z");
deleteBroken();
}
vEvent.setPropertyValue("TRANSP", getPropertyIfExists(davPropertySet, "transparent"));
vEvent.setPropertyValue("RRULE", getPropertyIfExists(davPropertySet, "rrule"));
String exdates = getPropertyIfExists(davPropertySet, "exdate");
if (exdates != null) {
String[] exdatearray = exdates.split(",");
for (String exdate : exdatearray) {
vEvent.addPropertyValue("EXDATE",
StringUtil.convertZuluDateTimeToAllDay(convertDateFromExchange(exdate)));
}
}
String sensitivity = getPropertyIfExists(davPropertySet, "sensitivity");
if ("2".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PRIVATE");
} else if ("3".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "CONFIDENTIAL");
} else if ("0".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PUBLIC");
}
String organizer = getPropertyIfExists(davPropertySet, "organizer");
String organizerEmail = null;
if (organizer != null) {
InternetAddress organizerAddress = new InternetAddress(organizer);
organizerEmail = organizerAddress.getAddress();
vEvent.setPropertyValue("ORGANIZER", "MAILTO:" + organizerEmail);
}
// Parse attendee list
String toHeader = getPropertyIfExists(davPropertySet, "to");
if (toHeader != null && !organizerEmail.equals(toHeader)) {
InternetAddress[] attendees = InternetAddress.parseHeader(toHeader, false);
for (InternetAddress attendee : attendees) {
if (!attendee.getAddress().equalsIgnoreCase(organizerEmail)) {
VProperty vProperty = new VProperty("ATTENDEE", attendee.getAddress());
if (attendee.getPersonal() != null) {
vProperty.addParam("CN", attendee.getPersonal());
}
vEvent.addProperty(vProperty);
}
}
}
vEvent.setPropertyValue("DESCRIPTION", getPropertyIfExists(davPropertySet, "description"));
vEvent.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT",
"1".equals(getPropertyIfExists(davPropertySet, "alldayevent")) ? "TRUE" : "FALSE");
vEvent.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS", getPropertyIfExists(davPropertySet, "busystatus"));
if ("1".equals(getPropertyIfExists(davPropertySet, "reminderset"))) {
VObject vAlarm = new VObject();
vAlarm.type = "VALARM";
vAlarm.setPropertyValue("ACTION", "DISPLAY");
vAlarm.setPropertyValue("DISPLAY", "Reminder");
String reminderdelta = getPropertyIfExists(davPropertySet, "reminderdelta");
VProperty vProperty = new VProperty("TRIGGER", "-PT" + reminderdelta + 'M');
vProperty.addParam("VALUE", "DURATION");
vAlarm.addProperty(vProperty);
vEvent.addVObject(vAlarm);
}
localVCalendar.addVObject(vEvent);
result = localVCalendar.toString().getBytes("UTF-8");
} catch (MessagingException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} catch (IOException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} finally {
propFindMethod.releaseConnection();
}
return result;
}
protected void deleteBroken() {
// try to delete broken event
if (Settings.getBooleanProperty("davmail.deleteBroken")) {
LOGGER.warn("Deleting broken event at: " + permanentUrl);
try {
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, permanentUrl);
} catch (IOException ioe) {
LOGGER.warn("Unable to delete broken event at: " + permanentUrl);
}
}
}
protected PutMethod internalCreateOrUpdate(String encodedHref, byte[] mimeContent) throws IOException {
PutMethod putmethod = new PutMethod(encodedHref);
putmethod.setRequestHeader("Translate", "f");
putmethod.setRequestHeader("Overwrite", "f");
if (etag != null) {
putmethod.setRequestHeader("If-Match", etag);
}
if (noneMatch != null) {
putmethod.setRequestHeader("If-None-Match", noneMatch);
}
putmethod.setRequestHeader("Content-Type", "message/rfc822");
putmethod.setRequestEntity(new ByteArrayRequestEntity(mimeContent, "message/rfc822"));
try {
httpClient.executeMethod(putmethod);
} finally {
putmethod.releaseConnection();
}
return putmethod;
}
/**
* @inheritDoc
*/
@Override
public ItemResult createOrUpdate() throws IOException {
byte[] mimeContent = createMimeContent();
String encodedHref = URIUtil.encodePath(getHref());
PutMethod putMethod = internalCreateOrUpdate(encodedHref, mimeContent);
int status = putMethod.getStatusCode();
if (status == HttpStatus.SC_OK) {
LOGGER.debug("Updated event " + encodedHref);
} else if (status == HttpStatus.SC_CREATED) {
LOGGER.debug("Created event " + encodedHref);
} else if (status == HttpStatus.SC_NOT_FOUND) {
LOGGER.debug("Event not found at " + encodedHref + ", searching permanenturl by urlcompname");
// failover, search item by urlcompname
MultiStatusResponse[] responses = searchItems(folderPath, EVENT_REQUEST_PROPERTIES, DavExchangeSession.this.isEqualTo("urlcompname", convertItemNameToEML(itemName)), FolderQueryTraversal.Shallow, 1);
if (responses.length == 1) {
encodedHref = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "permanenturl");
LOGGER.warn("Event found, permanenturl is " + encodedHref);
putMethod = internalCreateOrUpdate(encodedHref, mimeContent);
status = putMethod.getStatusCode();
if (status == HttpStatus.SC_OK) {
LOGGER.debug("Updated event " + encodedHref);
} else {
LOGGER.warn("Unable to create or update event " + status + ' ' + putMethod.getStatusLine());
}
}
} else {
LOGGER.warn("Unable to create or update event " + status + ' ' + putMethod.getStatusLine());
}
ItemResult itemResult = new ItemResult();
// 440 means forbidden on Exchange
if (status == 440) {
status = HttpStatus.SC_FORBIDDEN;
}
itemResult.status = status;
if (putMethod.getResponseHeader("GetETag") != null) {
itemResult.etag = putMethod.getResponseHeader("GetETag").getValue();
}
// trigger activeSync push event, only if davmail.forceActiveSyncUpdate setting is true
if ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) &&
(Settings.getBooleanProperty("davmail.forceActiveSyncUpdate"))) {
ArrayList<DavConstants> propertyList = new ArrayList<DavConstants>();
// Set contentclass to make ActiveSync happy
propertyList.add(Field.createDavProperty("contentclass", contentClass));
// ... but also set PR_INTERNET_CONTENT to preserve custom properties
propertyList.add(Field.createDavProperty("internetContent", new String(Base64.encodeBase64(mimeContent))));
PropPatchMethod propPatchMethod = new PropPatchMethod(encodedHref, propertyList);
int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
if (patchStatus != HttpStatus.SC_MULTI_STATUS) {
LOGGER.warn("Unable to patch event to trigger activeSync push");
} else {
// need to retrieve new etag
Item newItem = getItem(folderPath, itemName);
itemResult.etag = newItem.etag;
}
}
return itemResult;
}
}
protected Folder buildFolder(MultiStatusResponse entity) throws IOException {
String href = URIUtil.decode(entity.getHref());
Folder folder = new Folder();
DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK);
folder.displayName = getPropertyIfExists(properties, "displayname");
folder.folderClass = getPropertyIfExists(properties, "folderclass");
folder.hasChildren = "1".equals(getPropertyIfExists(properties, "hassubs"));
folder.noInferiors = "1".equals(getPropertyIfExists(properties, "nosubs"));
folder.unreadCount = getIntPropertyIfExists(properties, "unreadcount");
folder.ctag = getPropertyIfExists(properties, "contenttag");
folder.etag = getPropertyIfExists(properties, "lastmodified");
folder.uidNext = getIntPropertyIfExists(properties, "uidNext");
// replace well known folder names
if (inboxUrl != null && href.startsWith(inboxUrl)) {
folder.folderPath = href.replaceFirst(inboxUrl, INBOX);
} else if (sentitemsUrl != null && href.startsWith(sentitemsUrl)) {
folder.folderPath = href.replaceFirst(sentitemsUrl, SENT);
} else if (draftsUrl != null && href.startsWith(draftsUrl)) {
folder.folderPath = href.replaceFirst(draftsUrl, DRAFTS);
} else if (deleteditemsUrl != null && href.startsWith(deleteditemsUrl)) {
folder.folderPath = href.replaceFirst(deleteditemsUrl, TRASH);
} else if (calendarUrl != null && href.startsWith(calendarUrl)) {
folder.folderPath = href.replaceFirst(calendarUrl, CALENDAR);
} else if (contactsUrl != null && href.startsWith(contactsUrl)) {
folder.folderPath = href.replaceFirst(contactsUrl, CONTACTS);
} else {
int index = href.indexOf(mailPath.substring(0, mailPath.length() - 1));
if (index >= 0) {
if (index + mailPath.length() > href.length()) {
folder.folderPath = "";
} else {
folder.folderPath = href.substring(index + mailPath.length());
}
} else {
try {
URI folderURI = new URI(href, false);
folder.folderPath = folderURI.getPath();
} catch (URIException e) {
throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", href);
}
}
}
if (folder.folderPath.endsWith("/")) {
folder.folderPath = folder.folderPath.substring(0, folder.folderPath.length() - 1);
}
return folder;
}
protected static final Set<String> FOLDER_PROPERTIES = new HashSet<String>();
static {
FOLDER_PROPERTIES.add("displayname");
FOLDER_PROPERTIES.add("folderclass");
FOLDER_PROPERTIES.add("hassubs");
FOLDER_PROPERTIES.add("nosubs");
FOLDER_PROPERTIES.add("unreadcount");
FOLDER_PROPERTIES.add("contenttag");
FOLDER_PROPERTIES.add("lastmodified");
FOLDER_PROPERTIES.add("uidNext");
}
protected static final DavPropertyNameSet FOLDER_PROPERTIES_NAME_SET = new DavPropertyNameSet();
static {
for (String attribute : FOLDER_PROPERTIES) {
FOLDER_PROPERTIES_NAME_SET.add(Field.getPropertyName(attribute));
}
}
/**
* @inheritDoc
*/
@Override
public Folder getFolder(String folderPath) throws IOException {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(getFolderPath(folderPath)), 0, FOLDER_PROPERTIES_NAME_SET);
Folder folder = null;
if (responses.length > 0) {
folder = buildFolder(responses[0]);
folder.folderPath = folderPath;
}
return folder;
}
/**
* @inheritDoc
*/
@Override
public List<Folder> getSubFolders(String folderPath, Condition condition, boolean recursive) throws IOException {
boolean isPublic = folderPath.startsWith("/public");
FolderQueryTraversal mode = (!isPublic && recursive) ? FolderQueryTraversal.Deep : FolderQueryTraversal.Shallow;
List<Folder> folders = new ArrayList<Folder>();
MultiStatusResponse[] responses = searchItems(folderPath, FOLDER_PROPERTIES, and(isTrue("isfolder"), isFalse("ishidden"), condition), mode, 0);
for (MultiStatusResponse response : responses) {
Folder folder = buildFolder(response);
folders.add(buildFolder(response));
if (isPublic && recursive) {
getSubFolders(folder.folderPath, condition, recursive);
}
}
return folders;
}
/**
* @inheritDoc
*/
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
Set<PropertyValue> propertyValues = new HashSet<PropertyValue>();
if (properties != null) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
}
}
propertyValues.add(Field.createPropertyValue("folderclass", folderClass));
// standard MkColMethod does not take properties, override PropPatchMethod instead
ExchangePropPatchMethod method = new ExchangePropPatchMethod(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues) {
@Override
public String getName() {
return "MKCOL";
}
};
int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
if (status == HttpStatus.SC_MULTI_STATUS) {
status = method.getResponseStatusCode();
}
return status;
}
/**
* @inheritDoc
*/
@Override
public void deleteFolder(String folderPath) throws IOException {
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, URIUtil.encodePath(getFolderPath(folderPath)));
}
/**
* @inheritDoc
*/
@Override
public void moveFolder(String folderPath, String targetPath) throws IOException {
MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(folderPath)),
URIUtil.encodePath(getFolderPath(targetPath)), false);
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new HttpPreconditionFailedException(BundleMessage.format("EXCEPTION_UNABLE_TO_MOVE_FOLDER"));
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
} else if (folderPath.equalsIgnoreCase("/users/" + getEmail() + "/calendar")) {
// calendar renamed, need to reload well known folders
getWellKnownFolders();
}
} finally {
method.releaseConnection();
}
}
/**
* @inheritDoc
*/
@Override
public void moveItem(String sourcePath, String targetPath) throws IOException {
MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(sourcePath)),
URIUtil.encodePath(getFolderPath(targetPath)), false);
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_ITEM");
} else if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
} finally {
method.releaseConnection();
}
}
protected String getPropertyIfExists(DavPropertySet properties, String alias) {
DavProperty property = properties.get(Field.getResponsePropertyName(alias));
if (property == null) {
return null;
} else {
Object value = property.getValue();
if (value instanceof Node) {
return ((Node) value).getTextContent();
} else if (value instanceof List) {
StringBuilder buffer = new StringBuilder();
for (Object node : (List) value) {
if (buffer.length() > 0) {
buffer.append(',');
}
buffer.append(((Node) node).getTextContent());
}
return buffer.toString();
} else {
return (String) value;
}
}
}
protected int getIntPropertyIfExists(DavPropertySet properties, String alias) {
DavProperty property = properties.get(Field.getPropertyName(alias));
if (property == null) {
return 0;
} else {
return Integer.parseInt((String) property.getValue());
}
}
protected long getLongPropertyIfExists(DavPropertySet properties, String alias) {
DavProperty property = properties.get(Field.getPropertyName(alias));
if (property == null) {
return 0;
} else {
return Long.parseLong((String) property.getValue());
}
}
protected byte[] getBinaryPropertyIfExists(DavPropertySet properties, String alias) {
byte[] property = null;
String base64Property = getPropertyIfExists(properties, alias);
if (base64Property != null) {
try {
property = Base64.decodeBase64(base64Property.getBytes("ASCII"));
} catch (UnsupportedEncodingException e) {
LOGGER.warn(e);
}
}
return property;
}
protected Message buildMessage(MultiStatusResponse responseEntity) throws URIException, DavMailException {
Message message = new Message();
message.messageUrl = URIUtil.decode(responseEntity.getHref());
DavPropertySet properties = responseEntity.getProperties(HttpStatus.SC_OK);
message.permanentUrl = getPropertyIfExists(properties, "permanenturl");
message.size = getIntPropertyIfExists(properties, "messageSize");
message.uid = getPropertyIfExists(properties, "uid");
message.imapUid = getLongPropertyIfExists(properties, "imapUid");
message.read = "1".equals(getPropertyIfExists(properties, "read"));
message.junk = "1".equals(getPropertyIfExists(properties, "junk"));
message.flagged = "2".equals(getPropertyIfExists(properties, "flagStatus"));
message.draft = (getIntPropertyIfExists(properties, "messageFlags") & 8) != 0;
String lastVerbExecuted = getPropertyIfExists(properties, "lastVerbExecuted");
message.answered = "102".equals(lastVerbExecuted) || "103".equals(lastVerbExecuted);
message.forwarded = "104".equals(lastVerbExecuted);
message.date = convertDateFromExchange(getPropertyIfExists(properties, "date"));
message.deleted = "1".equals(getPropertyIfExists(properties, "deleted"));
if (LOGGER.isDebugEnabled()) {
StringBuilder buffer = new StringBuilder();
buffer.append("Message");
if (message.imapUid != 0) {
buffer.append(" IMAP uid: ").append(message.imapUid);
}
if (message.uid != null) {
buffer.append(" uid: ").append(message.uid);
}
buffer.append(" href: ").append(responseEntity.getHref()).append(" permanenturl:").append(message.permanentUrl);
LOGGER.debug(buffer.toString());
}
return message;
}
@Override
public MessageList searchMessages(String folderPath, Set<String> attributes, Condition condition) throws IOException {
MessageList messages = new MessageList();
MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow, 0);
for (MultiStatusResponse response : responses) {
Message message = buildMessage(response);
message.messageList = messages;
messages.add(message);
}
Collections.sort(messages);
return messages;
}
/**
* @inheritDoc
*/
@Override
public List<ExchangeSession.Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition, int maxCount) throws IOException {
List<ExchangeSession.Contact> contacts = new ArrayList<ExchangeSession.Contact>();
MultiStatusResponse[] responses = searchItems(folderPath, attributes,
and(isEqualTo("outlookmessageclass", "IPM.Contact"), isFalse("isfolder"), isFalse("ishidden"), condition),
FolderQueryTraversal.Shallow, maxCount);
for (MultiStatusResponse response : responses) {
contacts.add(new Contact(response));
}
return contacts;
}
/**
* @inheritDoc
*/
@Override
public List<ExchangeSession.Event> getEventMessages(String folderPath) throws IOException {
return searchEvents(folderPath, ITEM_PROPERTIES,
and(isEqualTo("contentclass", "urn:content-classes:calendarmessage"),
or(isNull("processed"), isFalse("processed"))));
}
@Override
public List<ExchangeSession.Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException {
List<ExchangeSession.Event> events = new ArrayList<ExchangeSession.Event>();
MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow, 0);
for (MultiStatusResponse response : responses) {
String instancetype = getPropertyIfExists(response.getProperties(HttpStatus.SC_OK), "instancetype");
Event event = new Event(response);
//noinspection VariableNotUsedInsideIf
if (instancetype == null) {
// check ics content
try {
event.getBody();
// getBody success => add event or task
events.add(event);
} catch (IOException e) {
// invalid event: exclude from list
LOGGER.warn("Invalid event " + event.displayName + " found at " + response.getHref(), e);
}
} else {
events.add(event);
}
}
return events;
}
protected MultiStatusResponse[] searchItems(String folderPath, Set<String> attributes, Condition condition,
FolderQueryTraversal folderQueryTraversal, int maxCount) throws IOException {
String folderUrl = getFolderPath(folderPath);
StringBuilder searchRequest = new StringBuilder();
searchRequest.append("SELECT ")
.append(Field.getRequestPropertyString("permanenturl"));
if (attributes != null) {
for (String attribute : attributes) {
searchRequest.append(',').append(Field.getRequestPropertyString(attribute));
}
}
searchRequest.append(" FROM SCOPE('").append(folderQueryTraversal).append(" TRAVERSAL OF \"").append(folderUrl).append("\"')");
if (condition != null) {
searchRequest.append(" WHERE ");
condition.appendTo(searchRequest);
}
DavGatewayTray.debug(new BundleMessage("LOG_SEARCH_QUERY", searchRequest));
return DavGatewayHttpClientFacade.executeSearchMethod(
httpClient, URIUtil.encodePath(folderUrl), searchRequest.toString(), maxCount);
}
protected static final Set<String> EVENT_REQUEST_PROPERTIES = new HashSet<String>();
static {
EVENT_REQUEST_PROPERTIES.add("permanenturl");
EVENT_REQUEST_PROPERTIES.add("urlcompname");
EVENT_REQUEST_PROPERTIES.add("etag");
EVENT_REQUEST_PROPERTIES.add("contentclass");
EVENT_REQUEST_PROPERTIES.add("displayname");
EVENT_REQUEST_PROPERTIES.add("subject");
}
protected static final DavPropertyNameSet EVENT_REQUEST_PROPERTIES_NAME_SET = new DavPropertyNameSet();
static {
for (String attribute : EVENT_REQUEST_PROPERTIES) {
EVENT_REQUEST_PROPERTIES_NAME_SET.add(Field.getPropertyName(attribute));
}
}
@Override
public Item getItem(String folderPath, String itemName) throws IOException {
String emlItemName = convertItemNameToEML(itemName);
String itemPath = getFolderPath(folderPath) + '/' + emlItemName;
MultiStatusResponse[] responses = null;
try {
responses = DavGatewayHttpClientFacade.executePropFindMethod(httpClient, URIUtil.encodePath(itemPath), 0, EVENT_REQUEST_PROPERTIES_NAME_SET);
if (responses.length == 0) {
throw new HttpNotFoundException(itemPath + " not found");
}
} catch (HttpNotFoundException e) {
try {
LOGGER.debug(itemPath + " not found, searching by urlcompname");
// failover: try to get event by displayname
responses = searchItems(folderPath, EVENT_REQUEST_PROPERTIES, isEqualTo("urlcompname", emlItemName), FolderQueryTraversal.Shallow, 1);
if (responses.length == 0) {
throw new HttpNotFoundException(itemPath + " not found");
}
} catch (HttpNotFoundException e2) {
LOGGER.debug("last failover: search all items");
List<ExchangeSession.Event> events = getAllEvents(folderPath);
for (ExchangeSession.Event event : events) {
if (itemName.equals(event.getName())) {
responses = DavGatewayHttpClientFacade.executePropFindMethod(httpClient, ((DavExchangeSession.Event) event).getPermanentUrl(), 0, EVENT_REQUEST_PROPERTIES_NAME_SET);
break;
}
}
if (responses == null || responses.length == 0) {
throw new HttpNotFoundException(itemPath + " not found");
}
LOGGER.warn("search by urlcompname failed, actual value is " + getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "urlcompname"));
}
}
// build item
String contentClass = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "contentclass");
String urlcompname = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "urlcompname");
if ("urn:content-classes:person".equals(contentClass)) {
// retrieve Contact properties
List<ExchangeSession.Contact> contacts = searchContacts(folderPath, CONTACT_ATTRIBUTES, isEqualTo("urlcompname", urlcompname), 1);
if (contacts.isEmpty()) {
LOGGER.warn("Item found, but unable to build contact");
throw new HttpNotFoundException(itemPath + " not found");
}
return contacts.get(0);
} else if ("urn:content-classes:appointment".equals(contentClass)
|| "urn:content-classes:calendarmessage".equals(contentClass)) {
return new Event(responses[0]);
} else {
LOGGER.warn("wrong contentclass on item " + itemPath + ": " + contentClass);
// return item anyway
return new Event(responses[0]);
}
}
@Override
public ExchangeSession.ContactPhoto getContactPhoto(ExchangeSession.Contact contact) throws IOException {
ContactPhoto contactPhoto = null;
if ("true".equals(contact.get("haspicture"))) {
final GetMethod method = new GetMethod(URIUtil.encodePath(contact.getHref()) + "/ContactPicture.jpg");
method.setRequestHeader("Translate", "f");
method.setRequestHeader("Accept-Encoding", "gzip");
InputStream inputStream = null;
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true);
if (isGzipEncoded(method)) {
inputStream = (new GZIPInputStream(method.getResponseBodyAsStream()));
} else {
inputStream = method.getResponseBodyAsStream();
}
contactPhoto = new ContactPhoto();
contactPhoto.contentType = "image/jpeg";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream partInputStream = inputStream;
byte[] bytes = new byte[8192];
int length;
while ((length = partInputStream.read(bytes)) > 0) {
baos.write(bytes, 0, length);
}
contactPhoto.content = new String(Base64.encodeBase64(baos.toByteArray()));
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.debug(e);
}
}
method.releaseConnection();
}
}
return contactPhoto;
}
@Override
public int sendEvent(String icsBody) throws IOException {
String itemName = UUID.randomUUID().toString() + ".EML";
byte[] mimeContent = (new Event(getFolderPath(DRAFTS), itemName, "urn:content-classes:calendarmessage", icsBody, null, null)).createMimeContent();
if (mimeContent == null) {
// no recipients, cancel
return HttpStatus.SC_NO_CONTENT;
} else {
sendMessage(mimeContent);
return HttpStatus.SC_OK;
}
}
@Override
public void deleteItem(String folderPath, String itemName) throws IOException {
String eventPath = URIUtil.encodePath(getFolderPath(folderPath) + '/' + convertItemNameToEML(itemName));
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, eventPath);
}
@Override
public void processItem(String folderPath, String itemName) throws IOException {
String eventPath = URIUtil.encodePath(getFolderPath(folderPath) + '/' + convertItemNameToEML(itemName));
// do not delete calendar messages, mark read and processed
ArrayList<DavConstants> list = new ArrayList<DavConstants>();
list.add(Field.createDavProperty("processed", "true"));
list.add(Field.createDavProperty("read", "1"));
PropPatchMethod patchMethod = new PropPatchMethod(eventPath, list);
DavGatewayHttpClientFacade.executeMethod(httpClient, patchMethod);
}
@Override
public ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException {
return new Event(getFolderPath(folderPath), itemName, contentClass, icsBody, etag, noneMatch).createOrUpdate();
}
/**
* create a fake event to get VTIMEZONE body
*/
@Override
protected void loadVtimezone() {
try {
// create temporary folder
String folderPath = getFolderPath("davmailtemp");
createCalendarFolder(folderPath, null);
PostMethod postMethod = new PostMethod(URIUtil.encodePath(folderPath));
postMethod.addParameter("Cmd", "saveappt");
postMethod.addParameter("FORMTYPE", "appointment");
String fakeEventUrl = null;
try {
// create fake event
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
fakeEventUrl = StringUtil.getToken(postMethod.getResponseBodyAsString(), "<span id=\"itemHREF\">", "</span>");
}
} finally {
postMethod.releaseConnection();
}
// failover for Exchange 2007, use PROPPATCH with forced timezone
if (fakeEventUrl == null) {
ArrayList<DavConstants> propertyList = new ArrayList<DavConstants>();
propertyList.add(Field.createDavProperty("contentclass", "urn:content-classes:appointment"));
propertyList.add(Field.createDavProperty("outlookmessageclass", "IPM.Appointment"));
propertyList.add(Field.createDavProperty("instancetype", "0"));
// get forced timezone id from settings
String timezoneId = Settings.getProperty("davmail.timezoneId");
if (timezoneId == null) {
// get timezoneid from OWA settings
timezoneId = getTimezoneIdFromExchange();
}
// without a timezoneId, use Exchange timezone
if (timezoneId != null) {
propertyList.add(Field.createDavProperty("timezoneid", timezoneId));
}
String patchMethodUrl = URIUtil.encodePath(folderPath) + '/' + UUID.randomUUID().toString() + ".EML";
PropPatchMethod patchMethod = new PropPatchMethod(URIUtil.encodePath(patchMethodUrl), propertyList);
try {
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode == HttpStatus.SC_MULTI_STATUS) {
fakeEventUrl = patchMethodUrl;
}
} finally {
patchMethod.releaseConnection();
}
}
if (fakeEventUrl != null) {
// get fake event body
GetMethod getMethod = new GetMethod(URIUtil.encodePath(fakeEventUrl));
getMethod.setRequestHeader("Translate", "f");
try {
httpClient.executeMethod(getMethod);
this.vTimezone = new VObject("BEGIN:VTIMEZONE" +
StringUtil.getToken(getMethod.getResponseBodyAsString(), "BEGIN:VTIMEZONE", "END:VTIMEZONE") +
"END:VTIMEZONE\r\n");
} finally {
getMethod.releaseConnection();
}
}
// delete temporary folder
deleteFolder("davmailtemp");
} catch (IOException e) {
LOGGER.warn("Unable to get VTIMEZONE info: " + e, e);
}
}
protected String getTimezoneIdFromExchange() {
String timezoneId = null;
String timezoneName = null;
try {
Set<String> attributes = new HashSet<String>();
attributes.add("roamingdictionary");
MultiStatusResponse[] responses = searchItems("/users/" + getEmail() + "/NON_IPM_SUBTREE", attributes, isEqualTo("messageclass", "IPM.Configuration.OWA.UserOptions"), DavExchangeSession.FolderQueryTraversal.Deep, 1);
if (responses.length == 1) {
byte[] roamingdictionary = getBinaryPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "roamingdictionary");
if (roamingdictionary != null) {
timezoneName = getTimezoneNameFromRoamingDictionary(roamingdictionary);
timezoneId = ResourceBundle.getBundle("timezoneids").getString(timezoneName);
}
}
} catch (MissingResourceException e) {
LOGGER.warn("Unable to retrieve Exchange timezone id for name " + timezoneName);
} catch (UnsupportedEncodingException e) {
LOGGER.warn("Unable to retrieve Exchange timezone id: " + e.getMessage(), e);
} catch (IOException e) {
LOGGER.warn("Unable to retrieve Exchange timezone id: " + e.getMessage(), e);
}
return timezoneId;
}
protected String getTimezoneNameFromRoamingDictionary(byte[] roamingdictionary) {
String timezoneName = null;
XMLStreamReader reader;
try {
reader = XMLStreamUtil.createXMLStreamReader(roamingdictionary);
while (reader.hasNext()) {
reader.next();
if (XMLStreamUtil.isStartTag(reader, "e")
&& "18-timezone".equals(reader.getAttributeValue(null, "k"))) {
String value = reader.getAttributeValue(null, "v");
if (value != null && value.startsWith("18-")) {
timezoneName = value.substring(3);
}
}
}
} catch (XMLStreamException e) {
LOGGER.error("Error while parsing RoamingDictionary: " + e, e);
}
return timezoneName;
}
@Override
protected ItemResult internalCreateOrUpdateContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) throws IOException {
return new Contact(getFolderPath(folderPath), itemName, properties, etag, noneMatch).createOrUpdate();
}
protected List<DavConstants> buildProperties(Map<String, String> properties) {
ArrayList<DavConstants> list = new ArrayList<DavConstants>();
if (properties != null) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
if ("read".equals(entry.getKey())) {
list.add(Field.createDavProperty("read", entry.getValue()));
} else if ("junk".equals(entry.getKey())) {
list.add(Field.createDavProperty("junk", entry.getValue()));
} else if ("flagged".equals(entry.getKey())) {
list.add(Field.createDavProperty("flagStatus", entry.getValue()));
} else if ("answered".equals(entry.getKey())) {
list.add(Field.createDavProperty("lastVerbExecuted", entry.getValue()));
if ("102".equals(entry.getValue())) {
list.add(Field.createDavProperty("iconIndex", "261"));
}
} else if ("forwarded".equals(entry.getKey())) {
list.add(Field.createDavProperty("lastVerbExecuted", entry.getValue()));
if ("104".equals(entry.getValue())) {
list.add(Field.createDavProperty("iconIndex", "262"));
}
} else if ("bcc".equals(entry.getKey())) {
list.add(Field.createDavProperty("bcc", entry.getValue()));
} else if ("deleted".equals(entry.getKey())) {
list.add(Field.createDavProperty("deleted", entry.getValue()));
} else if ("datereceived".equals(entry.getKey())) {
list.add(Field.createDavProperty("datereceived", entry.getValue()));
}
}
}
return list;
}
/**
* Create message in specified folder.
* Will overwrite an existing message with same messageName in the same folder
*
* @param folderPath Exchange folder path
* @param messageName message name
* @param properties message properties (flags)
* @param mimeMessage MIME message
* @throws IOException when unable to create message
*/
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException {
String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
PropPatchMethod patchMethod;
List<DavConstants> davProperties = buildProperties(properties);
if (properties != null && properties.containsKey("draft")) {
// note: draft is readonly after create, create the message first with requested messageFlags
davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
}
if (properties != null && properties.containsKey("mailOverrideFormat")) {
davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
}
if (properties != null && properties.containsKey("messageFormat")) {
davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
}
if (!davProperties.isEmpty()) {
patchMethod = new PropPatchMethod(messageUrl, davProperties);
try {
// update message with blind carbon copy and other flags
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
patchMethod.releaseConnection();
}
}
// update message body
PutMethod putmethod = new PutMethod(messageUrl);
putmethod.setRequestHeader("Translate", "f");
putmethod.setRequestHeader("Content-Type", "message/rfc822");
try {
// use same encoding as client socket reader
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.writeTo(baos);
baos.close();
putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
int code = httpClient.executeMethod(putmethod);
if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {
// first delete draft message
if (!davProperties.isEmpty()) {
try {
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
} catch (IOException e) {
LOGGER.warn("Unable to delete draft message");
}
}
if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
throw new InsufficientStorageException(putmethod.getStatusText());
} else {
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine());
}
}
} catch (MessagingException e) {
throw new IOException(e.getMessage());
} finally {
putmethod.releaseConnection();
}
try {
// need to update bcc after put
if (mimeMessage.getHeader("Bcc") != null) {
davProperties = new ArrayList<DavConstants>();
davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
patchMethod = new PropPatchMethod(messageUrl, davProperties);
try {
// update message with blind carbon copy
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
patchMethod.releaseConnection();
}
}
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
}
/**
* @inheritDoc
*/
@Override
public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException {
PropPatchMethod patchMethod = new PropPatchMethod(message.permanentUrl, buildProperties(properties)) {
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
// ignore response body, sometimes invalid with exchange mapi properties
}
};
try {
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE");
}
} finally {
patchMethod.releaseConnection();
}
}
/**
* @inheritDoc
*/
@Override
public void deleteMessage(ExchangeSession.Message message) throws IOException {
LOGGER.debug("Delete " + message.permanentUrl + " (" + message.messageUrl + ')');
DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, message.permanentUrl);
}
/**
* @inheritDoc
*/
@Override
public void sendMessage(byte[] messageBody) throws IOException {
try {
sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
}
protected static final long MAPI_SEND_NO_RICH_INFO = 0x00010000L;
protected static final long ENCODING_PREFERENCE = 0x00020000L;
protected static final long ENCODING_MIME = 0x00040000L;
protected static final long BODY_ENCODING_HTML = 0x00080000L;
protected static final long BODY_ENCODING_TEXT_AND_HTML = 0x00100000L;
protected static final long MAC_ATTACH_ENCODING_UUENCODE = 0x00200000L;
protected static final long MAC_ATTACH_ENCODING_APPLESINGLE = 0x00400000L;
protected static final long MAC_ATTACH_ENCODING_APPLEDOUBLE = 0x00600000L;
protected static final long OOP_DONT_LOOKUP = 0x10000000L;
@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
try {
// need to create draft first
String itemName = UUID.randomUUID().toString() + ".EML";
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("draft", "9");
String contentType = mimeMessage.getContentType();
if (contentType != null && contentType.startsWith("text/plain")) {
properties.put("messageFormat", "1");
} else {
properties.put("mailOverrideFormat", String.valueOf(ENCODING_PREFERENCE | ENCODING_MIME | BODY_ENCODING_TEXT_AND_HTML));
properties.put("messageFormat", "2");
}
createMessage(DRAFTS, itemName, properties, mimeMessage);
moveItem(DRAFTS + '/' + itemName, SENDMSG);
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
}
protected boolean isGzipEncoded(HttpMethod method) {
Header[] contentEncodingHeaders = method.getResponseHeaders("Content-Encoding");
if (contentEncodingHeaders != null) {
for (Header header : contentEncodingHeaders) {
if ("gzip".equals(header.getValue())) {
return true;
}
}
}
return false;
}
/**
* @inheritDoc
*/
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream contentInputStream = null;
try {
try {
contentInputStream = getContentInputStream(message.messageUrl);
} catch (HttpNotFoundException e) {
LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
contentInputStream = getContentInputStream(message.permanentUrl);
}
try {
IOUtil.write(contentInputStream, baos);
} finally {
contentInputStream.close();
}
} catch (IOException e) {
LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl + ", trying to rebuild from properties");
try {
DavPropertyNameSet messageProperties = new DavPropertyNameSet();
messageProperties.add(Field.getPropertyName("contentclass"));
messageProperties.add(Field.getPropertyName("message-id"));
messageProperties.add(Field.getPropertyName("from"));
messageProperties.add(Field.getPropertyName("to"));
messageProperties.add(Field.getPropertyName("cc"));
messageProperties.add(Field.getPropertyName("subject"));
messageProperties.add(Field.getPropertyName("htmldescription"));
messageProperties.add(Field.getPropertyName("body"));
PropFindMethod propFindMethod = new PropFindMethod(URIUtil.encodePath(message.permanentUrl), messageProperties, 0);
DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
if (responses.getResponses().length > 0) {
MimeMessage mimeMessage = new MimeMessage((Session) null);
DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
String propertyValue = getPropertyIfExists(properties, "contentclass");
if (propertyValue != null) {
mimeMessage.addHeader("Content-class", propertyValue);
}
propertyValue = getPropertyIfExists(properties, "from");
if (propertyValue != null) {
mimeMessage.addHeader("From", propertyValue);
}
propertyValue = getPropertyIfExists(properties, "to");
if (propertyValue != null) {
mimeMessage.addHeader("To", propertyValue);
}
propertyValue = getPropertyIfExists(properties, "cc");
if (propertyValue != null) {
mimeMessage.addHeader("Cc", propertyValue);
}
propertyValue = getPropertyIfExists(properties, "subject");
if (propertyValue != null) {
mimeMessage.setSubject(propertyValue);
}
propertyValue = getPropertyIfExists(properties, "htmldescription");
if (propertyValue != null) {
mimeMessage.setContent(propertyValue, "text/html");
} else {
propertyValue = getPropertyIfExists(properties, "body");
mimeMessage.setText(propertyValue);
}
mimeMessage.writeTo(baos);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
}
} catch (IOException e2) {
LOGGER.warn(e2);
} catch (DavException e2) {
LOGGER.warn(e2);
} catch (MessagingException e2) {
LOGGER.warn(e2);
}
// other exception
if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl);
try {
message.delete();
} catch (IOException ioe) {
LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
}
throw e;
}
}
return baos.toByteArray();
}
protected InputStream getContentInputStream(String url) throws IOException {
final GetMethod method = new GetMethod(URIUtil.encodePath(url));
method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
method.setRequestHeader("Translate", "f");
method.setRequestHeader("Accept-Encoding", "gzip");
InputStream inputStream;
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, method, true);
if (isGzipEncoded(method)) {
inputStream = new GZIPInputStream(method.getResponseBodyAsStream());
} else {
inputStream = method.getResponseBodyAsStream();
}
inputStream = new FilterInputStream(inputStream) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
method.releaseConnection();
}
}
};
} catch (HttpException e) {
method.releaseConnection();
LOGGER.warn("Unable to retrieve message at: " + url);
throw e;
}
return inputStream;
}
/**
* @inheritDoc
*/
@Override
public void copyMessage(ExchangeSession.Message message, String targetFolder) throws IOException {
try {
copyMessage(message.permanentUrl, targetFolder);
} catch (HttpNotFoundException e) {
LOGGER.debug("404 not found at permanenturl: " + message.permanentUrl + ", retry with messageurl");
copyMessage(message.messageUrl, targetFolder);
}
}
protected void copyMessage(String sourceUrl, String targetFolder) throws IOException {
String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
CopyMethod method = new CopyMethod(sourceUrl, targetPath, false);
// allow rename if a message with the same name exists
method.addRequestHeader("Allow-Rename", "t");
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new DavMailException("EXCEPTION_UNABLE_TO_COPY_MESSAGE");
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
} finally {
method.releaseConnection();
}
}
@Override
protected void moveToTrash(ExchangeSession.Message message) throws IOException {
String destination = URIUtil.encodePath(deleteditemsUrl) + '/' + UUID.randomUUID().toString();
LOGGER.debug("Deleting : " + message.permanentUrl + " to " + destination);
MoveMethod method = new MoveMethod(message.permanentUrl, destination, false);
method.addRequestHeader("Allow-rename", "t");
int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
// do not throw error if already deleted
if (status != HttpStatus.SC_CREATED && status != HttpStatus.SC_NOT_FOUND) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
if (method.getResponseHeader("Location") != null) {
destination = method.getResponseHeader("Location").getValue();
}
LOGGER.debug("Deleted to :" + destination);
}
protected String convertDateFromExchange(String exchangeDateValue) throws DavMailException {
String zuluDateValue = null;
if (exchangeDateValue != null) {
try {
zuluDateValue = getZuluDateFormat().format(getExchangeZuluDateFormatMillisecond().parse(exchangeDateValue));
} catch (ParseException e) {
throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue);
}
}
return zuluDateValue;
}
/**
* Format date to exchange search format.
*
* @param date date object
* @return formatted search date
*/
@Override
public String formatSearchDate(Date date) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS, Locale.ENGLISH);
dateFormatter.setTimeZone(GMT_TIMEZONE);
return dateFormatter.format(date);
}
}
| true | true | private byte[] getICSFromItemProperties() throws IOException {
byte[] result = null;
// experimental: build VCALENDAR from properties
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
davPropertyNameSet.add(Field.getPropertyName("method"));
davPropertyNameSet.add(Field.getPropertyName("created"));
davPropertyNameSet.add(Field.getPropertyName("calendarlastmodified"));
davPropertyNameSet.add(Field.getPropertyName("dtstamp"));
davPropertyNameSet.add(Field.getPropertyName("calendaruid"));
davPropertyNameSet.add(Field.getPropertyName("subject"));
davPropertyNameSet.add(Field.getPropertyName("dtstart"));
davPropertyNameSet.add(Field.getPropertyName("dtend"));
davPropertyNameSet.add(Field.getPropertyName("transparent"));
davPropertyNameSet.add(Field.getPropertyName("organizer"));
davPropertyNameSet.add(Field.getPropertyName("to"));
davPropertyNameSet.add(Field.getPropertyName("description"));
davPropertyNameSet.add(Field.getPropertyName("rrule"));
davPropertyNameSet.add(Field.getPropertyName("exdate"));
davPropertyNameSet.add(Field.getPropertyName("sensitivity"));
davPropertyNameSet.add(Field.getPropertyName("alldayevent"));
davPropertyNameSet.add(Field.getPropertyName("busystatus"));
davPropertyNameSet.add(Field.getPropertyName("reminderset"));
davPropertyNameSet.add(Field.getPropertyName("reminderdelta"));
PropFindMethod propFindMethod = new PropFindMethod(permanentUrl, davPropertyNameSet, 0);
try {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
if (responses.length == 0) {
throw new HttpNotFoundException(permanentUrl + " not found");
}
DavPropertySet davPropertySet = responses[0].getProperties(HttpStatus.SC_OK);
VCalendar localVCalendar = new VCalendar();
localVCalendar.setPropertyValue("PRODID", "-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN");
localVCalendar.setPropertyValue("VERSION", "2.0");
localVCalendar.setPropertyValue("METHOD", getPropertyIfExists(davPropertySet, "method"));
VObject vEvent = new VObject();
vEvent.type = "VEVENT";
vEvent.setPropertyValue("CREATED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "created")));
vEvent.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "calendarlastmodified")));
vEvent.setPropertyValue("DTSTAMP", convertDateFromExchange(getPropertyIfExists(davPropertySet, "dtstamp")));
vEvent.setPropertyValue("UID", getPropertyIfExists(davPropertySet, "calendaruid"));
vEvent.setPropertyValue("SUMMARY", getPropertyIfExists(davPropertySet, "subject"));
// check mandatory dtstart value
String dtstart = getPropertyIfExists(davPropertySet, "dtstart");
if (dtstart != null) {
vEvent.setPropertyValue("DTSTART", convertDateFromExchange(dtstart));
} else {
LOGGER.warn("missing dtstart on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTSTART", "20000101T000000Z");
deleteBroken();
}
// same on DTEND
String dtend = getPropertyIfExists(davPropertySet, "dtend");
if (dtend != null) {
vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtstart));
} else {
LOGGER.warn("missing dtend on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTEND", "20000101T010000Z");
deleteBroken();
}
vEvent.setPropertyValue("TRANSP", getPropertyIfExists(davPropertySet, "transparent"));
vEvent.setPropertyValue("RRULE", getPropertyIfExists(davPropertySet, "rrule"));
String exdates = getPropertyIfExists(davPropertySet, "exdate");
if (exdates != null) {
String[] exdatearray = exdates.split(",");
for (String exdate : exdatearray) {
vEvent.addPropertyValue("EXDATE",
StringUtil.convertZuluDateTimeToAllDay(convertDateFromExchange(exdate)));
}
}
String sensitivity = getPropertyIfExists(davPropertySet, "sensitivity");
if ("2".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PRIVATE");
} else if ("3".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "CONFIDENTIAL");
} else if ("0".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PUBLIC");
}
String organizer = getPropertyIfExists(davPropertySet, "organizer");
String organizerEmail = null;
if (organizer != null) {
InternetAddress organizerAddress = new InternetAddress(organizer);
organizerEmail = organizerAddress.getAddress();
vEvent.setPropertyValue("ORGANIZER", "MAILTO:" + organizerEmail);
}
// Parse attendee list
String toHeader = getPropertyIfExists(davPropertySet, "to");
if (toHeader != null && !organizerEmail.equals(toHeader)) {
InternetAddress[] attendees = InternetAddress.parseHeader(toHeader, false);
for (InternetAddress attendee : attendees) {
if (!attendee.getAddress().equalsIgnoreCase(organizerEmail)) {
VProperty vProperty = new VProperty("ATTENDEE", attendee.getAddress());
if (attendee.getPersonal() != null) {
vProperty.addParam("CN", attendee.getPersonal());
}
vEvent.addProperty(vProperty);
}
}
}
vEvent.setPropertyValue("DESCRIPTION", getPropertyIfExists(davPropertySet, "description"));
vEvent.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT",
"1".equals(getPropertyIfExists(davPropertySet, "alldayevent")) ? "TRUE" : "FALSE");
vEvent.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS", getPropertyIfExists(davPropertySet, "busystatus"));
if ("1".equals(getPropertyIfExists(davPropertySet, "reminderset"))) {
VObject vAlarm = new VObject();
vAlarm.type = "VALARM";
vAlarm.setPropertyValue("ACTION", "DISPLAY");
vAlarm.setPropertyValue("DISPLAY", "Reminder");
String reminderdelta = getPropertyIfExists(davPropertySet, "reminderdelta");
VProperty vProperty = new VProperty("TRIGGER", "-PT" + reminderdelta + 'M');
vProperty.addParam("VALUE", "DURATION");
vAlarm.addProperty(vProperty);
vEvent.addVObject(vAlarm);
}
localVCalendar.addVObject(vEvent);
result = localVCalendar.toString().getBytes("UTF-8");
} catch (MessagingException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} catch (IOException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} finally {
propFindMethod.releaseConnection();
}
return result;
}
| private byte[] getICSFromItemProperties() throws IOException {
byte[] result = null;
// experimental: build VCALENDAR from properties
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
davPropertyNameSet.add(Field.getPropertyName("method"));
davPropertyNameSet.add(Field.getPropertyName("created"));
davPropertyNameSet.add(Field.getPropertyName("calendarlastmodified"));
davPropertyNameSet.add(Field.getPropertyName("dtstamp"));
davPropertyNameSet.add(Field.getPropertyName("calendaruid"));
davPropertyNameSet.add(Field.getPropertyName("subject"));
davPropertyNameSet.add(Field.getPropertyName("dtstart"));
davPropertyNameSet.add(Field.getPropertyName("dtend"));
davPropertyNameSet.add(Field.getPropertyName("transparent"));
davPropertyNameSet.add(Field.getPropertyName("organizer"));
davPropertyNameSet.add(Field.getPropertyName("to"));
davPropertyNameSet.add(Field.getPropertyName("description"));
davPropertyNameSet.add(Field.getPropertyName("rrule"));
davPropertyNameSet.add(Field.getPropertyName("exdate"));
davPropertyNameSet.add(Field.getPropertyName("sensitivity"));
davPropertyNameSet.add(Field.getPropertyName("alldayevent"));
davPropertyNameSet.add(Field.getPropertyName("busystatus"));
davPropertyNameSet.add(Field.getPropertyName("reminderset"));
davPropertyNameSet.add(Field.getPropertyName("reminderdelta"));
PropFindMethod propFindMethod = new PropFindMethod(permanentUrl, davPropertyNameSet, 0);
try {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
if (responses.length == 0) {
throw new HttpNotFoundException(permanentUrl + " not found");
}
DavPropertySet davPropertySet = responses[0].getProperties(HttpStatus.SC_OK);
VCalendar localVCalendar = new VCalendar();
localVCalendar.setPropertyValue("PRODID", "-//davmail.sf.net/NONSGML DavMail Calendar V1.1//EN");
localVCalendar.setPropertyValue("VERSION", "2.0");
localVCalendar.setPropertyValue("METHOD", getPropertyIfExists(davPropertySet, "method"));
VObject vEvent = new VObject();
vEvent.type = "VEVENT";
vEvent.setPropertyValue("CREATED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "created")));
vEvent.setPropertyValue("LAST-MODIFIED", convertDateFromExchange(getPropertyIfExists(davPropertySet, "calendarlastmodified")));
vEvent.setPropertyValue("DTSTAMP", convertDateFromExchange(getPropertyIfExists(davPropertySet, "dtstamp")));
vEvent.setPropertyValue("UID", getPropertyIfExists(davPropertySet, "calendaruid"));
vEvent.setPropertyValue("SUMMARY", getPropertyIfExists(davPropertySet, "subject"));
// check mandatory dtstart value
String dtstart = getPropertyIfExists(davPropertySet, "dtstart");
if (dtstart != null) {
vEvent.setPropertyValue("DTSTART", convertDateFromExchange(dtstart));
} else {
LOGGER.warn("missing dtstart on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTSTART", "20000101T000000Z");
deleteBroken();
}
// same on DTEND
String dtend = getPropertyIfExists(davPropertySet, "dtend");
if (dtend != null) {
vEvent.setPropertyValue("DTEND", convertDateFromExchange(dtend));
} else {
LOGGER.warn("missing dtend on item, using fake value. Set davmail.deleteBroken=true to delete broken events");
vEvent.setPropertyValue("DTEND", "20000101T010000Z");
deleteBroken();
}
vEvent.setPropertyValue("TRANSP", getPropertyIfExists(davPropertySet, "transparent"));
vEvent.setPropertyValue("RRULE", getPropertyIfExists(davPropertySet, "rrule"));
String exdates = getPropertyIfExists(davPropertySet, "exdate");
if (exdates != null) {
String[] exdatearray = exdates.split(",");
for (String exdate : exdatearray) {
vEvent.addPropertyValue("EXDATE",
StringUtil.convertZuluDateTimeToAllDay(convertDateFromExchange(exdate)));
}
}
String sensitivity = getPropertyIfExists(davPropertySet, "sensitivity");
if ("2".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PRIVATE");
} else if ("3".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "CONFIDENTIAL");
} else if ("0".equals(sensitivity)) {
vEvent.setPropertyValue("CLASS", "PUBLIC");
}
String organizer = getPropertyIfExists(davPropertySet, "organizer");
String organizerEmail = null;
if (organizer != null) {
InternetAddress organizerAddress = new InternetAddress(organizer);
organizerEmail = organizerAddress.getAddress();
vEvent.setPropertyValue("ORGANIZER", "MAILTO:" + organizerEmail);
}
// Parse attendee list
String toHeader = getPropertyIfExists(davPropertySet, "to");
if (toHeader != null && !organizerEmail.equals(toHeader)) {
InternetAddress[] attendees = InternetAddress.parseHeader(toHeader, false);
for (InternetAddress attendee : attendees) {
if (!attendee.getAddress().equalsIgnoreCase(organizerEmail)) {
VProperty vProperty = new VProperty("ATTENDEE", attendee.getAddress());
if (attendee.getPersonal() != null) {
vProperty.addParam("CN", attendee.getPersonal());
}
vEvent.addProperty(vProperty);
}
}
}
vEvent.setPropertyValue("DESCRIPTION", getPropertyIfExists(davPropertySet, "description"));
vEvent.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT",
"1".equals(getPropertyIfExists(davPropertySet, "alldayevent")) ? "TRUE" : "FALSE");
vEvent.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS", getPropertyIfExists(davPropertySet, "busystatus"));
if ("1".equals(getPropertyIfExists(davPropertySet, "reminderset"))) {
VObject vAlarm = new VObject();
vAlarm.type = "VALARM";
vAlarm.setPropertyValue("ACTION", "DISPLAY");
vAlarm.setPropertyValue("DISPLAY", "Reminder");
String reminderdelta = getPropertyIfExists(davPropertySet, "reminderdelta");
VProperty vProperty = new VProperty("TRIGGER", "-PT" + reminderdelta + 'M');
vProperty.addParam("VALUE", "DURATION");
vAlarm.addProperty(vProperty);
vEvent.addVObject(vAlarm);
}
localVCalendar.addVObject(vEvent);
result = localVCalendar.toString().getBytes("UTF-8");
} catch (MessagingException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} catch (IOException e) {
LOGGER.warn("Unable to rebuild event content: " + e.getMessage(), e);
throw buildHttpException(e);
} finally {
propFindMethod.releaseConnection();
}
return result;
}
|
diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
index d5c575f288..995fb96a8e 100644
--- a/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/prefix/TestRecursivePrefixTreeStrategy.java
@@ -1,216 +1,216 @@
package org.apache.lucene.spatial.prefix;
/*
* 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 com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.io.GeohashUtils;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.spatial.SpatialMatchConcern;
import org.apache.lucene.spatial.StrategyTestCase;
import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TestRecursivePrefixTreeStrategy extends StrategyTestCase {
private int maxLength;
//Tests should call this first.
private void init(int maxLength) {
this.maxLength = maxLength;
this.ctx = SpatialContext.GEO;
GeohashPrefixTree grid = new GeohashPrefixTree(ctx, maxLength);
this.strategy = new RecursivePrefixTreeStrategy(grid, getClass().getSimpleName());
}
@Test
public void testFilterWithVariableScanLevel() throws IOException {
init(GeohashPrefixTree.getMaxLevelsPossible());
getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
//execute queries for each prefix grid scan level
for(int i = 0; i <= maxLength; i++) {
((RecursivePrefixTreeStrategy)strategy).setPrefixGridScanLevel(i);
executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
}
}
@Test
public void testOneMeterPrecision() {
init(GeohashPrefixTree.getMaxLevelsPossible());
GeohashPrefixTree grid = (GeohashPrefixTree) ((RecursivePrefixTreeStrategy) strategy).getGrid();
//DWS: I know this to be true. 11 is needed for one meter
double degrees = DistanceUtils.dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);
assertEquals(11, grid.getLevelForDistance(degrees));
}
@Test
public void testPrecision() throws IOException{
init(GeohashPrefixTree.getMaxLevelsPossible());
Point iPt = ctx.makePoint(2.8028712999999925, 48.3708044);//lon, lat
addDocument(newDoc("iPt", iPt));
commit();
Point qPt = ctx.makePoint(2.4632387000000335, 48.6003516);
final double KM2DEG = DistanceUtils.dist2Degrees(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
final double DEG2KM = 1 / KM2DEG;
final double DIST = 35.75;//35.7499...
assertEquals(DIST, ctx.getDistCalc().distance(iPt, qPt) * DEG2KM, 0.001);
//distErrPct will affect the query shape precision. The indexed precision
// was set to nearly zilch via init(GeohashPrefixTree.getMaxLevelsPossible());
final double distErrPct = 0.025; //the suggested default, by the way
final double distMult = 1+distErrPct;
assertTrue(35.74*distMult >= DIST);
checkHits(q(qPt, 35.74 * KM2DEG, distErrPct), 1, null);
assertTrue(30*distMult < DIST);
checkHits(q(qPt, 30 * KM2DEG, distErrPct), 0, null);
assertTrue(33*distMult < DIST);
checkHits(q(qPt, 33 * KM2DEG, distErrPct), 0, null);
assertTrue(34*distMult < DIST);
checkHits(q(qPt, 34 * KM2DEG, distErrPct), 0, null);
}
@Test
public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
- checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
+ checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
/** Query point-distance (in degrees) with zero error percent. */
private SpatialArgs q(Point pt, double distDEG) {
return q(pt, distDEG, 0.0);
}
private SpatialArgs q(Point pt, double distDEG, double distErrPct) {
Shape shape = ctx.makeCircle(pt, distDEG);
SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,shape);
args.setDistErrPct(distErrPct);
return args;
}
private void checkHits(SpatialArgs args, int assertNumFound, int[] assertIds) {
SearchResults got = executeQuery(strategy.makeQuery(args), 100);
assertEquals("" + args, assertNumFound, got.numFound);
if (assertIds != null) {
Set<Integer> gotIds = new HashSet<Integer>();
for (SearchResult result : got.results) {
gotIds.add(Integer.valueOf(result.document.get("id")));
}
for (int assertId : assertIds) {
assertTrue("has "+assertId,gotIds.contains(assertId));
}
}
}
private Document newDoc(String id, Shape shape) {
Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
for (Field f : strategy.createIndexableFields(shape)) {
doc.add(f);
}
if (storeShape)
doc.add(new StoredField(strategy.getFieldName(), ctx.toString(shape)));
return doc;
}
/** NGeohash round-trip for given precision. */
private Point alignGeohash(Point p) {
return GeohashUtils.decode(GeohashUtils.encodeLatLon(p.getY(), p.getX(), maxLength), ctx);
}
}
| true | true | public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3*1.01), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
| public void geohashRecursiveRandom() throws IOException {
init(12);
//1. Iterate test with the cluster at some worldly point of interest
Point[] clusterCenters = new Point[]{ctx.makePoint(-180,0), ctx.makePoint(0,90), ctx.makePoint(0,-90)};
for (Point clusterCenter : clusterCenters) {
//2. Iterate on size of cluster (a really small one and a large one)
String hashCenter = GeohashUtils.encodeLatLon(clusterCenter.getY(), clusterCenter.getX(), maxLength);
//calculate the number of degrees in the smallest grid box size (use for both lat & lon)
String smallBox = hashCenter.substring(0,hashCenter.length()-1);//chop off leaf precision
Rectangle clusterDims = GeohashUtils.decodeBoundary(smallBox,ctx);
double smallRadius = Math.max(clusterDims.getMaxX()-clusterDims.getMinX(),clusterDims.getMaxY()-clusterDims.getMinY());
assert smallRadius < 1;
double largeRadius = 20d;//good large size; don't use >=45 for this test code to work
double[] radiusDegs = {largeRadius,smallRadius};
for (double radiusDeg : radiusDegs) {
//3. Index random points in this cluster circle
deleteAll();
List<Point> points = new ArrayList<Point>();
for(int i = 0; i < 20; i++) {
//Note that this will not result in randomly distributed points in the
// circle, they will be concentrated towards the center a little. But
// it's good enough.
Point pt = ctx.getDistCalc().pointOnBearing(clusterCenter,
random().nextDouble() * radiusDeg, random().nextInt() * 360, ctx, null);
pt = alignGeohash(pt);
points.add(pt);
addDocument(newDoc("" + i, pt));
}
commit();
//3. Use some query centers. Each is twice the cluster's radius away.
for(int ri = 0; ri < 4; ri++) {
Point queryCenter = ctx.getDistCalc().pointOnBearing(clusterCenter,
radiusDeg*2, random().nextInt(360), ctx, null);
queryCenter = alignGeohash(queryCenter);
//4.1 Query a small box getting nothing
checkHits(q(queryCenter, radiusDeg - smallRadius/2), 0, null);
//4.2 Query a large box enclosing the cluster, getting everything
checkHits(q(queryCenter, radiusDeg*3 + smallRadius/2), points.size(), null);
//4.3 Query a medium box getting some (calculate the correct solution and verify)
double queryDist = radiusDeg * 2;
//Find matching points. Put into int[] of doc ids which is the same thing as the index into points list.
int[] ids = new int[points.size()];
int ids_sz = 0;
for (int i = 0; i < points.size(); i++) {
Point point = points.get(i);
if (ctx.getDistCalc().distance(queryCenter, point) <= queryDist)
ids[ids_sz++] = i;
}
ids = Arrays.copyOf(ids, ids_sz);
//assert ids_sz > 0 (can't because randomness keeps us from being able to)
checkHits(q(queryCenter, queryDist), ids.length, ids);
}
}//for radiusDeg
}//for clusterCenter
}//randomTest()
|
diff --git a/src/org/apache/xerces/jaxp/validation/XMLSchemaFactory.java b/src/org/apache/xerces/jaxp/validation/XMLSchemaFactory.java
index 51c427938..2c941d498 100644
--- a/src/org/apache/xerces/jaxp/validation/XMLSchemaFactory.java
+++ b/src/org/apache/xerces/jaxp/validation/XMLSchemaFactory.java
@@ -1,480 +1,482 @@
/*
* 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.xerces.jaxp.validation;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Locale;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.util.DOMEntityResolverWrapper;
import org.apache.xerces.util.DOMInputSource;
import org.apache.xerces.util.ErrorHandlerWrapper;
import org.apache.xerces.util.SAXInputSource;
import org.apache.xerces.util.SAXMessageFormatter;
import org.apache.xerces.util.SecurityManager;
import org.apache.xerces.util.XMLGrammarPoolImpl;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.w3c.dom.Node;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
/**
* {@link SchemaFactory} for XML Schema.
*
* @author Kohsuke Kawaguchi ([email protected])
* @version $Id$
*/
public final class XMLSchemaFactory extends SchemaFactory {
// feature identifiers
/** Feature identifier: schema full checking. */
private static final String SCHEMA_FULL_CHECKING =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING;
/** Feature identifier: use grammar pool only. */
private static final String USE_GRAMMAR_POOL_ONLY =
Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE;
// property identifiers
/** Property identifier: grammar pool. */
private static final String XMLGRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Property identifier: SecurityManager. */
private static final String SECURITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;
//
// Data
//
/** The XMLSchemaLoader */
private final XMLSchemaLoader fXMLSchemaLoader = new XMLSchemaLoader();
/** User-specified ErrorHandler; can be null. */
private ErrorHandler fErrorHandler;
/** The LSResrouceResolver */
private LSResourceResolver fLSResourceResolver;
/** The DOMEntityResolverWrapper */
private final DOMEntityResolverWrapper fDOMEntityResolverWrapper;
/** The ErrorHandlerWrapper */
private ErrorHandlerWrapper fErrorHandlerWrapper;
/** The SecurityManager. */
private SecurityManager fSecurityManager;
/** The container for the real grammar pool. */
private XMLGrammarPoolWrapper fXMLGrammarPoolWrapper;
/** Whether or not to allow new schemas to be added to the grammar pool */
private boolean fUseGrammarPoolOnly;
public XMLSchemaFactory() {
fErrorHandlerWrapper = new ErrorHandlerWrapper(DraconianErrorHandler.getInstance());
fDOMEntityResolverWrapper = new DOMEntityResolverWrapper();
fXMLGrammarPoolWrapper = new XMLGrammarPoolWrapper();
fXMLSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, true);
fXMLSchemaLoader.setProperty(XMLGRAMMAR_POOL, fXMLGrammarPoolWrapper);
fXMLSchemaLoader.setEntityResolver(fDOMEntityResolverWrapper);
fXMLSchemaLoader.setErrorHandler(fErrorHandlerWrapper);
fUseGrammarPoolOnly = true;
}
/**
* <p>Is specified schema supported by this <code>SchemaFactory</code>?</p>
*
* @param schemaLanguage Specifies the schema language which the returned <code>SchemaFactory</code> will understand.
* <code>schemaLanguage</code> must specify a <a href="#schemaLanguage">valid</a> schema language.
*
* @return <code>true</code> if <code>SchemaFactory</code> supports <code>schemaLanguage</code>, else <code>false</code>.
*
* @throws NullPointerException If <code>schemaLanguage</code> is <code>null</code>.
* @throws IllegalArgumentException If <code>schemaLanguage.length() == 0</code>
* or <code>schemaLanguage</code> does not specify a <a href="#schemaLanguage">valid</a> schema language.
*/
public boolean isSchemaLanguageSupported(String schemaLanguage) {
if (schemaLanguage == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaLanguageNull", null));
}
if (schemaLanguage.length() == 0) {
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaLanguageLengthZero", null));
}
// only W3C XML Schema 1.0 is supported
return schemaLanguage.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI);
}
public LSResourceResolver getResourceResolver() {
return fLSResourceResolver;
}
public void setResourceResolver(LSResourceResolver resourceResolver) {
fLSResourceResolver = resourceResolver;
fDOMEntityResolverWrapper.setEntityResolver(resourceResolver);
fXMLSchemaLoader.setEntityResolver(fDOMEntityResolverWrapper);
}
public ErrorHandler getErrorHandler() {
return fErrorHandler;
}
public void setErrorHandler(ErrorHandler errorHandler) {
fErrorHandler = errorHandler;
fErrorHandlerWrapper.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
fXMLSchemaLoader.setErrorHandler(fErrorHandlerWrapper);
}
public Schema newSchema( Source[] schemas ) throws SAXException {
// this will let the loader store parsed Grammars into the pool.
XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
fXMLGrammarPoolWrapper.setGrammarPool(pool);
XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
InputStream inputStream;
Reader reader;
for( int i=0; i<schemas.length; i++ ) {
Source source = schemas[i];
if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
String publicId = streamSource.getPublicId();
String systemId = streamSource.getSystemId();
inputStream = streamSource.getInputStream();
reader = streamSource.getReader();
xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
xmlInputSources[i].setByteStream(inputStream);
xmlInputSources[i].setCharacterStream(reader);
}
else if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
InputSource inputSource = saxSource.getInputSource();
if (inputSource == null) {
throw new SAXException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SAXSourceNullInputSource", null));
}
xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
}
else if (source instanceof DOMSource) {
DOMSource domSource = (DOMSource) source;
Node node = domSource.getNode();
String systemID = domSource.getSystemId();
xmlInputSources[i] = new DOMInputSource(node, systemID);
}
else if (source == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaSourceArrayMemberNull", null));
}
else {
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaFactorySourceUnrecognized",
new Object [] {source.getClass().getName()}));
}
}
try {
fXMLSchemaLoader.loadGrammar(xmlInputSources);
}
catch (XNIException e) {
// this should have been reported to users already.
throw Util.toSAXException(e);
}
catch (IOException e) {
// this hasn't been reported, so do so now.
SAXParseException se = new SAXParseException(e.getMessage(),null,e);
- fErrorHandler.error(se);
+ if (fErrorHandler != null) {
+ fErrorHandler.error(se);
+ }
throw se; // and we must throw it.
}
// Clear reference to grammar pool.
fXMLGrammarPoolWrapper.setGrammarPool(null);
// Select Schema implementation based on grammar count.
final int grammarCount = pool.getGrammarCount();
AbstractXMLSchema schema = null;
if (fUseGrammarPoolOnly) {
if (grammarCount > 1) {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool));
}
else if (grammarCount == 1) {
Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
schema = new SimpleXMLSchema(grammars[0]);
}
else {
schema = new EmptyXMLSchema();
}
}
else {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false);
}
propagateFeatures(schema);
return schema;
}
public Schema newSchema() throws SAXException {
/*
* It would make sense to return an EmptyXMLSchema object here, if
* fUseGrammarPoolOnly is set to true. However, because the default
* value of this feature is true, doing so would change the default
* behaviour of this method. Thus, we return a WeakReferenceXMLSchema
* regardless of the value of fUseGrammarPoolOnly. -PM
*/
// Use a Schema that uses the system id as the equality source.
AbstractXMLSchema schema = new WeakReferenceXMLSchema();
propagateFeatures(schema);
return schema;
}
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"FeatureNameNull", null));
}
if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
return (fSecurityManager != null);
}
else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
return fUseGrammarPoolOnly;
}
try {
return fXMLSchemaLoader.getFeature(name);
}
catch (XMLConfigurationException e) {
String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"feature-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"feature-not-supported", new Object [] {identifier}));
}
}
}
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"ProperyNameNull", null));
}
if (name.equals(SECURITY_MANAGER)) {
return fSecurityManager;
}
else if (name.equals(XMLGRAMMAR_POOL)) {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-supported", new Object [] {name}));
}
try {
return fXMLSchemaLoader.getProperty(name);
}
catch (XMLConfigurationException e) {
String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-supported", new Object [] {identifier}));
}
}
}
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"FeatureNameNull", null));
}
if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
fSecurityManager = value ? new SecurityManager() : null;
fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
return;
}
else if (name.equals(USE_GRAMMAR_POOL_ONLY)) {
fUseGrammarPoolOnly = value;
return;
}
try {
fXMLSchemaLoader.setFeature(name, value);
}
catch (XMLConfigurationException e) {
String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"feature-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"feature-not-supported", new Object [] {identifier}));
}
}
}
public void setProperty(String name, Object object)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"ProperyNameNull", null));
}
if (name.equals(SECURITY_MANAGER)) {
fSecurityManager = (SecurityManager) object;
fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
return;
}
else if (name.equals(XMLGRAMMAR_POOL)) {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-supported", new Object [] {name}));
}
try {
fXMLSchemaLoader.setProperty(name, object);
}
catch (XMLConfigurationException e) {
String identifier = e.getIdentifier();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-recognized", new Object [] {identifier}));
}
else {
throw new SAXNotSupportedException(
SAXMessageFormatter.formatMessage(Locale.getDefault(),
"property-not-supported", new Object [] {identifier}));
}
}
}
private void propagateFeatures(AbstractXMLSchema schema) {
schema.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, fSecurityManager != null);
String[] features = fXMLSchemaLoader.getRecognizedFeatures();
for (int i = 0; i < features.length; ++i) {
boolean state = fXMLSchemaLoader.getFeature(features[i]);
schema.setFeature(features[i], state);
}
}
/**
* Extension of XMLGrammarPoolImpl which exposes the number of
* grammars stored in the grammar pool.
*/
static class XMLGrammarPoolImplExtension extends XMLGrammarPoolImpl {
/** Constructs a grammar pool with a default number of buckets. */
public XMLGrammarPoolImplExtension() {
super();
}
/** Constructs a grammar pool with a specified number of buckets. */
public XMLGrammarPoolImplExtension(int initialCapacity) {
super(initialCapacity);
}
/** Returns the number of grammars contained in this pool. */
int getGrammarCount() {
return fGrammarCount;
}
} // XMLSchemaFactory.XMLGrammarPoolImplExtension
/**
* A grammar pool which wraps another.
*/
static class XMLGrammarPoolWrapper implements XMLGrammarPool {
private XMLGrammarPool fGrammarPool;
/*
* XMLGrammarPool methods
*/
public Grammar[] retrieveInitialGrammarSet(String grammarType) {
return fGrammarPool.retrieveInitialGrammarSet(grammarType);
}
public void cacheGrammars(String grammarType, Grammar[] grammars) {
fGrammarPool.cacheGrammars(grammarType, grammars);
}
public Grammar retrieveGrammar(XMLGrammarDescription desc) {
return fGrammarPool.retrieveGrammar(desc);
}
public void lockPool() {
fGrammarPool.lockPool();
}
public void unlockPool() {
fGrammarPool.unlockPool();
}
public void clear() {
fGrammarPool.clear();
}
/*
* Other methods
*/
void setGrammarPool(XMLGrammarPool grammarPool) {
fGrammarPool = grammarPool;
}
XMLGrammarPool getGrammarPool() {
return fGrammarPool;
}
} // XMLSchemaFactory.XMLGrammarPoolWrapper
} // XMLSchemaFactory
| true | true | public Schema newSchema( Source[] schemas ) throws SAXException {
// this will let the loader store parsed Grammars into the pool.
XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
fXMLGrammarPoolWrapper.setGrammarPool(pool);
XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
InputStream inputStream;
Reader reader;
for( int i=0; i<schemas.length; i++ ) {
Source source = schemas[i];
if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
String publicId = streamSource.getPublicId();
String systemId = streamSource.getSystemId();
inputStream = streamSource.getInputStream();
reader = streamSource.getReader();
xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
xmlInputSources[i].setByteStream(inputStream);
xmlInputSources[i].setCharacterStream(reader);
}
else if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
InputSource inputSource = saxSource.getInputSource();
if (inputSource == null) {
throw new SAXException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SAXSourceNullInputSource", null));
}
xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
}
else if (source instanceof DOMSource) {
DOMSource domSource = (DOMSource) source;
Node node = domSource.getNode();
String systemID = domSource.getSystemId();
xmlInputSources[i] = new DOMInputSource(node, systemID);
}
else if (source == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaSourceArrayMemberNull", null));
}
else {
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaFactorySourceUnrecognized",
new Object [] {source.getClass().getName()}));
}
}
try {
fXMLSchemaLoader.loadGrammar(xmlInputSources);
}
catch (XNIException e) {
// this should have been reported to users already.
throw Util.toSAXException(e);
}
catch (IOException e) {
// this hasn't been reported, so do so now.
SAXParseException se = new SAXParseException(e.getMessage(),null,e);
fErrorHandler.error(se);
throw se; // and we must throw it.
}
// Clear reference to grammar pool.
fXMLGrammarPoolWrapper.setGrammarPool(null);
// Select Schema implementation based on grammar count.
final int grammarCount = pool.getGrammarCount();
AbstractXMLSchema schema = null;
if (fUseGrammarPoolOnly) {
if (grammarCount > 1) {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool));
}
else if (grammarCount == 1) {
Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
schema = new SimpleXMLSchema(grammars[0]);
}
else {
schema = new EmptyXMLSchema();
}
}
else {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false);
}
propagateFeatures(schema);
return schema;
}
| public Schema newSchema( Source[] schemas ) throws SAXException {
// this will let the loader store parsed Grammars into the pool.
XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
fXMLGrammarPoolWrapper.setGrammarPool(pool);
XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
InputStream inputStream;
Reader reader;
for( int i=0; i<schemas.length; i++ ) {
Source source = schemas[i];
if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
String publicId = streamSource.getPublicId();
String systemId = streamSource.getSystemId();
inputStream = streamSource.getInputStream();
reader = streamSource.getReader();
xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
xmlInputSources[i].setByteStream(inputStream);
xmlInputSources[i].setCharacterStream(reader);
}
else if (source instanceof SAXSource) {
SAXSource saxSource = (SAXSource) source;
InputSource inputSource = saxSource.getInputSource();
if (inputSource == null) {
throw new SAXException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SAXSourceNullInputSource", null));
}
xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
}
else if (source instanceof DOMSource) {
DOMSource domSource = (DOMSource) source;
Node node = domSource.getNode();
String systemID = domSource.getSystemId();
xmlInputSources[i] = new DOMInputSource(node, systemID);
}
else if (source == null) {
throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaSourceArrayMemberNull", null));
}
else {
throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(Locale.getDefault(),
"SchemaFactorySourceUnrecognized",
new Object [] {source.getClass().getName()}));
}
}
try {
fXMLSchemaLoader.loadGrammar(xmlInputSources);
}
catch (XNIException e) {
// this should have been reported to users already.
throw Util.toSAXException(e);
}
catch (IOException e) {
// this hasn't been reported, so do so now.
SAXParseException se = new SAXParseException(e.getMessage(),null,e);
if (fErrorHandler != null) {
fErrorHandler.error(se);
}
throw se; // and we must throw it.
}
// Clear reference to grammar pool.
fXMLGrammarPoolWrapper.setGrammarPool(null);
// Select Schema implementation based on grammar count.
final int grammarCount = pool.getGrammarCount();
AbstractXMLSchema schema = null;
if (fUseGrammarPoolOnly) {
if (grammarCount > 1) {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool));
}
else if (grammarCount == 1) {
Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
schema = new SimpleXMLSchema(grammars[0]);
}
else {
schema = new EmptyXMLSchema();
}
}
else {
schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false);
}
propagateFeatures(schema);
return schema;
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java b/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java
index 4867042b4..47fafd960 100644
--- a/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java
+++ b/gdx/src/com/badlogic/gdx/graphics/BitmapFont.java
@@ -1,647 +1,648 @@
/*
* Copyright (c) 2008-2010, Matthias Mann
*
* 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 Matthias Mann nor
* the names of its 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 OWNER 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 com.badlogic.gdx.graphics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.utils.GdxRuntimeException;
/**
* Renders bitmap fonts. The font consists of 2 files: an image file or {@link TextureRegion} containing the glyphs and a file in
* the AngleCode BMFont text format that describes where each glyph is on the image. Currently only a single image of glyphs is
* supported.<br>
* <br>
* Text is drawn using a {@link SpriteBatch}. Text can be cached in a {@link BitmapFontCache} for faster rendering of static text,
* which saves needing to compute the location of each glyph each frame.<br>
* <br>
* * The texture for a BitmapFont loaded from a file is managed. {@link #dispose()} must be called to free the texture when no
* longer needed. A BitmapFont loaded using a {@link TextureRegion} is managed if the region's texture is managed. Disposing the
* BitmapFont disposes the region's texture, which may not be desirable if the texture is still being used elsewhere.<br>
* <br>
* The code is based on Matthias Mann's TWL BitmapFont class. Thanks for sharing, Matthias! :)
* @author Nathan Sweet <[email protected]>
* @author Matthias Mann
*/
public class BitmapFont {
static private final int LOG2_PAGE_SIZE = 9;
static private final int PAGE_SIZE = 1 << LOG2_PAGE_SIZE;
static private final int PAGES = 0x10000 / PAGE_SIZE;
TextureRegion region;
int lineHeight;
int capHeight;
int ascent;
int down;
private final Glyph[][] glyphs = new Glyph[PAGES][];
private int spaceWidth;
private int xHeight;
private final TextBounds textBounds = new TextBounds();
private float color = Color.WHITE.toFloatBits();
private Color tempColor = new Color(1, 1, 1, 1);
/**
* Creates a BitmapFont using the default 15pt Arial font included in the libgdx JAR file. This is convenient to easily display
* text without bothering with generating a bitmap font.
*/
public BitmapFont () {
this(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"),
Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), false);
}
/**
* Creates a BitmapFont with the glyphs relative to the specified region.
* @param region The texture region containing the glyphs. The glyphs must be relative to the lower left corner (ie, the region
* should not be flipped).
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner.
*/
public BitmapFont (FileHandle fontFile, TextureRegion region, boolean flip) {
init(fontFile, region, flip);
}
/**
* Creates a BitmapFont from a BMFont file. The image file name is read from the BMFont file and the image is loaded from the
* same directory.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner.
*/
public BitmapFont (FileHandle fontFile, boolean flip) {
init(fontFile, null, flip);
}
/**
* Creates a BitmapFont from a BMFont file, using the specified image for glyphs. Any image specified in the BMFont file is
* ignored.
* @param flip If true, the glyphs will be flipped for use with a perspective where 0,0 is the upper left corner.
*/
public BitmapFont (FileHandle fontFile, FileHandle imageFile, boolean flip) {
region = new TextureRegion(Gdx.graphics.newTexture(imageFile, TextureFilter.Linear, TextureFilter.Linear,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge));
init(fontFile, region, flip);
}
private void init (FileHandle fontFile, TextureRegion region, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.read()), 512);
try {
reader.readLine(); // info
String[] common = reader.readLine().split(" ", 4);
if (common.length < 4) throw new GdxRuntimeException("Invalid font file: " + fontFile);
if (!common[1].startsWith("lineHeight=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
lineHeight = Integer.parseInt(common[1].substring(11));
if (!common[2].startsWith("base=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
int baseLine = Integer.parseInt(common[2].substring(5));
if (region != null)
reader.readLine(); // page
else {
String[] page = reader.readLine().split(" ", 4);
if (!page[2].startsWith("file=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
- FileHandle imageFile = fontFile.parent().child(page[2].substring(5));
+ String imgFilename = page[2].substring(6, page[2].length()-1);
+ FileHandle imageFile = fontFile.parent().child(imgFilename);
region = new TextureRegion(Gdx.graphics.newTexture(imageFile, TextureFilter.Linear, TextureFilter.Linear,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge));
}
this.region = region;
float invTexWidth = 1.0f / region.getTexture().getWidth();
float invTexHeight = 1.0f / region.getTexture().getHeight();
float u = region.u;
float v = region.v;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.startsWith("kernings ")) break;
if (!line.startsWith("char ")) continue;
Glyph glyph = new Glyph();
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int ch = Integer.parseInt(tokens.nextToken());
if (ch <= Character.MAX_VALUE) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page == null) glyphs[ch / PAGE_SIZE] = page = new Glyph[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = glyph;
} else
continue;
tokens.nextToken();
float srcX = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
float srcY = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.width = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.height = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.xoffset = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
if (flip)
glyph.yoffset = Integer.parseInt(tokens.nextToken());
else
glyph.yoffset = -(glyph.height + Integer.parseInt(tokens.nextToken()));
tokens.nextToken();
glyph.xadvance = Integer.parseInt(tokens.nextToken());
glyph.u = u + srcX * invTexWidth;
glyph.u2 = u + (srcX + glyph.width) * invTexWidth;
if (flip) {
glyph.v = v + srcY * invTexHeight;
glyph.v2 = v + (srcY + glyph.height) * invTexHeight;
} else {
glyph.v2 = v + srcY * invTexHeight;
glyph.v = v + (srcY + glyph.height) * invTexHeight;
}
}
while (true) {
String line = reader.readLine();
if (line == null) break;
if (!line.startsWith("kerning ")) break;
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int first = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
int second = Integer.parseInt(tokens.nextToken());
if (first < 0 || first > Character.MAX_VALUE || second < 0 || second > Character.MAX_VALUE) continue;
Glyph glyph = getGlyph((char)first);
tokens.nextToken();
int amount = Integer.parseInt(tokens.nextToken());
glyph.setKerning(second, amount);
}
Glyph g = getGlyph(' ');
spaceWidth = g != null ? g.xadvance + g.width : 1;
g = getGlyph('x');
xHeight = g != null ? g.height : 1;
g = getGlyph('M');
capHeight = g != null ? g.height : 1;
ascent = baseLine - capHeight;
down = -lineHeight;
if (flip) {
ascent = -ascent;
down = -down;
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading font file: " + fontFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
Glyph getGlyph (char ch) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page != null) return page[ch & PAGE_SIZE - 1];
return null;
}
/**
* Draws a string at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds
* instance is used for all methods that return TextBounds.
*/
public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y) {
return draw(spriteBatch, str, x, y, 0, str.length());
}
/**
* Draws a substring at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @param start The first character of the string to draw.
* @param end The last character of the string to draw (exclusive).
* @return The bounds of the rendered string (the height is the distance from y to the baseline). Note the same TextBounds
* instance is used for all methods that return TextBounds.
*/
public TextBounds draw (SpriteBatch spriteBatch, CharSequence str, float x, float y, int start, int end) {
spriteBatch.setColor(color);
final Texture texture = region.getTexture();
y += ascent;
float startX = x;
Glyph lastGlyph = null;
while (start < end) {
lastGlyph = getGlyph(str.charAt(start++));
if (lastGlyph != null) {
spriteBatch.draw(texture, x + lastGlyph.xoffset, y + lastGlyph.yoffset, lastGlyph.width, lastGlyph.height,
lastGlyph.u, lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
x += lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = getGlyph(ch);
if (g == null) continue;
x += lastGlyph.getKerning(ch);
lastGlyph = g;
spriteBatch.draw(texture, x + lastGlyph.xoffset, y + lastGlyph.yoffset, lastGlyph.width, lastGlyph.height, lastGlyph.u,
lastGlyph.v, lastGlyph.u2, lastGlyph.v2);
x += g.xadvance;
}
textBounds.width = (int)(x - startX);
textBounds.height = capHeight;
return textBounds;
}
/**
* Draws a string, which may contain newlines (\n), at the specified position.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds.
*/
public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y) {
return drawMultiLine(spriteBatch, str, x, y, 0, HAlignment.LEFT);
}
/**
* Draws a string, which may contain newlines (\n), at the specified position and alignment. Each line is aligned horizontally
* within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds.
*/
public TextBounds drawMultiLine (SpriteBatch spriteBatch, CharSequence str, float x, float y, float alignmentWidth,
HAlignment alignment) {
int down = this.down;
int start = 0;
int numLines = 0;
int length = str.length();
int maxWidth = 0;
while (start < length) {
int lineEnd = indexOf(str, '\n', start);
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
int lineWidth = getBounds(str, start, lineEnd).width;
xOffset = alignmentWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
int lineWidth = draw(spriteBatch, str, x + xOffset, y, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = capHeight + (numLines - 1) * lineHeight;
return textBounds;
}
/**
* Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds.
*/
public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth) {
return drawWrapped(spriteBatch, str, x, y, wrapWidth, HAlignment.LEFT);
}
/**
* Draws a string, which may contain newlines (\n), with the specified position. Each line is automatically wrapped to keep it
* within a rectangle of the specified width, and aligned horizontally within that rectangle.
* @param x The x position for the left most character.
* @param y The y position for the top of most capital letters in the font (the {@link #getCapHeight() cap height}).
* @return The bounds of the rendered string (the height is the distance from y to the baseline of the last line). Note the
* same TextBounds instance is used for all methods that return TextBounds.
*/
public TextBounds drawWrapped (SpriteBatch spriteBatch, CharSequence str, float x, float y, float wrapWidth,
HAlignment alignment) {
int down = this.down;
int start = 0;
int numLines = 0;
int length = str.length();
int maxWidth = 0;
while (start < length) {
int lineEnd = start + computeVisibleGlpyhs(str, start, indexOf(str, '\n', start), wrapWidth);
int nextLineStart;
if (lineEnd < length) {
int originalLineEnd = lineEnd;
while (lineEnd > start) {
char ch = str.charAt(lineEnd);
if (ch == ' ' || ch == '\n') break;
lineEnd--;
}
if (lineEnd == start) {
lineEnd = originalLineEnd;
if (lineEnd == start) lineEnd++;
nextLineStart = lineEnd;
} else
nextLineStart = lineEnd + 1; // Eat space or newline.
} else {
if (lineEnd == start) lineEnd++;
nextLineStart = length;
}
float xOffset = 0;
if (alignment != HAlignment.LEFT) {
int lineWidth = getBounds(str, start, lineEnd).width;
xOffset = wrapWidth - lineWidth;
if (alignment == HAlignment.CENTER) xOffset /= 2;
}
int lineWidth = draw(spriteBatch, str, x + xOffset, y, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = nextLineStart;
y += down;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = capHeight + (numLines - 1) * lineHeight;
return textBounds;
}
/**
* Returns the size of the specified string. The height is the distance from the top of most capital letters in the font (the
* {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that return
* TextBounds.
*/
public TextBounds getBounds (CharSequence str) {
return getBounds(str, 0, str.length());
}
/**
* Returns the size of the specified substring. The height is the distance from the top of most capital letters in the font
* (the {@link #getCapHeight() cap height}) to the baseline. Note the same TextBounds instance is used for all methods that
* return TextBounds.
* @param start The first character of the string.
* @param end The last character of the string (exclusive).
*/
public TextBounds getBounds (CharSequence str, int start, int end) {
int width = 0;
Glyph lastGlyph = null;
while (start < end) {
lastGlyph = getGlyph(str.charAt(start++));
if (lastGlyph != null) {
width = lastGlyph.xadvance;
break;
}
}
while (start < end) {
char ch = str.charAt(start++);
Glyph g = getGlyph(ch);
if (g != null) {
width += lastGlyph.getKerning(ch);
lastGlyph = g;
width += g.xadvance;
}
}
textBounds.width = width;
textBounds.height = capHeight;
return textBounds;
}
/**
* Returns the size of the specified string, which may contain newlines. The height is the distance from the top of most
* capital letters in the font (the {@link #getCapHeight() cap height}) to the baseline of the last line of text. Note the same
* TextBounds instance is used for all methods that return TextBounds.
*/
public TextBounds getMultiLineBounds (CharSequence str) {
int start = 0;
int maxWidth = 0;
int numLines = 0;
int length = str.length();
while (start < length) {
int lineEnd = indexOf(str, '\n', start);
int lineWidth = getBounds(str, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = lineEnd + 1;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = capHeight + (numLines - 1) * lineHeight;
return textBounds;
}
/**
* Returns the size of the specified string, which may contain newlines and is wrapped to keep it within a rectangle of the
* specified width. The height is the distance from the top of most capital letters in the font (the {@link #getCapHeight() cap
* height}) to the baseline of the last line of text. Note the same TextBounds instance is used for all methods that return
* TextBounds.
*/
public TextBounds getWrappedBounds (CharSequence str, float wrapWidth) {
int start = 0;
int numLines = 0;
int length = str.length();
int maxWidth = 0;
while (start < length) {
int lineEnd = start + computeVisibleGlpyhs(str, start, indexOf(str, '\n', start), wrapWidth);
int nextLineStart;
if (lineEnd < length) {
int originalLineEnd = lineEnd;
while (lineEnd > start) {
char ch = str.charAt(lineEnd);
if (ch == ' ' || ch == '\n') break;
lineEnd--;
}
if (lineEnd == start) {
lineEnd = originalLineEnd;
if (lineEnd == start) lineEnd++;
nextLineStart = lineEnd;
} else
nextLineStart = lineEnd + 1; // Eat space or newline.
} else {
if (lineEnd == start) lineEnd++;
nextLineStart = length;
}
float xOffset = 0;
int lineWidth = getBounds(str, start, lineEnd).width;
maxWidth = Math.max(maxWidth, lineWidth);
start = nextLineStart;
numLines++;
}
textBounds.width = maxWidth;
textBounds.height = capHeight + (numLines - 1) * lineHeight;
return textBounds;
}
/**
* Returns the number of glyphs from the substring that can be rendered in the specified width.
* @param start The first character of the string.
* @param end The last character of the string (exclusive).
*/
public int computeVisibleGlpyhs (CharSequence str, int start, int end, float availableWidth) {
int index = start;
int width = 0;
Glyph lastGlyph = null;
for (; index < end; index++) {
char ch = str.charAt(index);
Glyph g = getGlyph(ch);
if (g != null) {
if (lastGlyph != null) width += lastGlyph.getKerning(ch);
lastGlyph = g;
if (width + g.width + g.xoffset > availableWidth) break;
width += g.xadvance;
}
}
return index - start;
}
public void setColor (Color tint) {
this.color = tint.toFloatBits();
}
public void setColor (float r, float g, float b, float a) {
int intBits = (int)(255 * a) << 24 | (int)(255 * b) << 16 | (int)(255 * g) << 8 | (int)(255 * r);
color = Float.intBitsToFloat(intBits);
}
/**
* Returns the color of this font. Changing the returned color will have no affect, {@link #setColor(Color)} or
* {@link #setColor(float, float, float, float)} must be used.
*/
public Color getColor () {
int intBits = Float.floatToRawIntBits(color);
Color color = this.tempColor;
color.r = (intBits & 0xff) / 255f;
color.g = ((intBits >>> 8) & 0xff) / 255f;
color.b = ((intBits >>> 16) & 0xff) / 255f;
color.a = ((intBits >>> 24) & 0xff) / 255f;
return color;
}
public TextureRegion getRegion () {
return region;
}
/**
* Returns the line height, which is the distance from one line of text to the next.
*/
public int getLineHeight () {
return lineHeight;
}
/**
* Returns the width of the space character.
*/
public int getSpaceWidth () {
return spaceWidth;
}
/**
* Returns the x-height, which is the distance from the top of most lowercase characters to the basline.
*/
public int getXHeight () {
return xHeight;
}
/**
* Returns the cap height, which is the distance from the top of most uppercase characters to the basline. Since the drawing
* position is the cap height of the first line, the cap height can be used to get the location of the baseline.
*/
public int getCapHeight () {
return capHeight;
}
/**
* Returns the ascent, which is the distance from the cap height to the top of the tallest glyph.
*/
public int getAscent () {
return ascent;
}
/**
* Disposes the texture used by this BitmapFont's region.
*/
public void dispose () {
region.getTexture().dispose();
}
/**
* Makes the specified glyphs fixed width. This can be useful to make the numbers in a font fixed width. Eg, when horizontally
* centering a score or loading percentage text, it will not jump around as different numbers are shown.
*/
public void setFixedWidthGlyphs (CharSequence glyphs) {
int maxAdvance = 0;
for (int index = 0, end = glyphs.length(); index < end; index++) {
Glyph g = getGlyph(glyphs.charAt(index));
if (g != null && g.xadvance > maxAdvance) maxAdvance = g.xadvance;
}
for (int index = 0, end = glyphs.length(); index < end; index++) {
Glyph g = getGlyph(glyphs.charAt(index));
if (g == null) continue;
g.xoffset += (maxAdvance - g.xadvance) / 2;
g.xadvance = maxAdvance;
g.kerning = null;
}
}
static class Glyph {
int width, height;
float u, v, u2, v2;
int xoffset, yoffset;
int xadvance;
byte[][] kerning;
int getKerning (char ch) {
if (kerning != null) {
byte[] page = kerning[ch >>> LOG2_PAGE_SIZE];
if (page != null) return page[ch & PAGE_SIZE - 1];
}
return 0;
}
void setKerning (int ch, int value) {
if (kerning == null) kerning = new byte[PAGES][];
byte[] page = kerning[ch >>> LOG2_PAGE_SIZE];
if (page == null) kerning[ch >>> LOG2_PAGE_SIZE] = page = new byte[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = (byte)value;
}
}
static int indexOf (CharSequence text, char ch, int start) {
final int n = text.length();
for (; start < n; start++)
if (text.charAt(start) == ch) return start;
return n;
}
static public class TextBounds {
public int width;
public int height;
}
static public enum HAlignment {
LEFT, CENTER, RIGHT
}
}
| true | true | private void init (FileHandle fontFile, TextureRegion region, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.read()), 512);
try {
reader.readLine(); // info
String[] common = reader.readLine().split(" ", 4);
if (common.length < 4) throw new GdxRuntimeException("Invalid font file: " + fontFile);
if (!common[1].startsWith("lineHeight=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
lineHeight = Integer.parseInt(common[1].substring(11));
if (!common[2].startsWith("base=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
int baseLine = Integer.parseInt(common[2].substring(5));
if (region != null)
reader.readLine(); // page
else {
String[] page = reader.readLine().split(" ", 4);
if (!page[2].startsWith("file=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
FileHandle imageFile = fontFile.parent().child(page[2].substring(5));
region = new TextureRegion(Gdx.graphics.newTexture(imageFile, TextureFilter.Linear, TextureFilter.Linear,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge));
}
this.region = region;
float invTexWidth = 1.0f / region.getTexture().getWidth();
float invTexHeight = 1.0f / region.getTexture().getHeight();
float u = region.u;
float v = region.v;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.startsWith("kernings ")) break;
if (!line.startsWith("char ")) continue;
Glyph glyph = new Glyph();
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int ch = Integer.parseInt(tokens.nextToken());
if (ch <= Character.MAX_VALUE) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page == null) glyphs[ch / PAGE_SIZE] = page = new Glyph[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = glyph;
} else
continue;
tokens.nextToken();
float srcX = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
float srcY = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.width = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.height = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.xoffset = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
if (flip)
glyph.yoffset = Integer.parseInt(tokens.nextToken());
else
glyph.yoffset = -(glyph.height + Integer.parseInt(tokens.nextToken()));
tokens.nextToken();
glyph.xadvance = Integer.parseInt(tokens.nextToken());
glyph.u = u + srcX * invTexWidth;
glyph.u2 = u + (srcX + glyph.width) * invTexWidth;
if (flip) {
glyph.v = v + srcY * invTexHeight;
glyph.v2 = v + (srcY + glyph.height) * invTexHeight;
} else {
glyph.v2 = v + srcY * invTexHeight;
glyph.v = v + (srcY + glyph.height) * invTexHeight;
}
}
while (true) {
String line = reader.readLine();
if (line == null) break;
if (!line.startsWith("kerning ")) break;
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int first = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
int second = Integer.parseInt(tokens.nextToken());
if (first < 0 || first > Character.MAX_VALUE || second < 0 || second > Character.MAX_VALUE) continue;
Glyph glyph = getGlyph((char)first);
tokens.nextToken();
int amount = Integer.parseInt(tokens.nextToken());
glyph.setKerning(second, amount);
}
Glyph g = getGlyph(' ');
spaceWidth = g != null ? g.xadvance + g.width : 1;
g = getGlyph('x');
xHeight = g != null ? g.height : 1;
g = getGlyph('M');
capHeight = g != null ? g.height : 1;
ascent = baseLine - capHeight;
down = -lineHeight;
if (flip) {
ascent = -ascent;
down = -down;
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading font file: " + fontFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
| private void init (FileHandle fontFile, TextureRegion region, boolean flip) {
BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.read()), 512);
try {
reader.readLine(); // info
String[] common = reader.readLine().split(" ", 4);
if (common.length < 4) throw new GdxRuntimeException("Invalid font file: " + fontFile);
if (!common[1].startsWith("lineHeight=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
lineHeight = Integer.parseInt(common[1].substring(11));
if (!common[2].startsWith("base=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
int baseLine = Integer.parseInt(common[2].substring(5));
if (region != null)
reader.readLine(); // page
else {
String[] page = reader.readLine().split(" ", 4);
if (!page[2].startsWith("file=")) throw new GdxRuntimeException("Invalid font file: " + fontFile);
String imgFilename = page[2].substring(6, page[2].length()-1);
FileHandle imageFile = fontFile.parent().child(imgFilename);
region = new TextureRegion(Gdx.graphics.newTexture(imageFile, TextureFilter.Linear, TextureFilter.Linear,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge));
}
this.region = region;
float invTexWidth = 1.0f / region.getTexture().getWidth();
float invTexHeight = 1.0f / region.getTexture().getHeight();
float u = region.u;
float v = region.v;
while (true) {
String line = reader.readLine();
if (line == null) break;
if (line.startsWith("kernings ")) break;
if (!line.startsWith("char ")) continue;
Glyph glyph = new Glyph();
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int ch = Integer.parseInt(tokens.nextToken());
if (ch <= Character.MAX_VALUE) {
Glyph[] page = glyphs[ch / PAGE_SIZE];
if (page == null) glyphs[ch / PAGE_SIZE] = page = new Glyph[PAGE_SIZE];
page[ch & PAGE_SIZE - 1] = glyph;
} else
continue;
tokens.nextToken();
float srcX = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
float srcY = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.width = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.height = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
glyph.xoffset = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
if (flip)
glyph.yoffset = Integer.parseInt(tokens.nextToken());
else
glyph.yoffset = -(glyph.height + Integer.parseInt(tokens.nextToken()));
tokens.nextToken();
glyph.xadvance = Integer.parseInt(tokens.nextToken());
glyph.u = u + srcX * invTexWidth;
glyph.u2 = u + (srcX + glyph.width) * invTexWidth;
if (flip) {
glyph.v = v + srcY * invTexHeight;
glyph.v2 = v + (srcY + glyph.height) * invTexHeight;
} else {
glyph.v2 = v + srcY * invTexHeight;
glyph.v = v + (srcY + glyph.height) * invTexHeight;
}
}
while (true) {
String line = reader.readLine();
if (line == null) break;
if (!line.startsWith("kerning ")) break;
StringTokenizer tokens = new StringTokenizer(line, " =");
tokens.nextToken();
tokens.nextToken();
int first = Integer.parseInt(tokens.nextToken());
tokens.nextToken();
int second = Integer.parseInt(tokens.nextToken());
if (first < 0 || first > Character.MAX_VALUE || second < 0 || second > Character.MAX_VALUE) continue;
Glyph glyph = getGlyph((char)first);
tokens.nextToken();
int amount = Integer.parseInt(tokens.nextToken());
glyph.setKerning(second, amount);
}
Glyph g = getGlyph(' ');
spaceWidth = g != null ? g.xadvance + g.width : 1;
g = getGlyph('x');
xHeight = g != null ? g.height : 1;
g = getGlyph('M');
capHeight = g != null ? g.height : 1;
ascent = baseLine - capHeight;
down = -lineHeight;
if (flip) {
ascent = -ascent;
down = -down;
}
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading font file: " + fontFile, ex);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
|
diff --git a/apps/animaldb/org/molgenis/animaldb/test/AnimaldbSeleniumTest.java b/apps/animaldb/org/molgenis/animaldb/test/AnimaldbSeleniumTest.java
index 241de99ce..9835be2f5 100644
--- a/apps/animaldb/org/molgenis/animaldb/test/AnimaldbSeleniumTest.java
+++ b/apps/animaldb/org/molgenis/animaldb/test/AnimaldbSeleniumTest.java
@@ -1,769 +1,769 @@
package org.molgenis.animaldb.test;
import java.io.File;
import java.util.Calendar;
import org.molgenis.MolgenisOptions.MapperImplementation;
import org.molgenis.framework.db.Database;
import org.molgenis.framework.db.jpa.JpaUtil;
import org.molgenis.util.DetectOS;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import plugins.emptydb.emptyDatabase;
import app.DatabaseFactory;
import app.FillMetadata;
import app.servlet.UsedMolgenisOptions;
import boot.Helper;
import boot.RunStandalone;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.HttpCommandProcessor;
import com.thoughtworks.selenium.Selenium;
public class AnimaldbSeleniumTest
{
private final Integer TIME_OUT = 1000;
private final String PAGE_LOAD_TIME_OUT = "10000";
private Selenium selenium;
boolean tomcat = false;
// String storagePath = new File(".").getAbsolutePath() + File.separator +
// "tmp_selenium_test_data";
@BeforeClass
public void start() throws Exception
{
int webserverPort = 8080;
if (!this.tomcat) webserverPort = Helper.getAvailablePort(11000, 10);
String seleniumUrl = "http://localhost:" + webserverPort + "/";
String seleniumHost = "localhost";
String seleniumBrowser = "firefox";
int seleniumPort = Helper.getAvailablePort(11010, 10);
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setSingleWindow(true);
rcc.setPort(seleniumPort);
try
{
SeleniumServer server = new SeleniumServer(false, rcc);
server.boot();
}
catch (Exception e)
{
throw new IllegalStateException("Cannot start selenium server: ", e);
}
HttpCommandProcessor proc = new HttpCommandProcessor(seleniumHost, seleniumPort, seleniumBrowser, seleniumUrl);
selenium = new DefaultSelenium(proc);
// selenium.setSpeed("1000");
selenium.start();
selenium.setTimeout(PAGE_LOAD_TIME_OUT);
if (new UsedMolgenisOptions().mapper_implementation == MapperImplementation.JPA)
{
Database db = DatabaseFactory.create();
JpaUtil.dropAndCreateTables(db, null);
FillMetadata.fillMetadata(db, false);
}
else
{
// To be sure, empty db and don't add MolgenisUsers etc.
new emptyDatabase(DatabaseFactory.create("apps/animaldb/org/molgenis/animaldb/animaldb.properties"), false);
}
if (!this.tomcat) new RunStandalone(webserverPort);
}
@Test
public void startup() throws InterruptedException
{
selenium.open("/animaldb/molgenis.do");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("startup");
}
@Test(dependsOnMethods =
{ "startup" })
public void loginAdmin() throws InterruptedException
{
// Login
Assert.assertEquals(selenium.getText("link=Register"), "Register");
selenium.type("id=username", "admin");
selenium.type("id=password", "admin");
selenium.click("id=Login");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Now we get to the Welcome screen
Assert.assertEquals(selenium.getTitle(), "AnimalDB");
Assert.assertTrue(selenium.isTextPresent("Welcome to AnimalDB!"));
// Go to Import database plugin
selenium.click("id=Admin_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("systemmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("LoadLegacy_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Import database"));
// Since Ate hates waiting, first see if we are on his laptop ;)
selenium.type("id=zip", new File(
"apps/animaldb/org/molgenis/animaldb/configurations/PrefillAnimalDB_default.zip").getAbsolutePath());
selenium.click("id=source1");
selenium.click("id=load");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Then try and see if we're on Roan's laptop
Assert.assertTrue(selenium.isTextPresent("Pre-filling AnimalDB successful"));
sleepHelper("loginAdmin");
}
@Test(dependsOnMethods =
{ "loginAdmin" })
public void fileStorageSettings() throws Exception
{
selenium.click("id=Admin_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=systemmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=FileStorage_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("File storage property status:"));
selenium.type("id=inputBox", "/tmp");
selenium.click("id=filestorage_setpath");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Properties are set"));
selenium.click("//input[@value='Validate']");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Validation status: VALIDATED"));
}
@Test(dependsOnMethods =
{ "fileStorageSettings" })
public void makeUser() throws InterruptedException
{
// Go to AnimalDB user mgmt. plugin (first item in Admin -> Security
// menu)
selenium.click("securitymenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Make user 'test'
selenium.click("link=Make new user");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=firstname", "test");
selenium.type("id=lastname", "test");
selenium.type("id=email", "[email protected]");
selenium.type("id=username", "test");
selenium.type("id=password1", "test");
selenium.type("id=password2", "test");
selenium.type("id=newinv", "testInv");
selenium.click("id=adduser");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium
.isTextPresent("User test successfully added and assigned ownership of investigation testInv"));
sleepHelper("makeUser");
}
@Test(dependsOnMethods =
{ "makeUser" })
public void logoutAdmin() throws InterruptedException
{
selenium.click("id=UserLogin_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=Logout");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("logoutAdmin");
}
@Test(dependsOnMethods =
{ "logoutAdmin" })
public void loginUser() throws InterruptedException
{
// Login
Assert.assertEquals(selenium.getText("link=Register"), "Register");
selenium.type("id=username", "test");
selenium.type("id=password", "test");
selenium.click("id=Login");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Now we get to the Welcome screen
Assert.assertEquals(selenium.getTitle(), "AnimalDB");
Assert.assertTrue(selenium.isTextPresent("Welcome to AnimalDB!"));
sleepHelper("loginUser");
}
@Test(dependsOnMethods =
{ "loginUser" })
public void addAnimals() throws Exception
{
// Go to Add Animal plugin
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=AddAnimal_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Bring in animals"));
// Add 10 female GMO House mice
selenium.select("id=species", "label=House mouse");
selenium.select("id=source", "label=Harlan");
selenium.select("id=animaltype", "label=B. Transgeen dier");
selenium.click("id=Cont1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.select("id=background", "label=C57BL/6j");
selenium.select("id=gene", "label=Cry1 KO");
// selenium.select("id=gene", "label=Cry2 KO"); NOTE: Selenium does not
// support multiple select, only last click is remembered!
selenium.click("id=Cont2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.select("id=genestate_Cry1 KO", "label=+/-");
// selenium.select("id=genestate_Cry2 KO", "label=+/-"); NOTE: Selenium
// does not support multiple select, only last click is remembered!
selenium.click("id=Cont3");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=numberoffemales", "10");
selenium.click("id=Save");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("10 animal(s) successfully added"));
// Add 10 male non-GMO House mice
selenium.select("id=species", "label=House mouse");
selenium.select("id=source", "label=Harlan");
selenium.select("id=animaltype", "label=A. Gewoon dier");
selenium.click("id=Cont1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.select("id=background", "label=C57BL/6j");
selenium.click("id=Cont2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=numberofmales", "10");
selenium.click("id=Save");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("10 animal(s) successfully added"));
sleepHelper("addAnimals");
}
@Test(dependsOnMethods =
{ "addAnimals" })
public void breedingWorkflow() throws Exception
{
// Go to Breeding line plugin
selenium.click("id=Settings_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=ManageLines_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Breeding lines"));
// Add a breeding line
selenium.type("id=linename", "MyLine");
selenium.select("id=species", "label=House mouse");
selenium.click("id=add");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Line successfully added"));
// Go to Breeding plugin
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// selenium.click("id=Breeding_tab_button");
selenium.click("id=Breeding_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Parentgroups"));
// Add a parentgroup
selenium.click("id=createParentgroup");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=numberPG", "3");
selenium.click("id=selectt");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
- selenium.click("id=showHideSettingsButton");
+ selenium.click("id=showHideFilterButton");
Thread.sleep(1000);
selenium.click("id=mothermatrix_removeFilter_2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first mother
selenium.click("id=motherB0");
// Thread.sleep(1000);
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Thread.sleep(1000);
selenium.click("id=mothermatrix_selected_1"); // select second mother
selenium.click("id=motherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third mother
selenium.click("id=motherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// click on next page for mothers in the matrix
selenium.click("id=mothermatrix_moveDownEnd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first father
selenium.click("id=fatherB0");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_1"); // select second father
selenium.click("id=fatherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third father
selenium.click("id=fatherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=from2to3");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("successfully added"));
// selenium.click("id=createParentgroup");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 1: mothers
// selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for
// first female in list
// selenium.click("id=from2to3");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 2: fathers
// selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for
// first male in list
// selenium.click("id=from3to4");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 3: start date and remarks
// selenium.click("id=addpg");
// selenium.waitForPageToLoad(pageLoadTimeout);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Add a litter
selenium.click("id=pgmatrix_selected_0");
selenium.click("id=createlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=littersize", "5");
selenium.click("id=birthdate");
selenium.type("id=birthdate", "2012-01-01");
selenium.click("id=addlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Wean litter
selenium.click("id=littermatrix_selected_0");
selenium.click("id=weanlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=weandate");
selenium.type("id=weandate", "2012-01-02");
selenium.type("id=weansizefemale", "2");
selenium.type("id=weansizemale", "3");
selenium.click("id=wean");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned"));
Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001"));
// Check cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Genotype litter
// TODO: expand
selenium.click("id=littermatrix_selected_0");
selenium.click("id=genotypelitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=genodate");
selenium.type("id=genodate", "2012-01-03");
Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001"));
Assert.assertTrue(selenium.isTextPresent("Line: MyLine"));
selenium.click("id=save");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped"));
// Check definitive cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("breedingWorkflow");
}
@Test(dependsOnMethods =
{ "breedingWorkflow" })
public void decWorkflow() throws Exception
{
Calendar calendar = Calendar.getInstance();
// String[] months = new String[] {"January", "February", "March",
// "April", "May", "June",
// "July", "August", "September", "October", "November", "December"};
// Go to DEC project plugin
selenium.click("id=decmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=AddProject_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("DEC applications"));
// Make a DEC project
boolean keepTrying = true;
int test = 0; // Check if we are on ate's laptop";
// for now just assume we are running on hudson.
// String pdfFileName =
// "/data/hudson/jobs/molgenis_animaldb/workspace/molgenis_apps/apps/animaldb/org/molgenis/animaldb/configurations/PrefillAnimalDB_default.zip";
String pdfFileName = new File("apps/animaldb/org/molgenis/animaldb/configurations/PrefillAnimalDB_default.zip")
.getAbsolutePath();
// String pdfFileName =
// "/home/paraiko/Projects/AnimalDB/prefill data/PrefillAnimalDB_default.zip";
selenium.click("id=add_decproject");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=dectitle", "MyDEC");
selenium.type("id=decnumber", "12345");
// pretend like these are PDFs...
selenium.type("id=decapppdf", pdfFileName);
selenium.type("id=decapprovalpdf", pdfFileName);
int thisYear = calendar.get(Calendar.YEAR);
selenium.type("id=startdate", thisYear + "-01-01");
selenium.type("id=enddate", thisYear + "-12-31");
selenium.type("id=decbudget", "20");
selenium.click("id=addproject");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("DEC project successfully added"));
Assert.assertTrue(selenium.isTextPresent("MyDEC"));
// Go to DEC subproject plugin
selenium.click("id=AddSubproject_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("DEC subprojects"));
// Make a DEC subproject
selenium.click("id=add_subproject");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=experimenttitle", "MyProject");
selenium.type("id=expnumber", "A");
selenium.type("id=decapppdf", "/home/test/subapp.pdf");
// int thisMonth = calendar.get(Calendar.MONTH);
// int thisYear = calendar.get(Calendar.YEAR);
selenium.type("id=startdate", thisYear + "-01-01");
selenium.type("id=enddate", thisYear + "-02-01");
selenium.type("id=decsubprojectbudget", "10");
selenium.click("id=addsubproject");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("DEC subproject successfully added"));
// Add animals to DEC
selenium.click("id=manage_animals_in_subproject");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=startadd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// toggle selectboxes for first five animals in list
selenium.click("id=addanimalsmatrix_selected_0");
selenium.click("id=addanimalsmatrix_selected_1");
selenium.click("id=addanimalsmatrix_selected_2");
selenium.click("id=addanimalsmatrix_selected_3");
selenium.click("id=addanimalsmatrix_selected_4");
selenium.type("id=subprojectadditiondate", thisYear + "-01-01");
selenium.click("id=doadd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Animal(s) successfully added"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Remove animals from DEC
// toggle selectboxes for first two animals in list
selenium.click("id=remanimalsmatrix_selected_0");
selenium.click("id=remanimalsmatrix_selected_1");
selenium.click("id=dorem"); // click Remove button
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=dorem"); // click Apply button
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Animal(s) successfully removed"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Check portal
selenium.click("DecStatus_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Assert.assertTrue(selenium.isTextPresent("DEC status portal"));
Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[1]/td[1]"), "12345");
Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[4]"), "A");
Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[7]"), "3");
Assert.assertEquals(selenium.getText("//table[@id='StatusTable']/tbody/tr[2]/td[8]"), "2");
sleepHelper("decWorkflow");
}
// @Test(dependsOnMethods={"decWorkflow"})
@Test(dependsOnMethods =
{ "breedingWorkflow" })
public void locations() throws Exception
{
// Go to locations plugin to create two locations
selenium.click("id=Settings_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=Locations_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Locations"));
selenium.click("link=Make new location");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=locname", "Room 101");
selenium.click("id=addloc");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Location successfully added"));
selenium.click("link=Make new location");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=locname", "IVC");
selenium.click("id=addloc");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Location successfully added"));
// Go to animals in locations plugin
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=LocationManagementPlugin_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Animals in locations"));
// Add five animals to Room 101
selenium.click("id=manage_loc_Room 101");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=add");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=animalsnotinlocmatrix_selected_5");
selenium.click("id=animalsnotinlocmatrix_selected_6");
selenium.click("id=animalsnotinlocmatrix_selected_7");
selenium.click("id=animalsnotinlocmatrix_selected_8");
selenium.click("id=animalsnotinlocmatrix_selected_9");
selenium.click("id=applyadd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium
.isTextPresent("Animals successfully added to Room 101. Now showing animals in that location."));
// Move two to IVC
selenium.click("id=animalsinlocmatrix_selected_0");
selenium.click("id=animalsinlocmatrix_selected_1");
selenium.click("id=move");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Animals successfully moved to IVC. Now switching to that location."));
Assert.assertTrue(selenium.isTextPresent("Animals in IVC:"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("locations");
}
@Test(dependsOnMethods =
{ "locations" })
public void yearlyReports() throws Exception
{
// Go to Report plugin
selenium.click("id=decmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=YearlyReportModule_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Report 4A (normal animals -> 10 males)
selenium.select("id=form", "value=4A");
selenium.click("id=generate");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertEquals(selenium.getTable("css=#reporttablediv > table.2.0"), "Muizen");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[2]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[3]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[4]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[5]/strong"), "10");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[6]/strong"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[7]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[8]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[9]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[10]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[11]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[12]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[13]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[14]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[15]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[16]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[17]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[18]"), "10");
// Report 4B (GMO animals -> 10 females + 5 weaned - 2 removed)
selenium.select("id=form", "value=4B");
selenium.click("id=generate");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertEquals(selenium.getTable("css=#reporttablediv > table.2.0"), "Muizen");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[2]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[3]"), "5");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[4]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[5]/strong"), "10");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[6]/strong"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[7]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[8]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[9]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[10]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[11]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[12]"), "2");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[13]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[14]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[15]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[16]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[17]"), "0");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[18]"), "13");
// Report 5
selenium.select("id=form", "value=5");
selenium.click("id=generate");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[1]"),
"12345A - DEC 12345");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[6]"), "2");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[15]"),
"A. Dood in het kader van de proef");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[16]"), "12345A");
Assert.assertEquals(selenium.getText("//div[@id='reporttablediv']/table/tbody/tr[3]/td[17]"), "Mus musculus");
sleepHelper("yearlyReports");
}
@Test(dependsOnMethods =
{ "yearlyReports" })
public void removeAnimals() throws Exception
{
// Remove 2 animals to test if removal by death via the remove animals
// plugin works.
Calendar calendar = Calendar.getInstance();
int thisYear = calendar.get(Calendar.YEAR);
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=RemAnimal_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=targetmatrix_selected_6");
selenium.click("id=targetmatrix_selected_7");
selenium.click("id=Select");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=deathdate", thisYear + "-02-02");
selenium.click("id=remarks");
selenium.type("id=remarks", "test");
selenium.click("id=Apply");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Animal(s) mm_000009 mm_000010 successfully removed"));
sleepHelper("removeAnimals");
}
// TODO add test for edit litter functionality
// @Test(dependsOnMethods =
// { "breedingWorkflow" })
// public void editLitters() throws Exception
// {
// }
/*
* @Test(dependsOnMethods={"removeAnimals"}) public void applyProtocol()
* throws Exception { // First log in as admin to be able to do this
* selenium.click("id=UserLogin_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.click("id=Logout");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.type("id=username", "admin"); selenium.type("id=password",
* "admin"); selenium.click("id=Login");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT); // Go to Protocol plugin
* selenium.click("id=Admin_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.click("id=systemmenu_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.click("id=ApplyProtocol_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT); // Apply 'SetWeight'
* protocol on animal 'mm_000001' selenium.select("id=Protocols",
* "label=SetWeight"); selenium.click("id=targetmatrix_selected_0"); //
* toggle selectbox for first animal in matrix selenium.click("id=TimeBox");
* selenium.click("id=Select");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* Assert.assertEquals(selenium
* .getText("//div[@id='divValueTable']/table/thead/tr/th[2]"), "Weight");
* Assert.assertEquals(selenium.getText(
* "//div[@id='divValueTable']/table/thead/tr/th[3]"), "Weight start");
* Assert.assertEquals(selenium.getText(
* "//div[@id='divValueTable']/table/thead/tr/th[4]"), "Weight end");
* selenium.type("id=0_1_0", "239"); selenium.click("id=ApplyStartTime_1");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.click("id=Apply");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* Assert.assertTrue(selenium
* .isTextPresent("Protocol applied successfully")); // Check in Timeline
* value viewer selenium.click("id=animalmenu_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
* selenium.click("id=TimelineViewer_tab_button");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
*
*
* //add weight and select the first value from matrix
* selenium.click("id=targetmatrix_selected_0"); // toggle radio button for
* first animal in list selenium.click("id=showHideSettingsButton");
* selenium.click("css=input.default");
*
* final String selector =
* "css=div#targetmatrix_measurementChooser_chzn.chzn-container ul.chzn-choices li.search-field input"
* ; selenium.type(selector, "Weigh"); selenium.keyUp(selector, "t");
* //keyDown(
* "css=div#targetmatrix_measurementChooser_chzn.chzn-container ul.chzn-choices li.search-field input"
* , "t"); sleepHelper("applyProtocol");
* selenium.click("id=targetmatrix_measurementChooser_chzn_o_0");
* selenium.click("css=#divtargetmatrix > div");
* selenium.click("id=targetmatrix_updateColHeaderFilter");
* selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
*
*
* Assert.assertTrue(selenium.isTextPresent("Weight"));
* Assert.assertTrue(selenium.isTextPresent("239"));
* sleepHelper("applyProtocol"); }
*/
@Test(dependsOnMethods =
{ "removeAnimals" })
public void logoutUser() throws InterruptedException
{
selenium.click("id=UserLogin_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=Logout");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("logout");
}
@AfterClass(alwaysRun = true)
public void stop() throws Exception
{
selenium.stop();
// added to fix TestDatabase which runs after this one...
// see comment in TestDatabase!
UsedMolgenisOptions usedMolgenisOptions = new UsedMolgenisOptions();
if (usedMolgenisOptions.mapper_implementation == MapperImplementation.JPA)
{
Database db = DatabaseFactory.create();
JpaUtil.dropAndCreateTables(db, null);
FillMetadata.fillMetadata(db, false);
}
else
{
// new
// Molgenis("apps/animaldb/org/molgenis/animaldb/animaldb.properties").updateDb(true);
new emptyDatabase(DatabaseFactory.create("apps/animaldb/org/molgenis/animaldb/animaldb.properties"), false);
}
// Helper.deleteStorage();
// Helper.deleteDatabase();
}
// helper function to get a good storage path
private String storagePath()
{
String storagePath = new File(".").getAbsolutePath() + File.separator + "tmp_selenium_test_data";
if (DetectOS.getOS().startsWith("windows"))
{
return storagePath.replace("\\", "/");
}
else
{
return storagePath;
}
}
private void sleepHelper(String who) throws InterruptedException
{
System.out.println(who + " done, now sleeping for " + TIME_OUT + " msec");
Thread.sleep(TIME_OUT);
}
}
| true | true | public void breedingWorkflow() throws Exception
{
// Go to Breeding line plugin
selenium.click("id=Settings_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=ManageLines_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Breeding lines"));
// Add a breeding line
selenium.type("id=linename", "MyLine");
selenium.select("id=species", "label=House mouse");
selenium.click("id=add");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Line successfully added"));
// Go to Breeding plugin
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// selenium.click("id=Breeding_tab_button");
selenium.click("id=Breeding_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Parentgroups"));
// Add a parentgroup
selenium.click("id=createParentgroup");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=numberPG", "3");
selenium.click("id=selectt");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=showHideSettingsButton");
Thread.sleep(1000);
selenium.click("id=mothermatrix_removeFilter_2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first mother
selenium.click("id=motherB0");
// Thread.sleep(1000);
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Thread.sleep(1000);
selenium.click("id=mothermatrix_selected_1"); // select second mother
selenium.click("id=motherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third mother
selenium.click("id=motherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// click on next page for mothers in the matrix
selenium.click("id=mothermatrix_moveDownEnd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first father
selenium.click("id=fatherB0");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_1"); // select second father
selenium.click("id=fatherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third father
selenium.click("id=fatherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=from2to3");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("successfully added"));
// selenium.click("id=createParentgroup");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 1: mothers
// selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for
// first female in list
// selenium.click("id=from2to3");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 2: fathers
// selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for
// first male in list
// selenium.click("id=from3to4");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 3: start date and remarks
// selenium.click("id=addpg");
// selenium.waitForPageToLoad(pageLoadTimeout);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Add a litter
selenium.click("id=pgmatrix_selected_0");
selenium.click("id=createlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=littersize", "5");
selenium.click("id=birthdate");
selenium.type("id=birthdate", "2012-01-01");
selenium.click("id=addlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Wean litter
selenium.click("id=littermatrix_selected_0");
selenium.click("id=weanlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=weandate");
selenium.type("id=weandate", "2012-01-02");
selenium.type("id=weansizefemale", "2");
selenium.type("id=weansizemale", "3");
selenium.click("id=wean");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned"));
Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001"));
// Check cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Genotype litter
// TODO: expand
selenium.click("id=littermatrix_selected_0");
selenium.click("id=genotypelitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=genodate");
selenium.type("id=genodate", "2012-01-03");
Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001"));
Assert.assertTrue(selenium.isTextPresent("Line: MyLine"));
selenium.click("id=save");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped"));
// Check definitive cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("breedingWorkflow");
}
| public void breedingWorkflow() throws Exception
{
// Go to Breeding line plugin
selenium.click("id=Settings_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=ManageLines_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Breeding lines"));
// Add a breeding line
selenium.type("id=linename", "MyLine");
selenium.select("id=species", "label=House mouse");
selenium.click("id=add");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Line successfully added"));
// Go to Breeding plugin
selenium.click("id=animalmenu_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// selenium.click("id=Breeding_tab_button");
selenium.click("id=Breeding_tab_button");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Parentgroups"));
// Add a parentgroup
selenium.click("id=createParentgroup");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=numberPG", "3");
selenium.click("id=selectt");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=showHideFilterButton");
Thread.sleep(1000);
selenium.click("id=mothermatrix_removeFilter_2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first mother
selenium.click("id=motherB0");
// Thread.sleep(1000);
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Thread.sleep(1000);
selenium.click("id=mothermatrix_selected_1"); // select second mother
selenium.click("id=motherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third mother
selenium.click("id=motherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// click on next page for mothers in the matrix
selenium.click("id=mothermatrix_moveDownEnd");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_0"); // select first father
selenium.click("id=fatherB0");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_1"); // select second father
selenium.click("id=fatherB1");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=mothermatrix_selected_2"); // select third father
selenium.click("id=fatherB2");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=from2to3");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("successfully added"));
// selenium.click("id=createParentgroup");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 1: mothers
// selenium.click("id=mothermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=mothermatrix_selected_0"); // toggle selectbox for
// first female in list
// selenium.click("id=from2to3");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 2: fathers
// selenium.click("id=fathermatrix_removeFilter_3"); // remove filter on
// line (line is not set for new animals)
// selenium.waitForPageToLoad(pageLoadTimeout);
// selenium.click("id=fathermatrix_selected_0"); // toggle selectbox for
// first male in list
// selenium.click("id=from3to4");
// selenium.waitForPageToLoad(pageLoadTimeout);
// // Screen 3: start date and remarks
// selenium.click("id=addpg");
// selenium.waitForPageToLoad(pageLoadTimeout);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Add a litter
selenium.click("id=pgmatrix_selected_0");
selenium.click("id=createlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.type("id=littersize", "5");
selenium.click("id=birthdate");
selenium.type("id=birthdate", "2012-01-01");
selenium.click("id=addlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Assert.assertTrue(selenium.isTextPresent("successfully added"));
// Wean litter
selenium.click("id=littermatrix_selected_0");
selenium.click("id=weanlitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=weandate");
selenium.type("id=weandate", "2012-01-02");
selenium.type("id=weansizefemale", "2");
selenium.type("id=weansizemale", "3");
selenium.click("id=wean");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully weaned"));
Assert.assertTrue(selenium.isTextPresent("LT_MyLine_000001"));
// Check cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
// Genotype litter
// TODO: expand
selenium.click("id=littermatrix_selected_0");
selenium.click("id=genotypelitter");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
selenium.click("id=genodate");
selenium.type("id=genodate", "2012-01-03");
Assert.assertTrue(selenium.isTextPresent("Parentgroup: PG_MyLine_000001"));
Assert.assertTrue(selenium.isTextPresent("Line: MyLine"));
selenium.click("id=save");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("All 5 animals successfully genotyped"));
// Check definitive cage labels link
selenium.click("id=littermatrix_selected_0");
selenium.click("id=label");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
Assert.assertTrue(selenium.isTextPresent("Download cage labels as pdf"));
selenium.click("link=Back to overview");
selenium.waitForPageToLoad(PAGE_LOAD_TIME_OUT);
sleepHelper("breedingWorkflow");
}
|
diff --git a/src/powercrystals/minefactoryreloaded/render/RendererFactoryGlassPane.java b/src/powercrystals/minefactoryreloaded/render/RendererFactoryGlassPane.java
index 18fd325e..12b6ef11 100644
--- a/src/powercrystals/minefactoryreloaded/render/RendererFactoryGlassPane.java
+++ b/src/powercrystals/minefactoryreloaded/render/RendererFactoryGlassPane.java
@@ -1,352 +1,353 @@
package powercrystals.minefactoryreloaded.render;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import powercrystals.minefactoryreloaded.block.BlockFactoryGlassPane;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
public class RendererFactoryGlassPane implements ISimpleBlockRenderingHandler
{
@Override
public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)
{
}
@Override
public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
BlockFactoryGlassPane pane = (BlockFactoryGlassPane)block;
int l = blockAccess.getHeight();
Tessellator tessellator = Tessellator.instance;
tessellator.setBrightness(pane.getMixedBrightnessForBlock(blockAccess, x, y, z));
float f = 1.0F;
int i1 = pane.colorMultiplier(blockAccess, x, y, z);
float f1 = (float)(i1 >> 16 & 255) / 255.0F;
float f2 = (float)(i1 >> 8 & 255) / 255.0F;
float f3 = (float)(i1 & 255) / 255.0F;
if (EntityRenderer.anaglyphEnable)
{
float f4 = (f1 * 30.0F + f2 * 59.0F + f3 * 11.0F) / 100.0F;
float f5 = (f1 * 30.0F + f2 * 70.0F) / 100.0F;
float f6 = (f1 * 30.0F + f3 * 70.0F) / 100.0F;
f1 = f4;
f2 = f5;
f3 = f6;
}
tessellator.setColorOpaque_F(f * f1, f * f2, f * f3);
Icon iconFront;
Icon iconSide;
int metadata;
if(renderer.hasOverrideBlockTexture())
{
iconFront = renderer.overrideBlockTexture;
iconSide = renderer.overrideBlockTexture;
}
else
{
metadata = blockAccess.getBlockMetadata(x, y, z);
iconFront = renderer.getBlockIconFromSideAndMetadata(pane, 0, metadata);
iconSide = pane.getBlockSideTextureFromMetadata(metadata);
}
double d0 = (double)iconFront.getMinU();
double d1 = (double)iconFront.getInterpolatedU(8.0D);
double d2 = (double)iconFront.getMaxU();
double d3 = (double)iconFront.getMinV();
double d4 = (double)iconFront.getMaxV();
double d5 = (double)iconSide.getInterpolatedU(7.0D);
double d6 = (double)iconSide.getInterpolatedU(9.0D);
double d7 = (double)iconSide.getMinV();
double d8 = (double)iconSide.getInterpolatedV(8.0D);
double d9 = (double)iconSide.getMaxV();
double d10 = (double)x;
double d11 = (double)x + 0.5D;
double d12 = (double)(x + 1);
double d13 = (double)z;
double d14 = (double)z + 0.5D;
double d15 = (double)(z + 1);
double d16 = (double)x + 0.5D - 0.0625D;
double d17 = (double)x + 0.5D + 0.0625D;
double d18 = (double)z + 0.5D - 0.0625D;
double d19 = (double)z + 0.5D + 0.0625D;
boolean connectedNegZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z - 1));
boolean connectedPosZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z + 1));
boolean connectedNegX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x - 1, y, z));
boolean connectedPosX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x + 1, y, z));
boolean renderTop = pane.shouldSideBeRendered(blockAccess, x, y + 1, z, 1);
boolean renderBottom = pane.shouldSideBeRendered(blockAccess, x, y - 1, z, 0);
if ((!connectedNegX || !connectedPosX) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegX && !connectedPosX)
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d6, d9);
+ tessellator.addVertexWithUV(d11, (double)(y + 1), d18, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
}
else if (!connectedNegX && connectedPosX)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d18, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
else
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
if (y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
if ((!connectedNegZ || !connectedPosZ) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegZ && !connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
}
else if (!connectedNegZ && connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d2, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
else
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
return true;
}
@Override
public boolean shouldRender3DInInventory()
{
return false;
}
@Override
public int getRenderId()
{
return MineFactoryReloadedCore.renderIdFactoryGlassPane;
}
}
| true | true | public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
BlockFactoryGlassPane pane = (BlockFactoryGlassPane)block;
int l = blockAccess.getHeight();
Tessellator tessellator = Tessellator.instance;
tessellator.setBrightness(pane.getMixedBrightnessForBlock(blockAccess, x, y, z));
float f = 1.0F;
int i1 = pane.colorMultiplier(blockAccess, x, y, z);
float f1 = (float)(i1 >> 16 & 255) / 255.0F;
float f2 = (float)(i1 >> 8 & 255) / 255.0F;
float f3 = (float)(i1 & 255) / 255.0F;
if (EntityRenderer.anaglyphEnable)
{
float f4 = (f1 * 30.0F + f2 * 59.0F + f3 * 11.0F) / 100.0F;
float f5 = (f1 * 30.0F + f2 * 70.0F) / 100.0F;
float f6 = (f1 * 30.0F + f3 * 70.0F) / 100.0F;
f1 = f4;
f2 = f5;
f3 = f6;
}
tessellator.setColorOpaque_F(f * f1, f * f2, f * f3);
Icon iconFront;
Icon iconSide;
int metadata;
if(renderer.hasOverrideBlockTexture())
{
iconFront = renderer.overrideBlockTexture;
iconSide = renderer.overrideBlockTexture;
}
else
{
metadata = blockAccess.getBlockMetadata(x, y, z);
iconFront = renderer.getBlockIconFromSideAndMetadata(pane, 0, metadata);
iconSide = pane.getBlockSideTextureFromMetadata(metadata);
}
double d0 = (double)iconFront.getMinU();
double d1 = (double)iconFront.getInterpolatedU(8.0D);
double d2 = (double)iconFront.getMaxU();
double d3 = (double)iconFront.getMinV();
double d4 = (double)iconFront.getMaxV();
double d5 = (double)iconSide.getInterpolatedU(7.0D);
double d6 = (double)iconSide.getInterpolatedU(9.0D);
double d7 = (double)iconSide.getMinV();
double d8 = (double)iconSide.getInterpolatedV(8.0D);
double d9 = (double)iconSide.getMaxV();
double d10 = (double)x;
double d11 = (double)x + 0.5D;
double d12 = (double)(x + 1);
double d13 = (double)z;
double d14 = (double)z + 0.5D;
double d15 = (double)(z + 1);
double d16 = (double)x + 0.5D - 0.0625D;
double d17 = (double)x + 0.5D + 0.0625D;
double d18 = (double)z + 0.5D - 0.0625D;
double d19 = (double)z + 0.5D + 0.0625D;
boolean connectedNegZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z - 1));
boolean connectedPosZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z + 1));
boolean connectedNegX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x - 1, y, z));
boolean connectedPosX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x + 1, y, z));
boolean renderTop = pane.shouldSideBeRendered(blockAccess, x, y + 1, z, 1);
boolean renderBottom = pane.shouldSideBeRendered(blockAccess, x, y - 1, z, 0);
if ((!connectedNegX || !connectedPosX) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegX && !connectedPosX)
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d6, d9);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
}
else if (!connectedNegX && connectedPosX)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d18, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
else
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
if (y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
if ((!connectedNegZ || !connectedPosZ) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegZ && !connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
}
else if (!connectedNegZ && connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d2, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
else
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
return true;
}
| public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
BlockFactoryGlassPane pane = (BlockFactoryGlassPane)block;
int l = blockAccess.getHeight();
Tessellator tessellator = Tessellator.instance;
tessellator.setBrightness(pane.getMixedBrightnessForBlock(blockAccess, x, y, z));
float f = 1.0F;
int i1 = pane.colorMultiplier(blockAccess, x, y, z);
float f1 = (float)(i1 >> 16 & 255) / 255.0F;
float f2 = (float)(i1 >> 8 & 255) / 255.0F;
float f3 = (float)(i1 & 255) / 255.0F;
if (EntityRenderer.anaglyphEnable)
{
float f4 = (f1 * 30.0F + f2 * 59.0F + f3 * 11.0F) / 100.0F;
float f5 = (f1 * 30.0F + f2 * 70.0F) / 100.0F;
float f6 = (f1 * 30.0F + f3 * 70.0F) / 100.0F;
f1 = f4;
f2 = f5;
f3 = f6;
}
tessellator.setColorOpaque_F(f * f1, f * f2, f * f3);
Icon iconFront;
Icon iconSide;
int metadata;
if(renderer.hasOverrideBlockTexture())
{
iconFront = renderer.overrideBlockTexture;
iconSide = renderer.overrideBlockTexture;
}
else
{
metadata = blockAccess.getBlockMetadata(x, y, z);
iconFront = renderer.getBlockIconFromSideAndMetadata(pane, 0, metadata);
iconSide = pane.getBlockSideTextureFromMetadata(metadata);
}
double d0 = (double)iconFront.getMinU();
double d1 = (double)iconFront.getInterpolatedU(8.0D);
double d2 = (double)iconFront.getMaxU();
double d3 = (double)iconFront.getMinV();
double d4 = (double)iconFront.getMaxV();
double d5 = (double)iconSide.getInterpolatedU(7.0D);
double d6 = (double)iconSide.getInterpolatedU(9.0D);
double d7 = (double)iconSide.getMinV();
double d8 = (double)iconSide.getInterpolatedV(8.0D);
double d9 = (double)iconSide.getMaxV();
double d10 = (double)x;
double d11 = (double)x + 0.5D;
double d12 = (double)(x + 1);
double d13 = (double)z;
double d14 = (double)z + 0.5D;
double d15 = (double)(z + 1);
double d16 = (double)x + 0.5D - 0.0625D;
double d17 = (double)x + 0.5D + 0.0625D;
double d18 = (double)z + 0.5D - 0.0625D;
double d19 = (double)z + 0.5D + 0.0625D;
boolean connectedNegZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z - 1));
boolean connectedPosZ = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x, y, z + 1));
boolean connectedNegX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x - 1, y, z));
boolean connectedPosX = pane.canThisFactoryPaneConnectToThisBlockID(blockAccess.getBlockId(x + 1, y, z));
boolean renderTop = pane.shouldSideBeRendered(blockAccess, x, y + 1, z, 1);
boolean renderBottom = pane.shouldSideBeRendered(blockAccess, x, y - 1, z, 0);
if ((!connectedNegX || !connectedPosX) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegX && !connectedPosX)
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1), d18, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
}
else if (!connectedNegX && connectedPosX)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (!connectedPosZ && !connectedNegZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d18, d5, d7);
tessellator.addVertexWithUV(d11, (double)(y + 0), d18, d5, d9);
tessellator.addVertexWithUV(d11, (double)(y + 0), d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1), d19, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
else
{
tessellator.addVertexWithUV(d10, (double)(y + 1), d14, d0, d3);
tessellator.addVertexWithUV(d10, (double)(y + 0), d14, d0, d4);
tessellator.addVertexWithUV(d12, (double)(y + 0), d14, d2, d4);
tessellator.addVertexWithUV(d12, (double)(y + 1), d14, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x - 1, y + 1, z))
{
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)(y + 1) + 0.01D, d18, d5, d8);
}
if (y < l - 1 && blockAccess.isAirBlock(x + 1, y + 1, z))
{
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)(y + 1) + 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)(y + 1) + 0.01D, d18, d5, d7);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d7);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x - 1, y - 1, z))
{
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d9);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d9);
tessellator.addVertexWithUV(d10, (double)y - 0.01D, d18, d5, d8);
}
if (y > 1 && blockAccess.isAirBlock(x + 1, y - 1, z))
{
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d19, d6, d7);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d19, d6, d8);
tessellator.addVertexWithUV(d12, (double)y - 0.01D, d18, d5, d8);
tessellator.addVertexWithUV(d11, (double)y - 0.01D, d18, d5, d7);
}
}
}
if ((!connectedNegZ || !connectedPosZ) && (connectedNegX || connectedPosX || connectedNegZ || connectedPosZ))
{
if (connectedNegZ && !connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
}
else if (!connectedNegZ && connectedPosZ)
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d14, d1, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d14, d1, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d2, d3);
if (!connectedPosX && !connectedNegX)
{
tessellator.addVertexWithUV(d17, (double)(y + 1), d14, d5, d7);
tessellator.addVertexWithUV(d17, (double)(y + 0), d14, d5, d9);
tessellator.addVertexWithUV(d16, (double)(y + 0), d14, d6, d9);
tessellator.addVertexWithUV(d16, (double)(y + 1), d14, d6, d7);
}
if (renderTop || y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
if (renderBottom || y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
else
{
tessellator.addVertexWithUV(d11, (double)(y + 1), d15, d0, d3);
tessellator.addVertexWithUV(d11, (double)(y + 0), d15, d0, d4);
tessellator.addVertexWithUV(d11, (double)(y + 0), d13, d2, d4);
tessellator.addVertexWithUV(d11, (double)(y + 1), d13, d2, d3);
if (renderTop)
{
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
}
else
{
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d13, d5, d7);
}
if (y < l - 1 && blockAccess.isAirBlock(x, y + 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)(y + 1) + 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)(y + 1) + 0.005D, d14, d6, d8);
}
}
if (renderBottom)
{
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d5, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
}
else
{
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z - 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d13, d6, d7);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d6, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d13, d5, d7);
}
if (y > 1 && blockAccess.isAirBlock(x, y - 1, z + 1))
{
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d14, d5, d8);
tessellator.addVertexWithUV(d16, (double)y - 0.005D, d15, d5, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d15, d6, d9);
tessellator.addVertexWithUV(d17, (double)y - 0.005D, d14, d6, d8);
}
}
}
return true;
}
|
diff --git a/common/net/minecraftforge/common/ForgeInternalHandler.java b/common/net/minecraftforge/common/ForgeInternalHandler.java
index 16c516949..c7020d911 100644
--- a/common/net/minecraftforge/common/ForgeInternalHandler.java
+++ b/common/net/minecraftforge/common/ForgeInternalHandler.java
@@ -1,28 +1,28 @@
package net.minecraftforge.common;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (entity instanceof EntityItem)
{
ItemStack item = ((EntityItem)entity).item;
if (item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
- event.world.spawnEntityInWorld(entity);
+ event.world.spawnEntityInWorld(newEntity);
}
}
}
}
}
| true | true | public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (entity instanceof EntityItem)
{
ItemStack item = ((EntityItem)entity).item;
if (item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(entity);
}
}
}
}
| public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
Entity entity = event.entity;
if (entity instanceof EntityItem)
{
ItemStack item = ((EntityItem)entity).item;
if (item.getItem().hasCustomEntity(item))
{
Entity newEntity = item.getItem().createEntity(event.world, entity, item);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
|
diff --git a/src/org/odk/collect/android/UploaderTask.java b/src/org/odk/collect/android/UploaderTask.java
index 4d71405..cced9d5 100644
--- a/src/org/odk/collect/android/UploaderTask.java
+++ b/src/org/odk/collect/android/UploaderTask.java
@@ -1,136 +1,136 @@
/*
* 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 org.odk.collect.android;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.util.Log;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung ([email protected])
*
*/
class UploaderTask extends AsyncTask<String, Integer, Void> {
private final static String t = "UploaderTask";
UploaderListener mStateListener;
/*
* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Void doInBackground(String... values) {
for (int i = 0; i < values.length; i++) {
this.publishProgress(i+1, values.length);
DefaultHttpClient httpclient = new DefaultHttpClient();
//this should get set in a preferences window or something.
HttpPost mypost = new HttpPost("http://opendatakit.appspot.com/submission");
File dir = new File(SharedConstants.ANSWERS_PATH + values[i]);
File[] files = dir.listFiles();
if (files == null)
this.cancel(true);
MultipartEntity entity = new MultipartEntity();
Log.e(t, "# of files " + files.length);
for(int j = 0; j < files.length; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
- Log.i(t, "adding xml file: " + f.getName());
+ Log.i(t, "adding xml file: " + f.getAbsolutePath());
entity.addPart("xml_submission_file", new FileBody(f));
}
- if (f.getName().endsWith(".png")) {
- Log.i(t, "adding image file: " + f.getName());
- entity.addPart("datafile", new FileBody(f));
+ else if (f.getName().endsWith(".png") || f.getName().endsWith(".jpg")) {
+ Log.i(t, "adding image file: " + f.getAbsolutePath());
+ entity.addPart(f.getName(), new FileBody(f));
} else {
- Log.i(t, "unhandled file: " + f.getName());
+ Log.i(t, "unhandled file: " + f.getAbsolutePath());
}
}
mypost.setEntity(entity);
HttpResponse response = null;
try {
response = httpclient.execute(mypost);
} catch (ClientProtocolException e) {
Log.e(t, "Protocol Exception Error");
e.printStackTrace();
} catch (IOException e) {
Log.e(t, "IO Execption Error");
e.printStackTrace();
}
if (response != null && response.getStatusLine().getStatusCode() == 200) {
Log.d(t, "response: " + response.getStatusLine());
} else {
Log.d(t, "response: " + response.getStatusLine());
}
}
// this is just for testing
/* for (int j = 0; j < 5; j++) {
this.publishProgress(j, 5);
for (int i = 0; i < 1000; i++) {
Log.e("testing", "wasiting time " + i );
}
if (j == 3)
this.cancel(true);
}*/
return null;
}
/*
* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Void unused) {
synchronized (this) {
if (mStateListener != null) mStateListener.uploadingComplete();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null)
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
public void setUploaderListener(UploaderListener sl) {
mStateListener = sl;
}
}
| false | true | protected Void doInBackground(String... values) {
for (int i = 0; i < values.length; i++) {
this.publishProgress(i+1, values.length);
DefaultHttpClient httpclient = new DefaultHttpClient();
//this should get set in a preferences window or something.
HttpPost mypost = new HttpPost("http://opendatakit.appspot.com/submission");
File dir = new File(SharedConstants.ANSWERS_PATH + values[i]);
File[] files = dir.listFiles();
if (files == null)
this.cancel(true);
MultipartEntity entity = new MultipartEntity();
Log.e(t, "# of files " + files.length);
for(int j = 0; j < files.length; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
Log.i(t, "adding xml file: " + f.getName());
entity.addPart("xml_submission_file", new FileBody(f));
}
if (f.getName().endsWith(".png")) {
Log.i(t, "adding image file: " + f.getName());
entity.addPart("datafile", new FileBody(f));
} else {
Log.i(t, "unhandled file: " + f.getName());
}
}
mypost.setEntity(entity);
HttpResponse response = null;
try {
response = httpclient.execute(mypost);
} catch (ClientProtocolException e) {
Log.e(t, "Protocol Exception Error");
e.printStackTrace();
} catch (IOException e) {
Log.e(t, "IO Execption Error");
e.printStackTrace();
}
if (response != null && response.getStatusLine().getStatusCode() == 200) {
Log.d(t, "response: " + response.getStatusLine());
} else {
Log.d(t, "response: " + response.getStatusLine());
}
}
// this is just for testing
/* for (int j = 0; j < 5; j++) {
this.publishProgress(j, 5);
for (int i = 0; i < 1000; i++) {
Log.e("testing", "wasiting time " + i );
}
if (j == 3)
this.cancel(true);
}*/
| protected Void doInBackground(String... values) {
for (int i = 0; i < values.length; i++) {
this.publishProgress(i+1, values.length);
DefaultHttpClient httpclient = new DefaultHttpClient();
//this should get set in a preferences window or something.
HttpPost mypost = new HttpPost("http://opendatakit.appspot.com/submission");
File dir = new File(SharedConstants.ANSWERS_PATH + values[i]);
File[] files = dir.listFiles();
if (files == null)
this.cancel(true);
MultipartEntity entity = new MultipartEntity();
Log.e(t, "# of files " + files.length);
for(int j = 0; j < files.length; j++) {
File f = files[j];
if (f.getName().endsWith(".xml")) {
Log.i(t, "adding xml file: " + f.getAbsolutePath());
entity.addPart("xml_submission_file", new FileBody(f));
}
else if (f.getName().endsWith(".png") || f.getName().endsWith(".jpg")) {
Log.i(t, "adding image file: " + f.getAbsolutePath());
entity.addPart(f.getName(), new FileBody(f));
} else {
Log.i(t, "unhandled file: " + f.getAbsolutePath());
}
}
mypost.setEntity(entity);
HttpResponse response = null;
try {
response = httpclient.execute(mypost);
} catch (ClientProtocolException e) {
Log.e(t, "Protocol Exception Error");
e.printStackTrace();
} catch (IOException e) {
Log.e(t, "IO Execption Error");
e.printStackTrace();
}
if (response != null && response.getStatusLine().getStatusCode() == 200) {
Log.d(t, "response: " + response.getStatusLine());
} else {
Log.d(t, "response: " + response.getStatusLine());
}
}
// this is just for testing
/* for (int j = 0; j < 5; j++) {
this.publishProgress(j, 5);
for (int i = 0; i < 1000; i++) {
Log.e("testing", "wasiting time " + i );
}
if (j == 3)
this.cancel(true);
}*/
|
diff --git a/src/main/java/hudson/plugins/clover/CloverBuildWrapper.java b/src/main/java/hudson/plugins/clover/CloverBuildWrapper.java
index 9426da0..093801b 100644
--- a/src/main/java/hudson/plugins/clover/CloverBuildWrapper.java
+++ b/src/main/java/hudson/plugins/clover/CloverBuildWrapper.java
@@ -1,173 +1,174 @@
package hudson.plugins.clover;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.Launcher;
import hudson.Proc;
import hudson.FilePath;
import hudson.Extension;
import hudson.Util;
import hudson.util.DescribableList;
import hudson.remoting.Channel;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Run;
import hudson.model.Descriptor;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Project;
import hudson.model.FreeStyleProject;
import hudson.model.Action;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.DataBoundConstructor;
import net.sf.json.JSONObject;
import com.atlassian.clover.api.ci.CIOptions;
import com.atlassian.clover.api.ci.Integrator;
/**
* A BuildWrapper that decorates the command line just before a build starts with targets and properties that will automatically
* integrate Clover into the Ant build.
*/
public class CloverBuildWrapper extends BuildWrapper {
public boolean historical = true;
public boolean json = true;
public String licenseCert;
@DataBoundConstructor
public CloverBuildWrapper(boolean historical, boolean json, String licenseCert) {
this.historical = historical;
this.json = json;
this.licenseCert = licenseCert;
}
@Override
public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
addCloverPublisher(build, listener);
return new Environment() {};
}
private void addCloverPublisher(AbstractBuild build, BuildListener listener) throws IOException {
DescribableList publishers = build.getProject().getPublishersList();
if (!publishers.contains(CloverPublisher.DESCRIPTOR)) {
final String reportDir = "clover";
listener.getLogger().println("Adding Clover Publisher with reportDir: " + reportDir);
build.getProject().getPublishersList().add(new CloverPublisher(reportDir));
}
}
@Override
public Action getProjectAction(AbstractProject job) {
// ensure only one project action exists on the project
if (job.getAction(CloverProjectAction.class) == null) {
return new CloverProjectAction((Project) job);
}
return super.getProjectAction(job);
}
@Override
public Launcher decorateLauncher(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
final DescriptorImpl descriptor = Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
final String license = Util.nullify(licenseCert) == null ? descriptor.licenseCert : licenseCert;
final CIOptions.Builder options = new CIOptions.Builder().
json(this.json).
historical(this.historical).
licenseCert(license).
fullClean(true);
final Launcher outer = launcher;
return new Launcher(outer) {
@Override
public Proc launch(ProcStarter starter) throws IOException {
if (!starter.cmds().isEmpty() && !starter.cmds().get(0).endsWith("ant")) {
} else {
Integrator integrator = Integrator.Factory.newAntIntegrator(options.build());
// decorateArguments takes a list of just the targets. does not include '/usr/bin/ant'
- integrator.decorateArguments(starter.cmds().subList(1, starter.cmds().size() - 1));
+ final int toindex = (starter.cmds().size() == 1) ? 1 : starter.cmds().size() - 1;
+ integrator.decorateArguments(starter.cmds().subList(1, toindex));
// masks.length must equal cmds.length
boolean[] masks = new boolean[starter.cmds().size()];
for (int i = 0; i < starter.masks().length; i++) {
masks[i] = starter.masks()[i];
}
starter.masks(masks);
}
return outer.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException {
return outer.launchChannel(cmd, out, workDir, envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
outer.kill(modelEnvVars);
}
};
}
public static final Descriptor<BuildWrapper> DESCRIPTOR = new DescriptorImpl();
/**
* Descriptor for {@link CloverPublisher}. Used as a singleton. The class is marked as public so that it can be
* accessed from views.
* <p/>
* <p/>
* See <tt>views/hudson/plugins/clover/CloverPublisher/*.jelly</tt> for the actual HTML fragment for the
* configuration screen.
*/
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
public String licenseCert;
public DescriptorImpl() {
super(CloverBuildWrapper.class);
load();
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "<img src='"+CloverProjectAction.ICON+"' height='24'/> Automatically record and report Code Coverage using <a href='http://atlassian.com/clover'>Clover.</a>. Currently for Ant builds only.";
}
@Override
public String getHelpFile() {
return "/plugin/clover/help-cloverConfig.html";
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
req.bindParameters(this, "clover.");
save();
return true;
}
public boolean isApplicable(AbstractProject item) {
// TODO: is there a better way to detect Ant builds?
// should only be enabled for Ant projects.
return (item instanceof FreeStyleProject);
}
}
}
| true | true | public Launcher decorateLauncher(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
final DescriptorImpl descriptor = Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
final String license = Util.nullify(licenseCert) == null ? descriptor.licenseCert : licenseCert;
final CIOptions.Builder options = new CIOptions.Builder().
json(this.json).
historical(this.historical).
licenseCert(license).
fullClean(true);
final Launcher outer = launcher;
return new Launcher(outer) {
@Override
public Proc launch(ProcStarter starter) throws IOException {
if (!starter.cmds().isEmpty() && !starter.cmds().get(0).endsWith("ant")) {
} else {
Integrator integrator = Integrator.Factory.newAntIntegrator(options.build());
// decorateArguments takes a list of just the targets. does not include '/usr/bin/ant'
integrator.decorateArguments(starter.cmds().subList(1, starter.cmds().size() - 1));
// masks.length must equal cmds.length
boolean[] masks = new boolean[starter.cmds().size()];
for (int i = 0; i < starter.masks().length; i++) {
masks[i] = starter.masks()[i];
}
starter.masks(masks);
}
return outer.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException {
return outer.launchChannel(cmd, out, workDir, envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
outer.kill(modelEnvVars);
}
};
}
| public Launcher decorateLauncher(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
final DescriptorImpl descriptor = Hudson.getInstance().getDescriptorByType(DescriptorImpl.class);
final String license = Util.nullify(licenseCert) == null ? descriptor.licenseCert : licenseCert;
final CIOptions.Builder options = new CIOptions.Builder().
json(this.json).
historical(this.historical).
licenseCert(license).
fullClean(true);
final Launcher outer = launcher;
return new Launcher(outer) {
@Override
public Proc launch(ProcStarter starter) throws IOException {
if (!starter.cmds().isEmpty() && !starter.cmds().get(0).endsWith("ant")) {
} else {
Integrator integrator = Integrator.Factory.newAntIntegrator(options.build());
// decorateArguments takes a list of just the targets. does not include '/usr/bin/ant'
final int toindex = (starter.cmds().size() == 1) ? 1 : starter.cmds().size() - 1;
integrator.decorateArguments(starter.cmds().subList(1, toindex));
// masks.length must equal cmds.length
boolean[] masks = new boolean[starter.cmds().size()];
for (int i = 0; i < starter.masks().length; i++) {
masks[i] = starter.masks()[i];
}
starter.masks(masks);
}
return outer.launch(starter);
}
@Override
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException {
return outer.launchChannel(cmd, out, workDir, envVars);
}
@Override
public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException {
outer.kill(modelEnvVars);
}
};
}
|
diff --git a/src/java/com/sapienter/jbilling/server/mediation/task/AbstractFileReader.java b/src/java/com/sapienter/jbilling/server/mediation/task/AbstractFileReader.java
index 622bfc37..34240483 100644
--- a/src/java/com/sapienter/jbilling/server/mediation/task/AbstractFileReader.java
+++ b/src/java/com/sapienter/jbilling/server/mediation/task/AbstractFileReader.java
@@ -1,453 +1,457 @@
/*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.server.mediation.task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.List;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import com.sapienter.jbilling.common.SessionInternalError;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.item.PricingField;
import com.sapienter.jbilling.server.mediation.Format;
import com.sapienter.jbilling.server.mediation.FormatField;
import com.sapienter.jbilling.server.mediation.Record;
import com.sapienter.jbilling.server.pluggableTask.admin.ParameterDescription;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.commons.digester.Digester;
public abstract class AbstractFileReader extends AbstractReader {
private String directory;
private String suffix;
private boolean rename;
private SimpleDateFormat dateFormat;
private boolean removeQuote;
private boolean autoID;
private static final Logger LOG = Logger.getLogger(AbstractFileReader.class);
private String formatFileName = null;
protected Format format = null;
private int bufferSize;
public AbstractFileReader() {
}
public static final ParameterDescription PARAMETER_FORMAT_FILE =
new ParameterDescription("format_file", true, ParameterDescription.Type.STR);
// optionals
public static final ParameterDescription PARAMETER_FORMAT_DIRECTORY =
new ParameterDescription("format_directory", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_DIRECTORY =
new ParameterDescription("directory", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_SUFFIX =
new ParameterDescription("suffix", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_RENAME =
new ParameterDescription("rename", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_DATE_FORMAT =
new ParameterDescription("date_format", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_REMOVE_QUOTE =
new ParameterDescription("removeQuote", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_AUTO_ID =
new ParameterDescription("autoID", false, ParameterDescription.Type.STR);
public static final ParameterDescription PARAMETER_BUFFER_SIZE =
new ParameterDescription("buffer_size", false, ParameterDescription.Type.STR);
//initializer for pluggable params
{
descriptions.add(PARAMETER_FORMAT_FILE);
descriptions.add(PARAMETER_FORMAT_DIRECTORY);
descriptions.add(PARAMETER_DIRECTORY);
descriptions.add(PARAMETER_SUFFIX);
descriptions.add(PARAMETER_RENAME);
descriptions.add(PARAMETER_DATE_FORMAT);
descriptions.add(PARAMETER_REMOVE_QUOTE);
descriptions.add(PARAMETER_AUTO_ID);
descriptions.add(PARAMETER_BUFFER_SIZE);
}
@Override
public boolean validate(List<String> messages) {
boolean retValue = super.validate(messages);
String formatFile = getParameter(PARAMETER_FORMAT_FILE.getName(), (String) null);
String formatDirectory = getParameter(PARAMETER_FORMAT_DIRECTORY.getName(), Util.getSysProp("base_dir") + "mediation");
if (formatFile == null) {
messages.add("parameter format_file is required");
return false;
}
formatFileName = formatDirectory + File.separator + formatFile;
// optionals
directory = getParameter(PARAMETER_DIRECTORY.getName(), Util.getSysProp("base_dir") + "mediation");
if (directory == null) {
messages.add("The plug-in parameter 'directory' is mandatory");
retValue = false;
}
suffix = getParameter(PARAMETER_SUFFIX.getName(), "ALL");
rename = getParameter(PARAMETER_RENAME.getName(), false);
dateFormat = new SimpleDateFormat(getParameter(PARAMETER_DATE_FORMAT.getName(), "yyyyMMdd-HHmmss"));
removeQuote = getParameter(PARAMETER_REMOVE_QUOTE.getName(), true);
autoID = getParameter(PARAMETER_AUTO_ID.getName(), false);
try {
bufferSize = getParameter(PARAMETER_BUFFER_SIZE.getName(), 0);
} catch (PluggableTaskException e) {
messages.add(e.getMessage());
}
LOG.debug("Started with " + " directory: " + directory + " suffix " + suffix + " rename " +
rename + " date format " + dateFormat.toPattern() + " removeQuote " + removeQuote +
" autoID " + autoID);
return retValue;
}
protected Format getFormat() throws IOException, SAXException {
// parse the XML ...
// create a field object per field element
if (format == null) {
Digester digester = new Digester();
digester.setValidating(true);
digester.setUseContextClassLoader(true);
digester.addObjectCreate("format", "com.sapienter.jbilling.server.mediation.Format");
digester.addObjectCreate("format/field", "com.sapienter.jbilling.server.mediation.FormatField");
digester.addCallMethod("format/field/name","setName",0);
digester.addCallMethod("format/field/type","setType",0);
digester.addCallMethod("format/field/startPosition","setStartPosition",0);
digester.addCallMethod("format/field/durationFormat","setDurationFormat",0);
digester.addCallMethod("format/field/length","setLength",0);
digester.addCallMethod("format/field/isKey","isKeyTrue");
digester.addSetNext("format/field", "addField", "com.sapienter.jbilling.server.mediation.FormatField");
format = (Format) digester.parse(new File(formatFileName));
LOG.debug("using format: " + format);
}
return format;
}
@Override
public Iterator<List<Record>> iterator() {
try {
return new Reader();
} catch (Exception e) {
throw new SessionInternalError(e);
}
}
/**
* This sorts the files so the oldest is processed first, and the newest last
*/
public class Reader implements Iterator<List<Record>> {
private final Logger LOG = Logger.getLogger(Reader.class);
private File[] files = null;
private int fileIndex = 0;
private List<Record> records = null;
private BufferedReader reader = null;
private int counter;
protected final Format format;
protected Reader() throws FileNotFoundException, IOException, SAXException {
files = new File(directory).listFiles(new FileFilter() {
public boolean accept(File pathname) {
if (suffix.equalsIgnoreCase("all") || pathname.getName().endsWith(suffix)) {
return true;
} else {
return false;
}
}
});
// sort the files, so the oldest is processed first
Arrays.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
return new Long(o1.lastModified()).compareTo(o2.lastModified());
}
});
if (!nextReader()) {
LOG.info("No files found to process");
format = null;
} else {
LOG.debug("Files to process = " + files.length);
format = getFormat();
counter = 0;
records = new ArrayList<Record>(getBatchSize());
}
}
/**
* Get the next set or records
* @return true if there are some, otherwise false
*/
public boolean hasNext() {
if (reader == null) {
return false;
}
records.clear();
String line = readLine();
int startedAt = 0;
while (line != null) {
counter++; // it read one just now
// convert this line to a Record
records.add(convertLineToRecord(line));
if (++startedAt >= getBatchSize()) {
break;
}
line = readLine();
}
return records.size() > 0;
}
/**
* Reads the next line from the current file, or closes this file and
* starts with the next one.
* @return The line read, or null if there are not any others.
*/
private String readLine() {
try {
String line = reader.readLine();
if (line == null) {
// we are done with this file
reader.close();
// rename it to avoid re-processing, if configured
if (rename) {
if (!files[fileIndex].renameTo(
new File(files[fileIndex].getAbsolutePath() + ".done"))) {
LOG.warn("Could not rename file " + files[fileIndex].getName());
}
}
// reached the last line, go to the next file
if (!nextReader()) {
return null; // all done then
} else {
// read the first line from the next file
line = reader.readLine();
counter = 0;
}
}
return line;
} catch (Exception e) {
throw new SessionInternalError(e);
}
}
/**
* Returns the records read since the last call to 'hasNext'
*/
public List<Record> next() {
if (records.size() == 0) {
throw new NoSuchElementException();
}
return records;
}
private Record convertLineToRecord(String line) {
String lineErrorString=null;
// get the raw fields from the line
String tokens[] = splitFields(line);
if (tokens.length != format.getFields().size() && !autoID) {
lineErrorString="Mismatch of number of fields between " +
"the format and the file for line " + line + " Expected " +
format.getFields().size() + " found " + tokens.length;
LOG.warn(lineErrorString);
}
// remove quotes if needed
if (removeQuote) {
for (int f = 0; f < tokens.length; f++) {
if (tokens[f].length() < 2) {
continue;
}
// remove first and last char, if they are quotes
if ((tokens[f].charAt(0) == '\"' || tokens[f].charAt(0) == '\'') &&
(tokens[f].charAt(tokens[f].length() - 1) == '\"' || tokens[f].charAt(tokens[f].length() - 1) == '\'')) {
tokens[f] = tokens[f].substring(1, tokens[f].length() - 1);
}
}
}
// create the record
Record record = new Record();
int tkIdx = 0;
try {
for (FormatField field:format.getFields()) {
if (autoID && field.getIsKey()) {
record.addField(new PricingField(field.getName(),
files[fileIndex].getName() + "-" + counter ), field.getIsKey());
tkIdx++;
continue;
}
switch (PricingField.mapType(field.getType())) {
case STRING:
record.addField(new PricingField(field.getName(),
tokens[tkIdx++]), field.getIsKey());
break;
case INTEGER:
String intStr = tokens[tkIdx++].trim();
if (field.getDurationFormat() != null && field.getDurationFormat().length() > 0) {
// requires hour/minute conversion
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
convertDuration(intStr, field.getDurationFormat()) : null),
field.getIsKey());
} else {
try {
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
Integer.valueOf(intStr.trim()) : null), field.getIsKey());
} catch (NumberFormatException e) {
throw new SessionInternalError("Converting to integer " + field +
" line " + line, AbstractFileReader.class, e);
}
}
break;
case DATE:
try {
String dateStr = tokens[tkIdx++];
record.addField(new PricingField(field.getName(), dateStr.length() > 0 ?
dateFormat.parse(dateStr) : null), field.getIsKey());
} catch (ParseException e) {
throw new SessionInternalError("Using format: " + dateFormat + "[" +
parameters.get(PARAMETER_DATE_FORMAT.getName()) + "]",
AbstractFileReader.class,e);
}
break;
case DECIMAL:
String floatStr = tokens[tkIdx++].trim();
record.addField(new PricingField(field.getName(), floatStr.length() > 0 ?
new BigDecimal(floatStr) : null), field.getIsKey());
break;
case BOOLEAN:
boolean value = "true".equalsIgnoreCase(tokens[tkIdx++].trim());
record.addField(new PricingField(field.getName(), value), field.getIsKey());
break;
}
}
} catch (RuntimeException e) {
//any format error in the Record creation will make this record trappable by the mediation processor
record.getErrors().add(e.getMessage());
}
//to handle format errors in the records
if ( null != lineErrorString ) {
- record.getErrors().set(0, lineErrorString);
+ if (record.getErrors().size()== 0 ) {
+ record.getErrors().add(lineErrorString);
+ } else {
+ record.getErrors().set(0, lineErrorString);
+ }
}
record.setPosition(counter);
return record;
}
private boolean nextReader() throws FileNotFoundException {
if (reader != null) { // first call
fileIndex++;
}
if (files.length > fileIndex) { // any more to process ?
if (bufferSize > 0) {
reader = new BufferedReader(new java.io.FileReader(files[fileIndex]), bufferSize);
} else {
reader = new BufferedReader(new java.io.FileReader(files[fileIndex]));
}
LOG.debug("Now processing file " + files[fileIndex].getName());
return true;
}
reader = null;
return false;
}
public void remove() {
// needed to comply with Iterator only
throw new SessionInternalError("remove not supported");
}
}
/**
* Chars 'H', 'M' and 'S' have to be grouped or the behaviour will be unexpected
* @param content
* @param format
* @return
*/
public static int convertDuration(String content, String format) {
int totalSeconds = 0;
// hours
try {
try {
totalSeconds += Integer.valueOf(content.substring(format.indexOf('H'),
format.lastIndexOf('H') + 1).trim()) * 60 * 60;
} catch (IndexOutOfBoundsException e) {
// no hours. ok
}
// minutes
try {
totalSeconds += Integer.valueOf(content.substring(format.indexOf('M'),
format.lastIndexOf('M') + 1).trim()) * 60;
} catch (IndexOutOfBoundsException e) {
// no minutes. ok
}
// seconds
try {
totalSeconds += Integer.valueOf(content.substring(format.indexOf('S'),
format.lastIndexOf('S') + 1).trim());
} catch (IndexOutOfBoundsException e) {
// no seconds. ok
}
} catch (NumberFormatException e) {
throw new SessionInternalError("converting duration format " + format + " content " + content,
AbstractFileReader.class, e);
}
return totalSeconds;
}
protected abstract String[] splitFields(String line);
}
| true | true | private Record convertLineToRecord(String line) {
String lineErrorString=null;
// get the raw fields from the line
String tokens[] = splitFields(line);
if (tokens.length != format.getFields().size() && !autoID) {
lineErrorString="Mismatch of number of fields between " +
"the format and the file for line " + line + " Expected " +
format.getFields().size() + " found " + tokens.length;
LOG.warn(lineErrorString);
}
// remove quotes if needed
if (removeQuote) {
for (int f = 0; f < tokens.length; f++) {
if (tokens[f].length() < 2) {
continue;
}
// remove first and last char, if they are quotes
if ((tokens[f].charAt(0) == '\"' || tokens[f].charAt(0) == '\'') &&
(tokens[f].charAt(tokens[f].length() - 1) == '\"' || tokens[f].charAt(tokens[f].length() - 1) == '\'')) {
tokens[f] = tokens[f].substring(1, tokens[f].length() - 1);
}
}
}
// create the record
Record record = new Record();
int tkIdx = 0;
try {
for (FormatField field:format.getFields()) {
if (autoID && field.getIsKey()) {
record.addField(new PricingField(field.getName(),
files[fileIndex].getName() + "-" + counter ), field.getIsKey());
tkIdx++;
continue;
}
switch (PricingField.mapType(field.getType())) {
case STRING:
record.addField(new PricingField(field.getName(),
tokens[tkIdx++]), field.getIsKey());
break;
case INTEGER:
String intStr = tokens[tkIdx++].trim();
if (field.getDurationFormat() != null && field.getDurationFormat().length() > 0) {
// requires hour/minute conversion
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
convertDuration(intStr, field.getDurationFormat()) : null),
field.getIsKey());
} else {
try {
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
Integer.valueOf(intStr.trim()) : null), field.getIsKey());
} catch (NumberFormatException e) {
throw new SessionInternalError("Converting to integer " + field +
" line " + line, AbstractFileReader.class, e);
}
}
break;
case DATE:
try {
String dateStr = tokens[tkIdx++];
record.addField(new PricingField(field.getName(), dateStr.length() > 0 ?
dateFormat.parse(dateStr) : null), field.getIsKey());
} catch (ParseException e) {
throw new SessionInternalError("Using format: " + dateFormat + "[" +
parameters.get(PARAMETER_DATE_FORMAT.getName()) + "]",
AbstractFileReader.class,e);
}
break;
case DECIMAL:
String floatStr = tokens[tkIdx++].trim();
record.addField(new PricingField(field.getName(), floatStr.length() > 0 ?
new BigDecimal(floatStr) : null), field.getIsKey());
break;
case BOOLEAN:
boolean value = "true".equalsIgnoreCase(tokens[tkIdx++].trim());
record.addField(new PricingField(field.getName(), value), field.getIsKey());
break;
}
}
} catch (RuntimeException e) {
//any format error in the Record creation will make this record trappable by the mediation processor
record.getErrors().add(e.getMessage());
}
//to handle format errors in the records
if ( null != lineErrorString ) {
record.getErrors().set(0, lineErrorString);
}
record.setPosition(counter);
return record;
}
| private Record convertLineToRecord(String line) {
String lineErrorString=null;
// get the raw fields from the line
String tokens[] = splitFields(line);
if (tokens.length != format.getFields().size() && !autoID) {
lineErrorString="Mismatch of number of fields between " +
"the format and the file for line " + line + " Expected " +
format.getFields().size() + " found " + tokens.length;
LOG.warn(lineErrorString);
}
// remove quotes if needed
if (removeQuote) {
for (int f = 0; f < tokens.length; f++) {
if (tokens[f].length() < 2) {
continue;
}
// remove first and last char, if they are quotes
if ((tokens[f].charAt(0) == '\"' || tokens[f].charAt(0) == '\'') &&
(tokens[f].charAt(tokens[f].length() - 1) == '\"' || tokens[f].charAt(tokens[f].length() - 1) == '\'')) {
tokens[f] = tokens[f].substring(1, tokens[f].length() - 1);
}
}
}
// create the record
Record record = new Record();
int tkIdx = 0;
try {
for (FormatField field:format.getFields()) {
if (autoID && field.getIsKey()) {
record.addField(new PricingField(field.getName(),
files[fileIndex].getName() + "-" + counter ), field.getIsKey());
tkIdx++;
continue;
}
switch (PricingField.mapType(field.getType())) {
case STRING:
record.addField(new PricingField(field.getName(),
tokens[tkIdx++]), field.getIsKey());
break;
case INTEGER:
String intStr = tokens[tkIdx++].trim();
if (field.getDurationFormat() != null && field.getDurationFormat().length() > 0) {
// requires hour/minute conversion
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
convertDuration(intStr, field.getDurationFormat()) : null),
field.getIsKey());
} else {
try {
record.addField(new PricingField(field.getName(), intStr.length() > 0 ?
Integer.valueOf(intStr.trim()) : null), field.getIsKey());
} catch (NumberFormatException e) {
throw new SessionInternalError("Converting to integer " + field +
" line " + line, AbstractFileReader.class, e);
}
}
break;
case DATE:
try {
String dateStr = tokens[tkIdx++];
record.addField(new PricingField(field.getName(), dateStr.length() > 0 ?
dateFormat.parse(dateStr) : null), field.getIsKey());
} catch (ParseException e) {
throw new SessionInternalError("Using format: " + dateFormat + "[" +
parameters.get(PARAMETER_DATE_FORMAT.getName()) + "]",
AbstractFileReader.class,e);
}
break;
case DECIMAL:
String floatStr = tokens[tkIdx++].trim();
record.addField(new PricingField(field.getName(), floatStr.length() > 0 ?
new BigDecimal(floatStr) : null), field.getIsKey());
break;
case BOOLEAN:
boolean value = "true".equalsIgnoreCase(tokens[tkIdx++].trim());
record.addField(new PricingField(field.getName(), value), field.getIsKey());
break;
}
}
} catch (RuntimeException e) {
//any format error in the Record creation will make this record trappable by the mediation processor
record.getErrors().add(e.getMessage());
}
//to handle format errors in the records
if ( null != lineErrorString ) {
if (record.getErrors().size()== 0 ) {
record.getErrors().add(lineErrorString);
} else {
record.getErrors().set(0, lineErrorString);
}
}
record.setPosition(counter);
return record;
}
|
diff --git a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
index fd3342d55a..d4300a4f3d 100644
--- a/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
+++ b/mes-plugins/mes-plugins-production-counting/src/main/java/com/qcadoo/mes/productionCounting/internal/print/ProductionCountingPdfService.java
@@ -1,407 +1,407 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.1.4
*
* This file is part of Qcadoo.
*
* Qcadoo 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.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.productionCounting.internal.print;
import static com.qcadoo.mes.productionCounting.internal.constants.OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.qcadoo.localization.api.TranslationService;
import com.qcadoo.localization.api.utils.DateUtils;
import com.qcadoo.mes.productionCounting.internal.constants.ProductionCountingConstants;
import com.qcadoo.mes.productionCounting.internal.print.utils.EntityProductInOutComparator;
import com.qcadoo.mes.productionCounting.internal.print.utils.EntityProductionRecordComparator;
import com.qcadoo.mes.productionCounting.internal.states.ProductionCountingStates;
import com.qcadoo.mes.technologies.TechnologyService;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.NumberService;
import com.qcadoo.model.api.search.SearchRestrictions;
import com.qcadoo.report.api.FontUtils;
import com.qcadoo.report.api.pdf.PdfDocumentService;
import com.qcadoo.report.api.pdf.PdfHelper;
import com.qcadoo.security.api.SecurityService;
import com.qcadoo.view.api.utils.TimeConverterService;
@Service
public class ProductionCountingPdfService extends PdfDocumentService {
private static final String TAB_SPACE_LITERAL = "\t \t \t";
private static final String FIELD_USED_QUANTITY = "usedQuantity";
private static final String NOT_AVAILABLE = "";
private static final String QCADOO_VIEW_FALSE = "qcadooView.false";
private static final String QCADOO_VIEW_TRUE = "qcadooView.true";
private static final String FIELD_PRODUCT = "product";
private static final String FIELD_NAME = "name";
private static final String FIELD_ORDER = "order";
@Autowired
private DataDefinitionService dataDefinitionService;
@Autowired
private SecurityService securityService;
@Autowired
private TimeConverterService timeConverterService;
@Autowired
private TechnologyService technologyService;
@Autowired
private TranslationService translationService;
@Autowired
private NumberService numberService;
@Autowired
private PdfHelper pdfHelper;
@Override
protected void buildPdfContent(final Document document, final Entity productionCounting, final Locale locale)
throws DocumentException {
final String documentTitle = translationService.translate("productionCounting.productionCounting.report.title", locale)
+ " " + productionCounting.getId().toString();
final String documentAuthor = translationService.translate("qcadooReport.commons.generatedBy.label", locale);
pdfHelper.addDocumentHeader(document, "", documentTitle, documentAuthor, (Date) productionCounting.getField("date"),
securityService.getCurrentUserName());
final PdfPTable leftPanel = createLeftPanel(productionCounting, locale);
final PdfPTable rightPanel = createRightPanel(productionCounting, locale);
final PdfPTable panelTable = pdfHelper.createPanelTable(2);
panelTable.addCell(leftPanel);
panelTable.addCell(rightPanel);
panelTable.setSpacingAfter(20);
panelTable.setSpacingBefore(20);
document.add(panelTable);
final List<Entity> productionRecordsList = dataDefinitionService
.get(ProductionCountingConstants.PLUGIN_IDENTIFIER, ProductionCountingConstants.MODEL_PRODUCTION_RECORD).find()
.add(SearchRestrictions.eq("state", ProductionCountingStates.ACCEPTED.getStringValue()))
.add(SearchRestrictions.belongsTo(FIELD_ORDER, productionCounting.getBelongsToField(FIELD_ORDER))).list()
.getEntities();
Collections.sort(productionRecordsList, new EntityProductionRecordComparator());
for (Entity productionRecord : productionRecordsList) {
addProductionRecord(document, productionRecord, locale);
}
}
private void addTableCellAsTable(final PdfPTable table, final String label, final Object fieldValue, final String nullValue,
final Font headerFont, final Font valueFont, final DecimalFormat df) {
final PdfPTable cellTable = new PdfPTable(2);
cellTable.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
cellTable.addCell(new Phrase(label, headerFont));
final Object value = fieldValue;
if (value == null) {
cellTable.addCell(new Phrase(nullValue, valueFont));
} else {
if (value instanceof BigDecimal && df != null) {
cellTable.addCell(new Phrase(df.format(value), valueFont));
} else {
cellTable.addCell(new Phrase(value.toString(), valueFont));
}
}
table.addCell(cellTable);
}
private PdfPTable createLeftPanel(final Entity productionCounting, final Locale locale) {
final PdfPTable leftPanel = pdfHelper.createPanelTable(1);
addTableCellAsTable(leftPanel, translationService.translate("productionCounting.productionCounting.report.title", locale)
+ ":", productionCounting.getId().toString(), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(leftPanel,
translationService.translate("productionCounting.productionBalance.report.panel.order", locale),
productionCounting.getBelongsToField(FIELD_ORDER).getStringField(FIELD_NAME), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(leftPanel,
translationService.translate("productionCounting.productionBalance.report.panel.product", locale),
productionCounting.getBelongsToField(FIELD_PRODUCT).getStringField(FIELD_NAME), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(leftPanel,
translationService.translate("productionCounting.productionBalance.report.panel.numberOfRecords", locale),
String.valueOf(productionCounting.getBelongsToField(FIELD_ORDER).getHasManyField("productionRecords").size()),
null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(leftPanel,
translationService.translate("productionCounting.productionBalance.description.label", locale) + ":",
productionCounting.getStringField("description"), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
return leftPanel;
}
private PdfPTable createRightPanel(final Entity productionCounting, final Locale locale) {
final PdfPTable rightPanel = pdfHelper.createPanelTable(1);
rightPanel.addCell(new Phrase(translationService.translate(
"costCalculation.costCalculationDetails.window.mainTab.form.parameters", locale) + ":", FontUtils
.getDejavuBold10Dark()));
rightPanel
.addCell(new Phrase(
TAB_SPACE_LITERAL
+ translationService.translate(
"productionCounting.productionBalance.report.panel.registerQuantityOutProduct", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField(
"registerQuantityInProduct") ? translationService.translate(QCADOO_VIEW_TRUE, locale)
: translationService.translate(QCADOO_VIEW_FALSE, locale)), FontUtils
.getDejavuBold9Dark()));
rightPanel
.addCell(new Phrase(
TAB_SPACE_LITERAL
+ translationService.translate(
"productionCounting.productionBalance.report.panel.registerQuantityInProduct", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField(
"registerQuantityOutProduct") ? translationService.translate(QCADOO_VIEW_TRUE, locale)
: translationService.translate(QCADOO_VIEW_FALSE, locale)), FontUtils
.getDejavuBold9Dark()));
rightPanel
.addCell(new Phrase(
TAB_SPACE_LITERAL
+ translationService.translate(
"productionCounting.productionBalance.report.panel.registerProductionTime", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField("registerProductionTime") ? translationService
.translate(QCADOO_VIEW_TRUE, locale) : translationService.translate(QCADOO_VIEW_FALSE,
locale)), FontUtils.getDejavuBold9Dark()));
rightPanel.addCell(new Phrase(TAB_SPACE_LITERAL
+ translationService.translate("productionCounting.productionBalance.report.panel.justOne", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField("justOne") ? translationService
.translate(QCADOO_VIEW_TRUE, locale) : translationService.translate(QCADOO_VIEW_FALSE, locale)),
FontUtils.getDejavuBold9Dark()));
rightPanel.addCell(new Phrase(TAB_SPACE_LITERAL
+ translationService.translate("productionCounting.productionBalance.report.panel.allowToClose", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField("allowToClose") ? translationService
.translate(QCADOO_VIEW_TRUE, locale) : translationService.translate(QCADOO_VIEW_FALSE, locale)),
FontUtils.getDejavuBold9Dark()));
rightPanel.addCell(new Phrase(TAB_SPACE_LITERAL
+ translationService.translate("productionCounting.productionBalance.report.panel.autoCloseOrder", locale)
+ " "
+ ((Boolean) productionCounting.getBelongsToField(FIELD_ORDER).getField("autoCloseOrder") ? translationService
.translate(QCADOO_VIEW_TRUE, locale) : translationService.translate(QCADOO_VIEW_FALSE, locale)),
FontUtils.getDejavuBold9Dark()));
return rightPanel;
}
private void addProductionRecord(final Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(translationService.translate("productionCounting.productionCounting.report.paragraph", locale)
+ " " + productionRecord.getStringField("number"), FontUtils.getDejavuBold19Dark()));
PdfPTable panelTable = pdfHelper.createPanelTable(2);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.recordType", locale),
- (Boolean) productionRecord.getField("lastRecord") ? translationService.translate(
+ (Boolean) productionRecord.getBooleanField("lastRecord") ? translationService.translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale) : translationService
.translate("productionCounting.productionCounting.report.panel.recordType.partial", locale), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if (productionRecord.getBelongsToField(FIELD_ORDER).getStringField(TYPE_OF_PRODUCTION_RECORDING).equals("02cumulated")) {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber")
+ " "
+ productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
.getStringField(FIELD_NAME), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, locale).format((Date) productionRecord
.getHasManyField("loggings").get(0).getField("dateAndTime")), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("machineTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale), NOT_AVAILABLE, null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
}
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getHasManyField("loggings").get(0).getStringField("worker"), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("laborTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
Entity technology = productionRecord.getBelongsToField(FIELD_ORDER).getBelongsToField("technology");
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityInProduct")) {
addInputProducts(document, productionRecord, technology, locale);
}
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityOutProduct")) {
addOutputProducts(document, productionRecord, technology, locale);
}
}
private void addInputProducts(final Document document, final Entity productionRecord, final Entity technology,
final Locale locale) throws DocumentException {
document.add(new Paragraph(translationService
.translate("productionCounting.productionCounting.report.paragraph2", locale), FontUtils.getDejavuBold11Dark()));
List<String> inputProductsTableHeader = new ArrayList<String>();
inputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.number", locale));
inputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.productionName", locale));
inputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.type", locale));
inputProductsTableHeader.add(translationService.translate(
"productionCounting.productionCounting.report.columnHeader.quantity", locale));
inputProductsTableHeader.add(translationService.translate("basic.product.unit.label", locale));
PdfPTable inputProductsTable = pdfHelper.createTableWithHeader(5, inputProductsTableHeader, false);
if (productionRecord.getHasManyField("recordOperationProductInComponents") != null) {
List<Entity> productsInList = new ArrayList<Entity>(
productionRecord.getHasManyField("recordOperationProductInComponents"));
Collections.sort(productsInList, new EntityProductInOutComparator());
for (Entity productIn : productsInList) {
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField(FIELD_PRODUCT).getStringField("number"),
FontUtils.getDejavuRegular9Dark()));
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField(FIELD_PRODUCT).getStringField(FIELD_NAME),
FontUtils.getDejavuRegular9Dark()));
String type = technologyService.getProductType(productIn.getBelongsToField(FIELD_PRODUCT), technology);
inputProductsTable.addCell(new Phrase(translationService.translate("basic.product.globalTypeOfMaterial.value."
+ type, locale), FontUtils.getDejavuRegular9Dark()));
inputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
if (productIn.getField(FIELD_USED_QUANTITY) == null) {
inputProductsTable.addCell(new Phrase(NOT_AVAILABLE, FontUtils.getDejavuRegular9Dark()));
} else {
inputProductsTable.addCell(new Phrase(numberService.format(productIn.getField(FIELD_USED_QUANTITY)),
FontUtils.getDejavuRegular9Dark()));
}
inputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
inputProductsTable.addCell(new Phrase(productIn.getBelongsToField(FIELD_PRODUCT).getStringField("unit"),
FontUtils.getDejavuRegular9Dark()));
}
}
document.add(inputProductsTable);
}
private void addOutputProducts(final Document document, final Entity productionRecord, final Entity technology,
final Locale locale) throws DocumentException {
document.add(new Paragraph(translationService
.translate("productionCounting.productionCounting.report.paragraph3", locale), FontUtils.getDejavuBold11Dark()));
List<String> outputProductsTableHeader = new ArrayList<String>();
outputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.number", locale));
outputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.productionName", locale));
outputProductsTableHeader.add(translationService.translate(
"productionCounting.productionBalance.report.columnHeader.type", locale));
outputProductsTableHeader.add(translationService.translate(
"productionCounting.productionCounting.report.columnHeader.quantity", locale));
outputProductsTableHeader.add(translationService.translate("basic.product.unit.label", locale));
PdfPTable outputProductsTable = pdfHelper.createTableWithHeader(5, outputProductsTableHeader, false);
if (productionRecord.getHasManyField("recordOperationProductOutComponents") != null) {
List<Entity> productsOutList = new ArrayList<Entity>(
productionRecord.getHasManyField("recordOperationProductOutComponents"));
Collections.sort(productsOutList, new EntityProductInOutComparator());
for (Entity productOut : productsOutList) {
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField(FIELD_PRODUCT).getStringField("number"),
FontUtils.getDejavuRegular9Dark()));
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField(FIELD_PRODUCT).getStringField(FIELD_NAME),
FontUtils.getDejavuRegular9Dark()));
String type = technologyService.getProductType(productOut.getBelongsToField(FIELD_PRODUCT), technology);
outputProductsTable.addCell(new Phrase(translationService.translate("basic.product.globalTypeOfMaterial.value."
+ type, locale), FontUtils.getDejavuRegular9Dark()));
outputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
if (productOut.getField(FIELD_USED_QUANTITY) == null) {
outputProductsTable.addCell(new Phrase(NOT_AVAILABLE, FontUtils.getDejavuRegular9Dark()));
} else {
outputProductsTable.addCell(new Phrase(numberService.format(productOut.getField(FIELD_USED_QUANTITY)),
FontUtils.getDejavuRegular9Dark()));
}
outputProductsTable.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
outputProductsTable.addCell(new Phrase(productOut.getBelongsToField(FIELD_PRODUCT).getStringField("unit"),
FontUtils.getDejavuRegular9Dark()));
}
}
document.add(outputProductsTable);
}
@Override
public String getReportTitle(final Locale locale) {
return translationService.translate("productionCounting.productionBalance.report.title", locale);
}
}
| true | true | private void addProductionRecord(final Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(translationService.translate("productionCounting.productionCounting.report.paragraph", locale)
+ " " + productionRecord.getStringField("number"), FontUtils.getDejavuBold19Dark()));
PdfPTable panelTable = pdfHelper.createPanelTable(2);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.recordType", locale),
(Boolean) productionRecord.getField("lastRecord") ? translationService.translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale) : translationService
.translate("productionCounting.productionCounting.report.panel.recordType.partial", locale), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if (productionRecord.getBelongsToField(FIELD_ORDER).getStringField(TYPE_OF_PRODUCTION_RECORDING).equals("02cumulated")) {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber")
+ " "
+ productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
.getStringField(FIELD_NAME), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, locale).format((Date) productionRecord
.getHasManyField("loggings").get(0).getField("dateAndTime")), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("machineTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale), NOT_AVAILABLE, null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
}
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getHasManyField("loggings").get(0).getStringField("worker"), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("laborTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
Entity technology = productionRecord.getBelongsToField(FIELD_ORDER).getBelongsToField("technology");
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityInProduct")) {
addInputProducts(document, productionRecord, technology, locale);
}
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityOutProduct")) {
addOutputProducts(document, productionRecord, technology, locale);
}
}
| private void addProductionRecord(final Document document, final Entity productionRecord, final Locale locale)
throws DocumentException {
document.add(new Paragraph(translationService.translate("productionCounting.productionCounting.report.paragraph", locale)
+ " " + productionRecord.getStringField("number"), FontUtils.getDejavuBold19Dark()));
PdfPTable panelTable = pdfHelper.createPanelTable(2);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.recordType", locale),
(Boolean) productionRecord.getBooleanField("lastRecord") ? translationService.translate(
"productionCounting.productionCounting.report.panel.recordType.final", locale) : translationService
.translate("productionCounting.productionCounting.report.panel.recordType.partial", locale), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if (productionRecord.getBelongsToField(FIELD_ORDER).getStringField(TYPE_OF_PRODUCTION_RECORDING).equals("02cumulated")) {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.operationAndLevel", locale),
productionRecord.getBelongsToField("orderOperationComponent").getStringField("nodeNumber")
+ " "
+ productionRecord.getBelongsToField("orderOperationComponent").getBelongsToField("operation")
.getStringField(FIELD_NAME), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.dateAndTime", locale),
new SimpleDateFormat(DateUtils.L_DATE_TIME_FORMAT, locale).format((Date) productionRecord
.getHasManyField("loggings").get(0).getField("dateAndTime")), null, FontUtils.getDejavuBold9Dark(),
FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("machineTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(panelTable, translationService.translate(
"productionCounting.productionCounting.report.panel.machineOperationTime", locale), NOT_AVAILABLE, null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
}
addTableCellAsTable(panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.worker", locale),
productionRecord.getHasManyField("loggings").get(0).getStringField("worker"), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerProductionTime")) {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
timeConverterService.convertTimeToString((Integer) productionRecord.getField("laborTime")), null,
FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
} else {
addTableCellAsTable(
panelTable,
translationService.translate("productionCounting.productionCounting.report.panel.laborOperationTime", locale),
NOT_AVAILABLE, null, FontUtils.getDejavuBold9Dark(), FontUtils.getDejavuBold9Dark(), null);
}
panelTable.setSpacingBefore(10);
document.add(panelTable);
Entity technology = productionRecord.getBelongsToField(FIELD_ORDER).getBelongsToField("technology");
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityInProduct")) {
addInputProducts(document, productionRecord, technology, locale);
}
if ((Boolean) productionRecord.getBelongsToField(FIELD_ORDER).getField("registerQuantityOutProduct")) {
addOutputProducts(document, productionRecord, technology, locale);
}
}
|
diff --git a/Common/pharabus/mods/aeperipheral/TileEntityAEPeripheral.java b/Common/pharabus/mods/aeperipheral/TileEntityAEPeripheral.java
index 154af01..e1a98c8 100644
--- a/Common/pharabus/mods/aeperipheral/TileEntityAEPeripheral.java
+++ b/Common/pharabus/mods/aeperipheral/TileEntityAEPeripheral.java
@@ -1,328 +1,328 @@
package pharabus.mods.aeperipheral;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import appeng.api.IAEItemStack;
import appeng.api.IItemList;
import appeng.api.Util;
import appeng.api.WorldCoord;
import appeng.api.events.GridTileLoadEvent;
import appeng.api.events.GridTileUnloadEvent;
import appeng.api.me.tiles.IGridMachine;
import appeng.api.me.tiles.IStorageAware;
import appeng.api.me.util.IGridInterface;
import appeng.api.me.util.IMEInventory;
import cpw.mods.fml.common.FMLLog;
import dan200.computer.api.IComputerAccess;
import dan200.computer.api.IPeripheral;
public class TileEntityAEPeripheral extends TileEntity implements IPeripheral,
IGridMachine, IStorageAware {
private boolean isValidFlag = true;
public boolean hasPower = false;
private IGridInterface myGrid;
public int gIdx = 0;
protected boolean isLoaded = false;
private Map<String,Alarm> targets = new HashMap<String,Alarm>();
@Override
public void validate() {
super.validate();
if (!isLoaded) {
if (AEPeripheralUtil.isClient()) {
aeperipheral.AEPeripheralGenericTick_client.TriggerInit(this);
} else {
aeperipheral.AEPeripheralGenericTick_server.TriggerInit(this);
}
}
}
@Override
public void invalidate() {
super.invalidate();
if (isLoaded) {
isLoaded = false;
terminate();
}
}
@Override
public String getType() {
return "AEPeripheral";
}
@Override
public String[] getMethodNames() {
return new String[] { "GetInventory", "GetCraftables", "Craft","AddAlert" };
}
@Override
public Object[] callMethod(IComputerAccess computer, int method,
Object[] arguments) throws Exception {
Map<String, String> ret = new HashMap<String, String>();
if (!hasPower)
return new Object[] { "No Power" };
if (myGrid == null)
return new Object[] { "No Contoller" };
if (myGrid != null) {
IGridInterface gi = this.getGrid();
IMEInventory ginv = null;
IItemList list = null;
switch (method) {
case 0:
ginv = gi.getCellArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
Long.toString(item.getStackSize()));
}
break;
case 1:
ginv = gi.getCraftableArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
item.getItemID() + ":" + item.getItemDamage());
}
break;
case 2:
if(arguments.length < 2)
{
throw new Exception("Not enough arguments");
}
if(!(arguments[0] instanceof String) || !(arguments[1] instanceof Double))
{
throw new Exception("bad arguments, expected numbers");
}
String[] item = arguments[0].toString().split(":");
int Id = Integer.parseInt(item[0]);
int damage = Integer.parseInt(item[1]);
int howMany = (int) Math.floor((Double) arguments[1]);
gi.craftingRequest(new ItemStack(Id, howMany, damage));
break;
case 3:
if(arguments.length < 4)
{
throw new Exception("Not enough arguments");
}
String alarmName = (String) arguments[0];
- String[] targetitem = arguments[0].toString().split(":");
+ String[] targetitem = arguments[1].toString().split(":");
int targetId = Integer.parseInt(targetitem[0]);
int targetDamage = Integer.parseInt(targetitem[1]);
int min = (int) Math.floor((Double) arguments[2]);
int max = (int) Math.floor((Double) arguments[3]);
IAEItemStack target = Util.createItemStack(new ItemStack(targetId,0,targetDamage));
Alarm alarm = new Alarm(alarmName,min,max,target,computer);
this.targets.remove(alarmName);
this.targets.put(alarmName,alarm);
break;
}
}
return new Object[] { ret };
}
@Override
public boolean canAttachToSide(int side) {
return true;
}
@Override
public void attach(IComputerAccess computer) {
// TODO Auto-generated method stub
}
@Override
public void detach(IComputerAccess computer) {
// TODO Auto-generated method stub
}
@Override
public WorldCoord getLocation() {
// TODO Auto-generated method stub
return new WorldCoord(xCoord, yCoord, zCoord);
}
@Override
public boolean isValid() {
// TODO Auto-generated method stub
return isValidFlag;
}
@Override
public void setPowerStatus(boolean _hasPower) {
FMLLog.log(Level.INFO,
"AEPeripheral setPowerStatus called _hasPower is" + _hasPower);
if (hasPower != _hasPower) {
hasPower = _hasPower;
markForUpdate();
}
}
@Override
public boolean isPowered() {
return hasPower;
}
@Override
public IGridInterface getGrid() {
FMLLog.log(Level.INFO, "AEPeripheral getGrid called my grid is"
+ myGrid.isValid());
return myGrid.isValid() ? myGrid : null;
}
@Override
public void setGrid(IGridInterface gi) {
FMLLog.log(Level.INFO, "AEPeripheral setGrid called");
if (gi != myGrid) {
myGrid = gi;
if (gi != null) {
gIdx = gi.getGridIndex();
} else {
gIdx = 0;
}
if (myGrid == null) {
setPowerStatus(false);
}
markForUpdate();
}
}
@Override
public World getWorld() {
return worldObj;
}
public void markForUpdate() {
if (AEPeripheralUtil.isClient()) {
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
} else {
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
@Override
public float getPowerDrainPerTick() {
return 1.0F;
}
public void init() {
if (isLoaded)
return;
isLoaded = true;
MinecraftForge.EVENT_BUS.post(new GridTileLoadEvent(this, worldObj,
getLocation()));
worldObj.updateAllLightTypes(xCoord, yCoord, zCoord);
}
protected void terminate() {
isLoaded = false;
setGrid(null);
MinecraftForge.EVENT_BUS.post(new GridTileUnloadEvent(this, worldObj,
getLocation()));
}
@Override
public void onNetworkInventoryChange(IItemList iss) {
FMLLog.log(Level.INFO, "AEPeripheral networkchanged called");
for(Alarm value : targets.values())
{
IAEItemStack out = iss.findItem(value.getTarget());
if(out != null)
{
long level = out.getStackSize();
if(value.getMin() == 0)
{
if(level >= value.getMax())
{
value.Fire(level);
}
}
else if(value.getMax() == 0)
{
if(level <= value.getMin())
{
value.Fire(level);
}
}
else
{
if(level >= value.getMin() && level <= value.getMax())
{
value.Fire(level);
}
}
}
}
}
private class Alarm
{
private IComputerAccess computer;
private int min;
private int max;
private IAEItemStack target;
private String alarmName;
protected Alarm(String alarmname,int min, int max,IAEItemStack target,IComputerAccess computer)
{
this.computer = computer;
this.min = min;
this.max = max;
this.target = target;
this.alarmName = alarmname;
}
protected void Fire(long level)
{
this.computer.queueEvent(this.alarmName, new Object[] {level});
}
public IAEItemStack getTarget()
{
return this.target;
}
public int getMin()
{
return this.min;
}
public int getMax()
{
return this.max;
}
}
}
| true | true | public Object[] callMethod(IComputerAccess computer, int method,
Object[] arguments) throws Exception {
Map<String, String> ret = new HashMap<String, String>();
if (!hasPower)
return new Object[] { "No Power" };
if (myGrid == null)
return new Object[] { "No Contoller" };
if (myGrid != null) {
IGridInterface gi = this.getGrid();
IMEInventory ginv = null;
IItemList list = null;
switch (method) {
case 0:
ginv = gi.getCellArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
Long.toString(item.getStackSize()));
}
break;
case 1:
ginv = gi.getCraftableArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
item.getItemID() + ":" + item.getItemDamage());
}
break;
case 2:
if(arguments.length < 2)
{
throw new Exception("Not enough arguments");
}
if(!(arguments[0] instanceof String) || !(arguments[1] instanceof Double))
{
throw new Exception("bad arguments, expected numbers");
}
String[] item = arguments[0].toString().split(":");
int Id = Integer.parseInt(item[0]);
int damage = Integer.parseInt(item[1]);
int howMany = (int) Math.floor((Double) arguments[1]);
gi.craftingRequest(new ItemStack(Id, howMany, damage));
break;
case 3:
if(arguments.length < 4)
{
throw new Exception("Not enough arguments");
}
String alarmName = (String) arguments[0];
String[] targetitem = arguments[0].toString().split(":");
int targetId = Integer.parseInt(targetitem[0]);
int targetDamage = Integer.parseInt(targetitem[1]);
int min = (int) Math.floor((Double) arguments[2]);
int max = (int) Math.floor((Double) arguments[3]);
IAEItemStack target = Util.createItemStack(new ItemStack(targetId,0,targetDamage));
Alarm alarm = new Alarm(alarmName,min,max,target,computer);
this.targets.remove(alarmName);
this.targets.put(alarmName,alarm);
break;
}
}
return new Object[] { ret };
}
| public Object[] callMethod(IComputerAccess computer, int method,
Object[] arguments) throws Exception {
Map<String, String> ret = new HashMap<String, String>();
if (!hasPower)
return new Object[] { "No Power" };
if (myGrid == null)
return new Object[] { "No Contoller" };
if (myGrid != null) {
IGridInterface gi = this.getGrid();
IMEInventory ginv = null;
IItemList list = null;
switch (method) {
case 0:
ginv = gi.getCellArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
Long.toString(item.getStackSize()));
}
break;
case 1:
ginv = gi.getCraftableArray();
list = ginv.getAvailableItems();
for (IAEItemStack item : list) {
ret.put(item.getItemStack().getDisplayName(),
item.getItemID() + ":" + item.getItemDamage());
}
break;
case 2:
if(arguments.length < 2)
{
throw new Exception("Not enough arguments");
}
if(!(arguments[0] instanceof String) || !(arguments[1] instanceof Double))
{
throw new Exception("bad arguments, expected numbers");
}
String[] item = arguments[0].toString().split(":");
int Id = Integer.parseInt(item[0]);
int damage = Integer.parseInt(item[1]);
int howMany = (int) Math.floor((Double) arguments[1]);
gi.craftingRequest(new ItemStack(Id, howMany, damage));
break;
case 3:
if(arguments.length < 4)
{
throw new Exception("Not enough arguments");
}
String alarmName = (String) arguments[0];
String[] targetitem = arguments[1].toString().split(":");
int targetId = Integer.parseInt(targetitem[0]);
int targetDamage = Integer.parseInt(targetitem[1]);
int min = (int) Math.floor((Double) arguments[2]);
int max = (int) Math.floor((Double) arguments[3]);
IAEItemStack target = Util.createItemStack(new ItemStack(targetId,0,targetDamage));
Alarm alarm = new Alarm(alarmName,min,max,target,computer);
this.targets.remove(alarmName);
this.targets.put(alarmName,alarm);
break;
}
}
return new Object[] { ret };
}
|
diff --git a/src/com/farpost/intellij/remotecall/notifier/SocketMessageNotifier.java b/src/com/farpost/intellij/remotecall/notifier/SocketMessageNotifier.java
index 7b3b8d8..046bfdc 100644
--- a/src/com/farpost/intellij/remotecall/notifier/SocketMessageNotifier.java
+++ b/src/com/farpost/intellij/remotecall/notifier/SocketMessageNotifier.java
@@ -1,94 +1,94 @@
package com.farpost.intellij.remotecall.notifier;
import com.farpost.intellij.remotecall.handler.MessageHandler;
import com.intellij.openapi.diagnostic.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class SocketMessageNotifier implements MessageNotifier {
private final Logger log = Logger.getInstance(getClass().getName());
private Collection<MessageHandler> messageHandlers = new HashSet<MessageHandler>();
private ServerSocket serverSocket;
private static final String CRLF = "\r\n";
public SocketMessageNotifier(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public void addMessageHandler(MessageHandler handler) {
messageHandlers.add(handler);
}
public void run() {
while (true) {
Socket clientSocket;
try {
clientSocket = serverSocket.accept();
if (!clientSocket.getInetAddress().getHostAddress().equals("127.0.0.1")) {
log.warn("Not allowed requests from " + clientSocket.getInetAddress().getHostAddress());
continue;
}
} catch (IOException e) {
log.error("Error while accepting", e);
continue;
}
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
String inputLine, requestString = "";
while ((inputLine = in.readLine()) != null && !inputLine.equals(CRLF) && !inputLine.equals("")) {
requestString += inputLine;
}
StringTokenizer tokenizer = new StringTokenizer(requestString);
String method = tokenizer.nextToken();
if (!method.equals("GET")) {
log.warn("Only GET requests allowed");
continue;
}
log.info("Received request " + requestString);
Map<String, String> parameters = getParametersFromUrl(tokenizer.nextToken());
String message = parameters.get("message") != null ? parameters.get("message") : "";
log.info("Received message " + message);
- handleMessage(requestString);
+ handleMessage(message);
} catch (IOException e) {
log.error("Error", e);
}
}
}
private Map<String, String> getParametersFromUrl(String url) {
String parametersString = url.substring(url.indexOf('?') + 1);
Map<String, String> parameters = new HashMap<String, String>();
StringTokenizer tokenizer = new StringTokenizer(parametersString, "&");
while (tokenizer.hasMoreElements()) {
String[] parametersPair = tokenizer.nextToken().split("=", 2);
if (parametersPair.length > 1) {
parameters.put(parametersPair[0], parametersPair[1]);
}
}
return parameters;
}
private void handleMessage(String message) {
for (MessageHandler handler : messageHandlers) {
handler.handleMessage(message);
}
}
}
| true | true | public void run() {
while (true) {
Socket clientSocket;
try {
clientSocket = serverSocket.accept();
if (!clientSocket.getInetAddress().getHostAddress().equals("127.0.0.1")) {
log.warn("Not allowed requests from " + clientSocket.getInetAddress().getHostAddress());
continue;
}
} catch (IOException e) {
log.error("Error while accepting", e);
continue;
}
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
String inputLine, requestString = "";
while ((inputLine = in.readLine()) != null && !inputLine.equals(CRLF) && !inputLine.equals("")) {
requestString += inputLine;
}
StringTokenizer tokenizer = new StringTokenizer(requestString);
String method = tokenizer.nextToken();
if (!method.equals("GET")) {
log.warn("Only GET requests allowed");
continue;
}
log.info("Received request " + requestString);
Map<String, String> parameters = getParametersFromUrl(tokenizer.nextToken());
String message = parameters.get("message") != null ? parameters.get("message") : "";
log.info("Received message " + message);
handleMessage(requestString);
} catch (IOException e) {
log.error("Error", e);
}
}
}
| public void run() {
while (true) {
Socket clientSocket;
try {
clientSocket = serverSocket.accept();
if (!clientSocket.getInetAddress().getHostAddress().equals("127.0.0.1")) {
log.warn("Not allowed requests from " + clientSocket.getInetAddress().getHostAddress());
continue;
}
} catch (IOException e) {
log.error("Error while accepting", e);
continue;
}
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream())
);
String inputLine, requestString = "";
while ((inputLine = in.readLine()) != null && !inputLine.equals(CRLF) && !inputLine.equals("")) {
requestString += inputLine;
}
StringTokenizer tokenizer = new StringTokenizer(requestString);
String method = tokenizer.nextToken();
if (!method.equals("GET")) {
log.warn("Only GET requests allowed");
continue;
}
log.info("Received request " + requestString);
Map<String, String> parameters = getParametersFromUrl(tokenizer.nextToken());
String message = parameters.get("message") != null ? parameters.get("message") : "";
log.info("Received message " + message);
handleMessage(message);
} catch (IOException e) {
log.error("Error", e);
}
}
}
|
diff --git a/java/marytts/modules/phonemiser/Syllabifier.java b/java/marytts/modules/phonemiser/Syllabifier.java
index f75479f4f..0238ad7af 100755
--- a/java/marytts/modules/phonemiser/Syllabifier.java
+++ b/java/marytts/modules/phonemiser/Syllabifier.java
@@ -1,347 +1,348 @@
/**
* Copyright 2000-2006 DFKI GmbH.
* All Rights Reserved. Use is subject to license terms.
*
* This file is part of MARY TTS.
*
* MARY TTS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 marytts.modules.phonemiser;
import java.util.LinkedList;
import java.util.ListIterator;
public class Syllabifier
{
protected AllophoneSet allophoneSet;
public Syllabifier(AllophoneSet allophoneSet)
{
this.allophoneSet = allophoneSet;
}
/**
* Syllabify a phonetic string, marking syllable boundaries with dash characters in the output.
* If the input marks stressed vowels with a suffix "1", these marks are removed, and
* single quotes (') are inserted at the beginning of the corresponding syllable.
* @param phoneString the phone string to syllabify.
* @return a syllabified phone string, with space characters inserted between individual phone symbols
*/
public String syllabify(String phoneString)
{
LinkedList<String> phoneList = splitIntoAllophones(phoneString);
syllabify(phoneList);
StringBuilder sb = new StringBuilder();
for (String p : phoneList) {
if (sb.length() > 0) sb.append(" ");
sb.append(p);
}
return sb.toString();
}
/**
* Syllabify a linked list of phones. This is an implementation of the
* syllabification rules by J¨rgen Trouvain.
* @return a linked list of phone strings with inserted "-" strings at
* syllable boundaries.
*/
public void syllabify(LinkedList<String> phoneList)
{
// Regel(1a)
// Jede Grenze einer morphologischen Wurzel stellt eine
// Silbengrenze dar.
// Regel(1b)
// Jede Grenze eines Präfixes stellt eine Silbengrenze dar.
// Dort, wo ein Fugensuffix bzw ein Suffix beginnt,
// gibt es keine morphologische Silbengrenze.
// Bsp: Lebens-gefaehrte und nicht Leben-s-gefaehrte
// Bsp: Mei-nung und nicht Mein-ung
// Note: We don't have morpheme boundaries! (=> so ignore rule 1)
// 2.: finde nicht-morphologische Silbengrenzen
// teile Woerter, die eine morphologisch bedingte Silbengrenze haben
// in ihre Silbenteile, um dort spaeter nach weiteren,
// nicht-morphologisch bedingten, Silbengrenzen zu suchen
// Only one such component as long as we don't have morpheme boundaries
if (phoneList == null) return;
ListIterator<String> it = phoneList.listIterator(0);
if (!it.hasNext()) return;
Allophone previous = getAllophone(it.next());
boolean previousIsVowel = (previous != null && previous.sonority() >= 4);
while (it.hasNext()) {
Allophone next = getAllophone(it.next());
boolean nextIsVowel = (next != null && next.sonority() >= 4);
// Regel(5)
// Wenn zwischen zwei Vokalen keine weiteren Phone sind,
// dann setze die Silbengrenze vor den zweiten Vokal.
if (previousIsVowel && nextIsVowel &&
!next.name().equals("6")) {
// Insert a syllable boundary between the two.
it.previous(); // one step back
it.add("-"); // insert syllable boundary
it.next(); // and forward again
}
previousIsVowel = nextIsVowel;
}
// Regel(4)
// Suche das "Tal" (kleinster Level < 4) zwischen zwei benachbarten
// Vokalen, sofern die Vokale nicht durch eine morphologisch bedingte
// Grenze getrennt werden.
it = phoneList.listIterator(0);
int minSonority = 7; // one higher than possible maximum.
int minIndex = -1; // position of the sonority minimum
while (it.hasNext()) {
String s = it.next();
if (s.equals("-")) {
// Forget about all valleys:
minSonority = 7;
minIndex = -1;
} else {
Allophone ph = getAllophone(s);
if (ph != null && ph.sonority() < minSonority) {
minSonority = ph.sonority();
minIndex = it.previousIndex();
} else if (ph != null && ph.sonority() >= 4) {
// Found a vowel. Now, if there is a (non-initial) sonority
// valley before this vowel, insert a valley marker:
if (minIndex > 0) {
int steps = 0;
while (it.nextIndex() > minIndex) {
steps++;
it.previous();
}
it.add(".");
while (steps > 0) {
it.next();
steps--;
}
}
minSonority = 7;
minIndex = -1;
}
}
}
// Regel(6a)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) nur *ein* Konsonant des
// Levels 2 oder 3, so ersetze die Talmarkierung durch eine
// ambisilbische Silbengrenze (Symbol "_").
// halbformal:
// ([v5]).([k2,3])([v4,5,6])
// --> ([v5])_([k2,3])([v4,5,6])
// Regel(6b)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) mehr als ein Konsonant
// (Levels 1,2 oder 3), und folgt gleichzeitig dem 5er-Vokal eine
// Talmarkierung, so versetze die "Talmarkierung" ein Phonem weiter und
// ersetze sie durch eine normale Silbengrenze.
// halbformal:
// ([v5]).([k1,2,3])([k1,2,3]+)([v4,5,6])
// --> ([v5]).([k1,2,3])-([k1,2,3]+)([v4,5,6])
// Regel(6c)
// In allen anderen Faellen ersetze die "Talmarkierung" mit einer
// normalen Silbengrenze.
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
if (s.equals(".")) {
it.previous(); // skip . backwards
Allophone ph = getAllophone(it.previous());
it.next(); it.next(); // skip ph and . forwards
if (ph != null && ph.sonority() == 5) {
// The phone just after the marker:
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// Now the big question: another consonant or not?
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// (6b) remove ., go one further, insert -
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
it.remove(); // remove the .
it.next(); // skip one ph
it.add("-");
} else {
// (6a) replace . with _
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
// only use minuses, because underscores denote also pauses
//it.set("_"); // replace . with _
it.set("-"); // replace . with -
}
} else {
// unlikely case: no consonant after a 5
+ it.previous(); it.previous();
it.set("-");
}
} else {
// (6c) simply replace . with -
it.set("-");
}
}
}
// Regel(7)
// Folgt einem Phonem /N/, vor dem unmittelbar eine ambisilbische
// Silbengrenze steht, ein Vollvokal (Level 5 oder 6), so verschiebe
// die Silbengrenze um ein Phonem (naemlich hinter das /N/) und
// ersetze es durch eine normale Silbengrenze.
// halbformal:
// _N([v5,6])
// --> N-([v5,6])
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
// only use minuses, because underscores denote also pauses
//if (s.equals("_")) {
if (s.equals("-")) {
Allophone ph = getAllophone(it.next());
if (ph != null && ph.name().equals("N")) {
ph = getAllophone(it.next());
if (ph != null && ph.sonority() >= 5) {
// (7) remove _, put a - after the N
// skip vowel, N, and _ backwards:
it.previous(); it.previous(); it.previous();
it.remove(); // remove _
it.next(); // skip N forwards
it.add("-"); // insert -
} // else, just leave it
}
}
}
correctStressSymbol(phoneList);
}
/**
* For those syllables containing a "1" character, remove that "1"
* character and add a stress marker ' at the beginning of the syllable.
*/
protected void correctStressSymbol(LinkedList<String> phoneList)
{
boolean stressFound = false;
ListIterator<String> it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
if (s.endsWith("1")) {
it.set(s.substring(0, s.length()-1)); // delete "1"
if (!stressFound) {
// Only add a stress marker for first occurrence of "1":
// Search backwards for syllable boundary or beginning of word:
int steps = 0;
while (it.hasPrevious()) {
steps++;
String t = it.previous();
if (t.equals("-") || t.equals("_")) { // syllable boundary
it.next();
steps--;
break;
}
}
it.add("'");
while (steps > 0) {
it.next();
steps--;
}
stressFound = true;
}
}
}
// No stressed vowel in word?
if (!stressFound) {
// Stress first non-schwa syllable
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
Allophone ph = allophoneSet.getAllophone(s);
if (ph != null && ph.sonority() >= 5) { // non-schwa vowel
// Search backwards for syllable boundary or beginning of word:
int steps = 0;
while (it.hasPrevious()) {
steps++;
String t = it.previous();
if (t.equals("-") || t.equals("_")) { // syllable boundary
it.next();
steps--;
break;
}
}
it.add("'");
while (steps > 0) {
it.next();
steps--;
}
break; // OK, that's it.
}
}
}
}
/**
* Convert a phone string into a list of string representations of
* individual phones. The input can use the suffix "1" to indicate
* stressed vowels.
* @param phoneString the phone string to split
* @return a linked list of strings, each string representing an individual phone
*/
protected LinkedList<String> splitIntoAllophones(String phoneString)
{
LinkedList<String> phoneList = new LinkedList<String>();
for (int i=0; i<phoneString.length(); i++) {
// Try to cut off individual segments,
// starting with the longest prefixes,
// and allowing for a suffix "1" marking stress:
String name = null;
for (int j=3; j>=1; j--) {
if (i+j <= phoneString.length()) {
String candidate = phoneString.substring(i, i+j);
if (getAllophone(candidate) != null) { // found
name = candidate;
i+=j-1; // so that the next i++ goes beyond current phone
break;
}
}
}
if (name != null) {
phoneList.add(name);
}
}
return phoneList;
}
/**
* Get the Allophone object named phone; if phone ends with "1",
* discard the "1" and use the rest of the string as the phone symbol.
*/
protected Allophone getAllophone(String phone)
{
if (phone.endsWith("1"))
return allophoneSet.getAllophone(phone.substring(0,phone.length()-1));
else
return allophoneSet.getAllophone(phone);
}
}
| true | true | public void syllabify(LinkedList<String> phoneList)
{
// Regel(1a)
// Jede Grenze einer morphologischen Wurzel stellt eine
// Silbengrenze dar.
// Regel(1b)
// Jede Grenze eines Präfixes stellt eine Silbengrenze dar.
// Dort, wo ein Fugensuffix bzw ein Suffix beginnt,
// gibt es keine morphologische Silbengrenze.
// Bsp: Lebens-gefaehrte und nicht Leben-s-gefaehrte
// Bsp: Mei-nung und nicht Mein-ung
// Note: We don't have morpheme boundaries! (=> so ignore rule 1)
// 2.: finde nicht-morphologische Silbengrenzen
// teile Woerter, die eine morphologisch bedingte Silbengrenze haben
// in ihre Silbenteile, um dort spaeter nach weiteren,
// nicht-morphologisch bedingten, Silbengrenzen zu suchen
// Only one such component as long as we don't have morpheme boundaries
if (phoneList == null) return;
ListIterator<String> it = phoneList.listIterator(0);
if (!it.hasNext()) return;
Allophone previous = getAllophone(it.next());
boolean previousIsVowel = (previous != null && previous.sonority() >= 4);
while (it.hasNext()) {
Allophone next = getAllophone(it.next());
boolean nextIsVowel = (next != null && next.sonority() >= 4);
// Regel(5)
// Wenn zwischen zwei Vokalen keine weiteren Phone sind,
// dann setze die Silbengrenze vor den zweiten Vokal.
if (previousIsVowel && nextIsVowel &&
!next.name().equals("6")) {
// Insert a syllable boundary between the two.
it.previous(); // one step back
it.add("-"); // insert syllable boundary
it.next(); // and forward again
}
previousIsVowel = nextIsVowel;
}
// Regel(4)
// Suche das "Tal" (kleinster Level < 4) zwischen zwei benachbarten
// Vokalen, sofern die Vokale nicht durch eine morphologisch bedingte
// Grenze getrennt werden.
it = phoneList.listIterator(0);
int minSonority = 7; // one higher than possible maximum.
int minIndex = -1; // position of the sonority minimum
while (it.hasNext()) {
String s = it.next();
if (s.equals("-")) {
// Forget about all valleys:
minSonority = 7;
minIndex = -1;
} else {
Allophone ph = getAllophone(s);
if (ph != null && ph.sonority() < minSonority) {
minSonority = ph.sonority();
minIndex = it.previousIndex();
} else if (ph != null && ph.sonority() >= 4) {
// Found a vowel. Now, if there is a (non-initial) sonority
// valley before this vowel, insert a valley marker:
if (minIndex > 0) {
int steps = 0;
while (it.nextIndex() > minIndex) {
steps++;
it.previous();
}
it.add(".");
while (steps > 0) {
it.next();
steps--;
}
}
minSonority = 7;
minIndex = -1;
}
}
}
// Regel(6a)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) nur *ein* Konsonant des
// Levels 2 oder 3, so ersetze die Talmarkierung durch eine
// ambisilbische Silbengrenze (Symbol "_").
// halbformal:
// ([v5]).([k2,3])([v4,5,6])
// --> ([v5])_([k2,3])([v4,5,6])
// Regel(6b)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) mehr als ein Konsonant
// (Levels 1,2 oder 3), und folgt gleichzeitig dem 5er-Vokal eine
// Talmarkierung, so versetze die "Talmarkierung" ein Phonem weiter und
// ersetze sie durch eine normale Silbengrenze.
// halbformal:
// ([v5]).([k1,2,3])([k1,2,3]+)([v4,5,6])
// --> ([v5]).([k1,2,3])-([k1,2,3]+)([v4,5,6])
// Regel(6c)
// In allen anderen Faellen ersetze die "Talmarkierung" mit einer
// normalen Silbengrenze.
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
if (s.equals(".")) {
it.previous(); // skip . backwards
Allophone ph = getAllophone(it.previous());
it.next(); it.next(); // skip ph and . forwards
if (ph != null && ph.sonority() == 5) {
// The phone just after the marker:
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// Now the big question: another consonant or not?
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// (6b) remove ., go one further, insert -
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
it.remove(); // remove the .
it.next(); // skip one ph
it.add("-");
} else {
// (6a) replace . with _
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
// only use minuses, because underscores denote also pauses
//it.set("_"); // replace . with _
it.set("-"); // replace . with -
}
} else {
// unlikely case: no consonant after a 5
it.set("-");
}
} else {
// (6c) simply replace . with -
it.set("-");
}
}
}
// Regel(7)
// Folgt einem Phonem /N/, vor dem unmittelbar eine ambisilbische
// Silbengrenze steht, ein Vollvokal (Level 5 oder 6), so verschiebe
// die Silbengrenze um ein Phonem (naemlich hinter das /N/) und
// ersetze es durch eine normale Silbengrenze.
// halbformal:
// _N([v5,6])
// --> N-([v5,6])
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
// only use minuses, because underscores denote also pauses
//if (s.equals("_")) {
if (s.equals("-")) {
Allophone ph = getAllophone(it.next());
if (ph != null && ph.name().equals("N")) {
ph = getAllophone(it.next());
if (ph != null && ph.sonority() >= 5) {
// (7) remove _, put a - after the N
// skip vowel, N, and _ backwards:
it.previous(); it.previous(); it.previous();
it.remove(); // remove _
it.next(); // skip N forwards
it.add("-"); // insert -
} // else, just leave it
}
}
}
correctStressSymbol(phoneList);
}
| public void syllabify(LinkedList<String> phoneList)
{
// Regel(1a)
// Jede Grenze einer morphologischen Wurzel stellt eine
// Silbengrenze dar.
// Regel(1b)
// Jede Grenze eines Präfixes stellt eine Silbengrenze dar.
// Dort, wo ein Fugensuffix bzw ein Suffix beginnt,
// gibt es keine morphologische Silbengrenze.
// Bsp: Lebens-gefaehrte und nicht Leben-s-gefaehrte
// Bsp: Mei-nung und nicht Mein-ung
// Note: We don't have morpheme boundaries! (=> so ignore rule 1)
// 2.: finde nicht-morphologische Silbengrenzen
// teile Woerter, die eine morphologisch bedingte Silbengrenze haben
// in ihre Silbenteile, um dort spaeter nach weiteren,
// nicht-morphologisch bedingten, Silbengrenzen zu suchen
// Only one such component as long as we don't have morpheme boundaries
if (phoneList == null) return;
ListIterator<String> it = phoneList.listIterator(0);
if (!it.hasNext()) return;
Allophone previous = getAllophone(it.next());
boolean previousIsVowel = (previous != null && previous.sonority() >= 4);
while (it.hasNext()) {
Allophone next = getAllophone(it.next());
boolean nextIsVowel = (next != null && next.sonority() >= 4);
// Regel(5)
// Wenn zwischen zwei Vokalen keine weiteren Phone sind,
// dann setze die Silbengrenze vor den zweiten Vokal.
if (previousIsVowel && nextIsVowel &&
!next.name().equals("6")) {
// Insert a syllable boundary between the two.
it.previous(); // one step back
it.add("-"); // insert syllable boundary
it.next(); // and forward again
}
previousIsVowel = nextIsVowel;
}
// Regel(4)
// Suche das "Tal" (kleinster Level < 4) zwischen zwei benachbarten
// Vokalen, sofern die Vokale nicht durch eine morphologisch bedingte
// Grenze getrennt werden.
it = phoneList.listIterator(0);
int minSonority = 7; // one higher than possible maximum.
int minIndex = -1; // position of the sonority minimum
while (it.hasNext()) {
String s = it.next();
if (s.equals("-")) {
// Forget about all valleys:
minSonority = 7;
minIndex = -1;
} else {
Allophone ph = getAllophone(s);
if (ph != null && ph.sonority() < minSonority) {
minSonority = ph.sonority();
minIndex = it.previousIndex();
} else if (ph != null && ph.sonority() >= 4) {
// Found a vowel. Now, if there is a (non-initial) sonority
// valley before this vowel, insert a valley marker:
if (minIndex > 0) {
int steps = 0;
while (it.nextIndex() > minIndex) {
steps++;
it.previous();
}
it.add(".");
while (steps > 0) {
it.next();
steps--;
}
}
minSonority = 7;
minIndex = -1;
}
}
}
// Regel(6a)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) nur *ein* Konsonant des
// Levels 2 oder 3, so ersetze die Talmarkierung durch eine
// ambisilbische Silbengrenze (Symbol "_").
// halbformal:
// ([v5]).([k2,3])([v4,5,6])
// --> ([v5])_([k2,3])([v4,5,6])
// Regel(6b)
// Steht zwischen einem ungespannten Vokal (Level 5) und dem
// darauffolgenden Vokal (Level 4, 5 oder 6) mehr als ein Konsonant
// (Levels 1,2 oder 3), und folgt gleichzeitig dem 5er-Vokal eine
// Talmarkierung, so versetze die "Talmarkierung" ein Phonem weiter und
// ersetze sie durch eine normale Silbengrenze.
// halbformal:
// ([v5]).([k1,2,3])([k1,2,3]+)([v4,5,6])
// --> ([v5]).([k1,2,3])-([k1,2,3]+)([v4,5,6])
// Regel(6c)
// In allen anderen Faellen ersetze die "Talmarkierung" mit einer
// normalen Silbengrenze.
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
if (s.equals(".")) {
it.previous(); // skip . backwards
Allophone ph = getAllophone(it.previous());
it.next(); it.next(); // skip ph and . forwards
if (ph != null && ph.sonority() == 5) {
// The phone just after the marker:
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// Now the big question: another consonant or not?
ph = getAllophone(it.next());
if (ph != null && ph.sonority() <= 3) {
// (6b) remove ., go one further, insert -
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
it.remove(); // remove the .
it.next(); // skip one ph
it.add("-");
} else {
// (6a) replace . with _
// two ph back, and the .:
it.previous(); it.previous(); it.previous();
// only use minuses, because underscores denote also pauses
//it.set("_"); // replace . with _
it.set("-"); // replace . with -
}
} else {
// unlikely case: no consonant after a 5
it.previous(); it.previous();
it.set("-");
}
} else {
// (6c) simply replace . with -
it.set("-");
}
}
}
// Regel(7)
// Folgt einem Phonem /N/, vor dem unmittelbar eine ambisilbische
// Silbengrenze steht, ein Vollvokal (Level 5 oder 6), so verschiebe
// die Silbengrenze um ein Phonem (naemlich hinter das /N/) und
// ersetze es durch eine normale Silbengrenze.
// halbformal:
// _N([v5,6])
// --> N-([v5,6])
it = phoneList.listIterator(0);
while (it.hasNext()) {
String s = it.next();
// only use minuses, because underscores denote also pauses
//if (s.equals("_")) {
if (s.equals("-")) {
Allophone ph = getAllophone(it.next());
if (ph != null && ph.name().equals("N")) {
ph = getAllophone(it.next());
if (ph != null && ph.sonority() >= 5) {
// (7) remove _, put a - after the N
// skip vowel, N, and _ backwards:
it.previous(); it.previous(); it.previous();
it.remove(); // remove _
it.next(); // skip N forwards
it.add("-"); // insert -
} // else, just leave it
}
}
}
correctStressSymbol(phoneList);
}
|
diff --git a/src/edu/kit/asa/alloy2relsmt/smt/RelTheory.java b/src/edu/kit/asa/alloy2relsmt/smt/RelTheory.java
index 8b5f6fc..498ec30 100644
--- a/src/edu/kit/asa/alloy2relsmt/smt/RelTheory.java
+++ b/src/edu/kit/asa/alloy2relsmt/smt/RelTheory.java
@@ -1,1072 +1,1072 @@
package edu.kit.asa.alloy2relsmt.smt;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import edu.kit.asa.alloy2relsmt.util.Util;
/**
* Implements the relational theory for SMT. Includes axioms, declarations and lemmas
* @author Jonny
*
*/
public final class RelTheory {
private SMTFile file;
public RelTheory (SMTFile target){
file = target;
}
/** adds a declaration and theory for the converter function
* @param arity arity of the expression
* @throws ModelException
*/
public void declareA2r(int ar) throws ModelException {
// declare prerequisite sorts and functions
declareAtom();
declareRel(ar);
declareIn(ar);
// prepare declaration
String[] params = new String[ar];
for(int i = 0; i < ar; i++){
params[i] = "Atom";
}
// declaration
String name = "a2r_" + ar;
if(file.addFunction("Rel" + ar, name, params)){
// axiom
Term xInX, inImpliesEqual;
TermVar[] x = makeTuple(ar, "x"),
y = makeTuple(ar, "y");
xInX = Term.reverseIn(Term.call(name, x), x);
inImpliesEqual = Term.reverseIn(Term.call(name, x), y).implies(TermBinOp.equals(x, y));
Term axiom = Term.forall("Atom", x, xInX.and(Term.forall("Atom", y, inImpliesEqual)));
axiom.setComment("axiom for the conversion function Atom -> Relation");
file.addAxiom(axiom);
}
}
/** adds declaration and theory for Atom */
public void declareAtom() {
file.addSort("(declare-sort Atom)");
}
public void declareCardinality(int ar) throws ModelException {
declareRel(ar);
declareFinite();
declareOrd();
String name = "card_" + ar;
String relar = "Rel" + ar;
Term one = Term.call("1");
Term zero = Term.call("0");
TermVar[] a = makeTuple(ar, "a");
if (file.addFunction("Int", name, relar)) {
TermVar R = TermVar.var(relar, "R");
Term cardR = Term.call(name, R);
Term finR = Term.call("finite", R);
Term ordA = Term.call("ord", Util.reverse(Util.concat(a, R)));
Term validCard = cardR.gte(ordA).and(ordA.gte(one));
// ∀r: Reln , a1:n : Atom | (finite n (r) ∧ inn (a1:n , r)) ⇒ 1 ≤ ordn (r, a1:n ) ≤ card n (r)
{
Term guard = finR.and(Term.reverseIn(R, a));
Term axiom = guard.implies(validCard).forall(Util.concat(a, R));
axiom.setComment("axiom about finite Relations having a card > ord > 1");
file.addAxiom(axiom);
}
// ∀r: Reln , i: int | (finite n (r) ∧ 1 ≤ i ≤ card n (r))
// ⇒ ∃a1:n : Atom | inn (a1:n , r) ∧ ordn (r, a1:n ) = i
{
TermVar i = TermVar.var("Int", "i");
Term guard = finR.and(validCard);
Term axiom = guard.implies(Term.reverseIn(R, a).and(ordA.equal(i)).exists(i)).forall(R, i).forall(a);
axiom.setComment("axiom about finite Relations having atoms for certain numbers in ord");
file.addAxiom(axiom);
}
{
// lemma about a2r_1 having card_1
Term call = Term.call("a2r_" + ar, a);
Term lemma = Term.call(name, call).equal(one).forall(a);
lemma.setComment("lemma about a2r_x having card_x");
file.addLemma(lemma);
}
{
// lemma about some having card_1 > 0
Term call = Term.call("some_" + ar, R);
Term lemma = call.implies(Term.call(name, R).gt(zero)).forall(R);
lemma.setComment("lemma about some_x having card_x > 0");
file.addLemma(lemma);
}
}
}
public void declareDifference(int ar) throws ModelException {
declareRel(ar);
String relar = "Rel"+ar;
String name = "diff_" + ar;
if(file.addFunction(relar, name, relar, relar))
{
// add axiom
List<TermVar> argList = new LinkedList<TermVar>(); // this is a list of all quantified variables in the forall expression
TermVar A, B; // these are the left and right arg in "(diff_x A B)"
A = TermVar.var(relar, "A");
B = TermVar.var(relar, "B");
argList.add(A);
argList.add(B);
TermVar[] aTuple = makeTuple(ar, "a"); // this is a "tuple". it consists of one atom per rank
argList.addAll(Arrays.asList(aTuple)); // we will also quantify over those
Term somethingIsInTheCallToDiff = Term.in(Arrays.asList(aTuple), Term.call(name, A, B));
Term inAandNotB = Term.in(Arrays.asList(aTuple), A).and(Term.in(Arrays.asList(aTuple), B).not());
Term axiom = somethingIsInTheCallToDiff.iff(inAandNotB).forall(argList);
file.addAxiom(axiom);
}
}
/** adds a declaration and theory for disjoint
* @param arity arity of the expression
* @throws ModelException
*/
public void declareDisjoint(int ar) throws ModelException {
declareAtom();
declareRel(ar);
String relAr = "Rel" + ar;
if( file.addFunction("Bool", "disjoint_" +ar, relAr, relAr) )
{
// forall a in A, b in B | not a in B.
// or maybe: forall a in A, b in B | not a in B and not b in A...?
TermVar A, B;
TermVar[] a = makeTuple(ar, "a");
A = TermVar.var(relAr, "A");
B = TermVar.var(relAr, "B");
Term aInB = Term.reverseIn(B, a);
Term aInA = Term.reverseIn(A, a);
Term exclusive = aInA.and(aInB).not(); // aInA.implies(aInB.not());
Term axiom = Term.call("disjoint_" + ar, A, B).iff(exclusive.forall(a)).forall(A, B);
axiom.comment = Term.call("disjoint_" + ar, A, B).iff(aInA.implies(aInB.not()).forall(a)).forall(A, B).toString() + "; alternative";
file.addAxiom(axiom); // add this axiom to the list of assertions
}
}
/** Declares the binary domain restriction operator <:. The resulting relation (S <: R) contains
* all tuples of R that start with an element in S
* @param rar arity of the right-hand parameter
* @throws ModelException
* @rem left-hand arity is required to be 1 (type:set)
*/
public void declareDomainRestriction(int rar) throws ModelException {
declareRel(1);
declareRel(rar);
String relar = "Rel"+rar;
if(file.addFunction(relar, "domRestr_" + rar, "Rel1", relar))
{
// for all (a1 a2) in R and b in S, ((a1 a2) in (S <: R)) => b = a1
TermVar[] a = makeTuple(rar, "a");
TermVar b = TermVar.var("Atom", "b");
TermVar R = TermVar.var(relar, "R");
TermVar S = TermVar.var("Rel1", "S");
Term guard = Term.reverseIn(R, a).and(Term.reverseIn(S, b)).and(Term.reverseIn(Term.call("domRestr_" + rar, S, R), a));
Term axiom = guard.implies(a[0].equal(b)).forall(R, S, b).forall(a);
axiom.setComment("Axiom for domain restriction of arity " + rar);
file.addAxiom(axiom);
}
}
private void declareFinite() throws ModelException {
declareRel(1);
file.addFunction("Bool", "finite", "Rel1");
}
private void declareFirst(String suffix) throws ModelException {
// implementing "first"
declareA2r(1);
declareOrd();
String name = "first"+suffix;
// firstS = sin 1 (ordInv 1 (N [S], 1))
if (file.addFunction("Rel1",name)) {
Term first = Term.call(name);
TermVar N = TermVar.var(suffix); // not actually a variable but a constant
TermVar one = TermVar.var("Int", "1"); // not a variable but a constant
Term ordInv = Term.call("at", N, one);
Term a2r = Term.call("a2r_1", ordInv);
Term axiom = first.equal(a2r);
axiom.setComment("axiom for " + name);
file.addAxiom(axiom);
}
}
private void declareI2a() throws ModelException {
declareInt();
Term N = Term.call("N_Int");
String namei2a = "i2a";
String namea2i = "a2i";
if (file.addFunction("Atom", namei2a, "Int")) {
TermVar a = TermVar.var("Atom", "a");
Term guard = Term.reverseIn(N, a);
// i2a(a2i(a))
Term thereAndBack = Term.call(namei2a, Term.call(namea2i, a));
// ∀a: Atom | in1 (a, N [Int]) ⇒ i2a(a2i(a)) = a
Term axiom = guard.implies(thereAndBack.equal(a)).forall(a);
file.addAxiom(axiom);
}
if (file.addFunction("Int", namea2i, "Atom")) {
TermVar i = TermVar.var("Int", "i");
// in1 (i2a(i), N [Int])
Term inN = Term.call("in_1", Term.call(namei2a, i), N);
// a2i(i2a(i))
Term thereAndBack = Term.call(namea2i, Term.call(namei2a, i));
// ∀i: int | in1 (i2a(i), N [Int]) ∧ a2i(i2a(i)) = i
Term axiom = inN.implies(thereAndBack.equal(i)).forall(i);
axiom.setComment("axiom for i2a and a2i");
file.addAxiom(axiom);
}
}
public void declareIdentity() throws ModelException {
declareRel(2);
if(file.addFunction("Rel"+2, "iden"))
{
TermVar a0 = TermVar.var("Atom", "a0");
Term axiom = Term.reverseIn(Term.call("iden"), a0, a0);
file.addAxiom(axiom.forall(a0));
}
}
/** adds a declaration for in (no axiom)
* @param arity arity of the expression
* @throws ModelException couldn't declare this add this function because of "addFunction"
*/
public void declareIn(int ar) {
declareAtom();
declareRel(ar);
String[] params = new String[ar + 1];
for(int i = 0; i < ar; i++)
params[i] = "Atom";
params[ar] = "Rel" + ar;
file.addFunction("Bool", "in_" + ar, params);
// axiom omitted: "in" does not have an axiom (uninterpreted)
}
private void declareInt() {
file.addFunction("Rel1", "N_Int");
}
public void declareIntersection(int ar) throws ModelException {
declareRel(ar);
String relar = "Rel"+ar;
if(file.addFunction(relar, "inter_" + ar, relar, relar))
{
TermVar[] a = makeTuple(ar, "a");
TermVar R = TermVar.var(relar, "R");
TermVar S = TermVar.var(relar, "S");
Term tInIntersec = Term.reverseIn(Term.call("inter_" + ar, R, S), a);
Term meaning = Term.reverseIn(R, a).or(Term.reverseIn(S, a));
Term axiom = tInIntersec.implies(meaning).forall(R, S).forall(a);
axiom.setComment("axiom for intersection " + ar);
file.addAxiom(axiom);
}
}
public void declareJoin(int lar, int rar) throws ModelException {
if(lar < 1 || rar < 1)
throw new ModelException("The join is not defined for arguments of arity 0.");
if(lar + rar < 3)
throw new ModelException("The dot-join is not defined for two arguments of arity 1.");
declareAtom(); // we work with atoms in this axiom
declareRel(lar); // declare left relation
declareRel(rar); // declare right relation
int resultArity = rar + lar - 2; // this is the arity of the resulting relation
declareRel(resultArity); // declare result relation
declareSubset(rar); // declare subset
declareIn(rar); // declare the in-function for the right hand argument
declareIn(lar); // declare the in-function for the right hand argument
declareIn(resultArity); // declare the in-function for the result
String leftRelar = "Rel"+lar; // shorthand for Rel+lar
String rightRelar = "Rel"+rar; // shorthand for Rel+lar
String name = "join_" + lar + "x" + rar; // this function name
if(file.addFunction("Rel"+resultArity, name, leftRelar, rightRelar))
{
// add axiom
/* For the expression (join_1x2 A B) this axiom should read (infix):
* \forall A Rel1, B Rel2, y Atom| (y \elem join_1x2)
* iff [(\exist x Atom| x \elem A) and (a2r_2(x y) \subset B)]
*/
TermVar A, B; // relation symbols for our two arguments
A = TermVar.var(leftRelar, "A"); // the left relation
B = TermVar.var(rightRelar, "B"); // the right relation
TermVar[] y = makeTuple(resultArity, "y"); // y is a tuple of the resulting relation
Term somethingInTheJoin = Term.reverseIn(Term.call(name, A, B), y); // a call to "join"
TermVar x = TermVar.var("Atom", "x"); // x is the row that gets removed by the join
TermVar[] amembers = Arrays.copyOf(y, lar);
amembers[lar - 1] = x;
TermVar[] bmembers = new TermVar[rar]; // this is a tuple to join on (element of B)
bmembers[0] = x; // add the last atom in x as the first atom in the match
for (int i = 0; i < bmembers.length - 1; i++) {
bmembers[i + 1] = y[(lar-1)+i];
}
Term xInA = Term.reverseIn(A, amembers); // this means: (y0 y1 .. x) \elem A
Term xyInB = Term.reverseIn(B, bmembers); // this means: (x y2 y3 ...) \elem B
List<TermVar> arglist = new LinkedList<TermVar>(); // universally quantified vars for this axiom
arglist.add(A); // quantify over A
arglist.add(B); // quantify over B
arglist.addAll(Arrays.asList(y)); // quantify over all atoms in the y-tuple
Term axiom = somethingInTheJoin.iff((xInA.and(xyInB)).exists(x)).forall(arglist);
axiom.setComment("axiom for " + name);
file.addAxiom(axiom);
// to work properly, we also add some neccessary lemmas
assertLemmasJoin(lar, rar);
}
}
/** Implements "last" for a given relation. The name of the relation must be a proper suffix
* for a SMT function.
*
* @param suffix
* @param finite
* @throws ModelException
*/
private void declareLast(String suffix, boolean finite) throws ModelException {
declareNone();
// implement Last
String name = "last"+suffix;
file.addFunction("Rel1", name);
// this branch is important because card_1 may not be defined (due to S being infite). SMT does not handle partial functions, so undefined values are not allowed
TermVar N = TermVar.var(suffix); // not actually a variable but a constant
Term lastS = Term.call(name);
if (!finite) {
declareNone();
// ¬finite 1 (N [S]) ⇒ lastS = none 1
Term none = Term.call("none");
Term axiom = Term.call("finite", N).not().implies(lastS.equal(none));
axiom.setComment("infinite axiom for " + name);
file.addAxiom(axiom);
}
else {
declareCardinality(1);
declareOrd();
declareA2r(1);
// finite 1 (N [S]) ⇒ (lastS = sin 1 (ordInv 1 (N [S], card 1 (N [S]))))
Term cardN = Term.call("card_1", N);
Term ordInv = Term.call("at", N, cardN);
Term a2r = Term.call("a2r_1", ordInv);
Term axiom = lastS.equal(a2r);
axiom.setComment("finite axiom for " + name);
file.addAxiom(axiom);
{
// lemma about cardinality being the ord of lastX
TermVar x = TermVar.var("Atom", "x");
Term xInLastS = Term.reverseIn(lastS, x);
Term ordX = Term.call("ord", N, x);
Term lemma = xInLastS.implies(cardN.equal(ordX)).forall(x);
lemma.setComment("lemma about cardinality being the ord of " + lastS);
file.addLemma(lemma);
}
}
}
/** declares and defines the operator "lone" for arity 1.
* "lone" means "at most one"
* @throws ModelException
*/
public void declareLone() throws ModelException {
List<TermVar> argList = new LinkedList<TermVar>();
declareRel(1);
String name = "lone_1";
String relar = "Rel1";
if(file.addFunction("Bool", name, relar))
{
// add axiom
TermVar X = TermVar.var(relar, "X");
TermVar[] aTuple = makeTuple(1, "a");
argList.addAll(Arrays.asList(aTuple));
TermVar[] bTuple = makeTuple(1, "b");
argList.addAll(Arrays.asList(bTuple));
Term lone = Term.call(name, X);
Term aEqualsBTerm = TermBinOp.equals(aTuple, bTuple);
Term aInX = Term.reverseIn(X, aTuple);
Term bInX = Term.reverseIn(X, bTuple);
Term aAndBinX = aInX.and(bInX);
Term existanceImpliesEqual = aAndBinX.implies(aEqualsBTerm).forall(argList);
Term axiom = (lone.iff(existanceImpliesEqual)).forall(X);
file.addAxiom(axiom);
}
}
/** Declares the constant relations Next for a given relation S
* (nextS : Rel2)
* @param suffix the name of the relation S
* @throws ModelException
*/
private void declareNext(String suffix) throws ModelException {
// declarations
declareAtom();
declareIn(1);
declareIn(2);
declareRel(1);
declareRel(2);
declareOrd();
declareFinite();
declareNone();
String nextSname = "next"+suffix;
if (file.addFunction("Rel2", nextSname)) {
TermVar a = TermVar.var("Atom", "a");
TermVar b = TermVar.var("Atom", "b");
TermVar N = TermVar.var(suffix); // actually constant
TermVar one = TermVar.var("1"); // actually constant
// ∀a, b: Atom |(in 1 (a, N [S]) ∧ in 1 (b, N [S]))
// ⇒ (in 2 (a, b, nextS ) ⇔ ord 1 (N [S], b) = ord 1 (N [S], a) + 1)
{
Term guard = Term.reverseIn(N, a).and(Term.reverseIn(N, b));
Term inS = Term.reverseIn(Term.call(nextSname), a, b);
Term follows = Term.call("ord", N, b).equal(Term.call("ord", N, a).plus(one));
Term axiom = guard.implies(inS.equal(follows)).forall(a, b);
axiom.setComment("axiom for " + nextSname);
file.addAxiom(axiom);
}
// ¬(N [S] = none 1 )
{
Term axiom = Term.call("none").equal(N).not();
axiom.setComment("'there is no empty ordered relation' axiom for " + nextSname);
file.addAxiom(axiom);
}
}
}
private void declareNexts(String suffix) throws ModelException {
declareNext(suffix); // "next"+suffix
declareTransitiveClosure(); // transClos
declareDomainRestriction(2); // domRestr_2
declareJoin(1, 2);
if (file.addFunction("Rel1", "nexts"+suffix, "Rel1")) {
// so/nexts = e . ^ so/Ord . (so/Ord <: Next)
// I didn't implement so/Ord, so I'll try it like this: e.^next
//Term nexts = Term.call("nexts", params)
TermVar e = TermVar.var("Rel1", "e"); // parameter to the function
TermVar sig = TermVar.var("Rel1", suffix); // constant
Term nextX = Term.call("next" + suffix);
Term nexts = Term.call("nexts" + suffix, e);
Term tcl = Term.call("transClos", nextX);
Term guard = Term.call("subset_1", e, sig);
Term axiom = guard.implies(nexts.equal(Term.call("join_1x2", e, tcl))).forall(e);
axiom.setComment("axiom for the function 'nexts' of " + suffix);
file.addAxiom(axiom);
}
}
/** adds a declaration and theory for "no" (the empty function)
* @param arity arity of none
* @throws ModelException
*/
public void declareNo(int ar) throws ModelException {
declareAtom();
declareIn(ar);
String relar = "Rel" + ar;
if(file.addFunction("Bool", "no_" + ar, relar))
{
// forall tuples of this arity, tuple is not member of none
TermVar[] a = makeTuple(ar, "a");
TermVar R = TermVar.var(relar, "R");
Term no = Term.call("no_"+ar, R);
Term memb = Term.reverseIn(R, a);
Term axiom = no.implies(memb.not()).forall(R).forall(a);
axiom.setComment("axiom for 'the expression is empty'");
file.addAxiom(axiom);
}
}
public void declareNone() throws ModelException {
declareAtom();
declareIn(1);
if(file.addFunction("Rel1", "none")){
// forall tuples, there exists no in None
TermVar a = TermVar.var("Atom", "a");
Term axiom = Term.reverseIn(Term.call("none"), a).not().forall(a);
axiom.setComment("axiom for empty set");
file.addAxiom(axiom);
}
}
/** declares and defines the operator "one" for arity = 1.
* "one" means "one and only one"
* @throws ModelException
*/
public void declareOne() throws ModelException {
List<TermVar> argList = new LinkedList<TermVar>();
declareRel(1);
String name = "one_1";
String relar = "Rel1";
if(file.addFunction("Bool", name, relar))
{
// add axiom
TermVar X = TermVar.var(relar, "X");
TermVar[] aTuple = makeTuple(1, "a");
argList.addAll(Arrays.asList(aTuple));
Term notEmpty = Term.exists(aTuple, Term.in(argList, X));
TermVar[] bTuple = makeTuple(1, "b");
argList.addAll(Arrays.asList(bTuple));
Term one = Term.call(name, X);
// make the a == b expression
Term aEqualsBTerm = TermBinOp.equals(aTuple, bTuple);
Term aInX = Term.reverseIn(X, aTuple);
Term bInX = Term.reverseIn(X, bTuple);
Term aAndBinX = aInX.and(bInX);
Term existanceImpliesEqual = aAndBinX.implies(aEqualsBTerm).forall(argList);
Term axiom = (one.iff(notEmpty.and(existanceImpliesEqual))).forall(X);
file.addAxiom(axiom);
}
}
private void declareOrd() throws ModelException{
declareAtom();
declareRel(1);
if(file.addFunction("Int", "ord", "Rel1", "Atom"))
{
// ∀r: Reln , a1:n , b1:n : Atom | (finite n (r) ∧ inn (a1:n , r) ∧ inn (b1:n , r)
// ∧ ordn (r, a1:n ) = ordn (r, b1:n )) ⇒ (a1 = b1 ∧ … ∧ an = bn )
TermVar R = TermVar.var("Rel1", "R");
TermVar a = TermVar.var("Atom", "a");
TermVar b = TermVar.var("Atom", "b");
Term guard = Term.reverseIn(R, a).and(Term.reverseIn(R, b));
Term ordeq = Term.call("ord", R, a).equal(Term.call("ord", R, b));
Term axiom = guard.and(ordeq).implies(a.equal(b)).forall(R,a,b);
axiom.setComment("axiom for ord");
file.addAxiom(axiom);
}
if(file.addFunction("Atom", "at", "Rel1", "Int"))
{
// ∀r: Rel1 , a: Atom | in 1 (a, r) ⇒ at 1 (r, ord1 (r, a)) = a
TermVar R = TermVar.var("Rel1", "R");
TermVar a = TermVar.var("Atom", "a");
Term guard = Term.reverseIn(R, a);
Term ord = Term.call("ord", R, a);
Term axiom = guard.implies(Term.call("at", R, ord).equal(a)).forall(R, a);
axiom.setComment("axiom for at (the reverse of ord)");
file.addAxiom(axiom);
}
}
/** Declares all the axioms needed for ordering a given signature.
* Will only produce either finite or infinite axioms.
*
* @param suffix : the name of the signature on which the ordering is defined
* @param finite : if true, the signature is considered finite.
* If false, the signature is considered infinite. This affects special operations like "last element" and "cardinality"
* @throws ModelException
*/
public void declareOrdering(String suffix, boolean finite) throws ModelException {
/* We begin by declaring the common operators finite, and ord.
* Orderings are only valid for signature, so arity is always assumed to be 1.
* The iterator function "elem" is implicitly declared inside declareOrd().
*/
declareFinite();
//declareI2a();
declareOrd();
declareNext(suffix);
declareNexts(suffix);
declareFirst(suffix);
declareLast(suffix, finite);
}
/**
* Declares the relational override
* @param ar
* @throws ModelException
* @rem The relational override works like a union of p and q,
* except that the tuples of q can replaces tuples in p
*/
public void declareOverride(int ar) throws ModelException {
if (ar < 2) {
throw new ModelException("Arity of an override expression 'P ++ Q' must be 2 or higher.");
}
declareRel(ar);
String relar = "Rel"+ar;
if(file.addFunction(relar, "overr_" + ar, relar, relar))
{
// forall a=(a0 a1), b=(b0 b1), P and Q, the tuple a is in P++Q if
// a is in Q or a is in P and there is no b in Q with b0 = a0
TermVar[] a = makeTuple(ar, "a");
TermVar[] b = makeTuple(ar, "b");
TermVar P = TermVar.var(relar, "P");
TermVar Q = TermVar.var(relar, "Q");
Term guard = Term.reverseIn(Term.call("overr_"+ar, P, Q), a);
Term inQ = Term.reverseIn(Q, a);
Term inP = Term.reverseIn(P, a);
Term bEqA = a[0].equal(b[0]);
Term noB = Term.reverseIn(Q, b).and(bEqA).not();
Term axiom = guard.implies(inQ.or(inP.and(noB.exists(b)))).forall(P, Q).forall(a);
axiom.setComment("axiom for override, arity " + ar);
file.addAxiom(axiom);
}
}
public void declareProduct(int lar, int rar) throws ModelException {
if(lar < 1 || rar < 1)
throw new ModelException("The product is not defined for arguments of arity 0.");
declareAtom();
declareRel(rar);
declareRel(lar);
declareRel(lar + rar);
declareIn(rar);
declareIn(lar);
declareIn(lar + rar);
// careful with overloaded + operator
String name = String.format("prod_%dx%d", lar, rar);
String leftRelar = "Rel"+lar;
String rightRelar = "Rel"+rar;
int resultArity = lar + /*sum*/ rar;
String resultRelar = "Rel" + /*concatenation*/ resultArity;
if(file.addFunction(resultRelar, name, leftRelar, rightRelar))
{
// add axiom
// these are the two parameters for the product function
TermVar A = TermVar.var(leftRelar, "A"),
B = TermVar.var(rightRelar, "B");
TermVar[] x = makeTuple(lar, "x"),
y = makeTuple(rar, "y"); // these are two elements, one of A and one of B
Term fn = Term.call(name, A, B);
Term somethingIsInProduct = Term.reverseIn(fn, Util.concat(x, y));
Term xInAandYInB = Term.reverseIn(A, x).and(Term.reverseIn(B, y));
Term axiom = somethingIsInProduct.iff(xInAandYInB).forall(A, B).forall(x).forall(y);
file.addAxiom(axiom);
if(lar == 1 && rar == 1)
{
/* something like:
* (assert
(forall ((R Rel2)(A Rel1)(B Rel1))
(=>
(subset_2 R (prod_1x1 A B)) ; R=(i.qi) A=IID B=Interface ; guard
(forall ((a0 Atom)) ; body
(=>
(in_1 a0 A) ; a in A
(= (not (in_1 a0 (join_2x1 R B))) ; exclusionB
- (no_2 (join_1x2 (a2r_1 a0) R)))))))) ; exclusionA
+ (no_1 (join_1x2 (a2r_1 a0) R)))))))) ; exclusionA
*/
// lemma for subset and product
declareJoin(lar, resultArity);
declareJoin(resultArity, rar);
declareSubset(resultArity);
// declareIn?
declareNo((lar + resultArity - 2));
TermVar R = TermVar.var(resultRelar, "R");
TermVar[] a = makeTuple(lar, "a");
Term guard = Term.call("subset_" + resultArity , R, fn);
Term ainA = Term.reverseIn(A, a);
Term joinA = Term.call("join_" + lar + "x" + resultArity, Term.call("a2r_" + lar, a), R);
Term joinB = Term.call("join_" + resultArity + "x" + rar, R, B);
Term nojoinA = Term.call("no_" + (lar + resultArity - 2), joinA);
Term exclusionA = nojoinA;
Term exclusionB = Term.reverseIn(joinB, a).not();
Term body = ainA.implies((exclusionB.equal(exclusionA))).forall(a);
Term lemma = guard.implies(body).forall(R, A, B);
lemma.setComment("lemma about subset " + resultArity + " and product "+ lar + "x" + rar + " , using join");
file.addLemma(lemma);
}
}
}
/** Declares the range restriction operator
* @param lar arity of the left-hand parameter
* @throws ModelException
* @rem right-hand arity is required to be 1 (type:set)
*/
public void declareRangeRestriction(int lar) throws ModelException {
declareRel(1);
declareRel(lar);
String relar = "Rel"+lar;
if(file.addFunction(relar, "rangeRestr_" + lar, relar, "Rel1"))
{
// for all (b1 b2) in R and a in S, ((b1 b2) in (R :> S)) => b2 = a
TermVar[] b = makeTuple(lar, "b");
TermVar a = TermVar.var("Atom", "a");
TermVar R = TermVar.var(relar, "R");
TermVar S = TermVar.var("Rel1", "S");
Term guard = Term.reverseIn(R, b).and(Term.reverseIn(S, a)).and(Term.reverseIn(Term.call("rangeRestr_" + lar, R, S), b));
Term axiom = guard.implies(b[0].equal(a));
axiom.setComment("Axiom for range restriction of arity " + lar);
file.addAxiom(axiom);
}
}
public void declareReflexiveTransitiveClosure() throws ModelException {
declareAtom();
declareIn(2);
declareRel(2);
declareTrans();
declareIdentity();
String name = "reflTransClos";
if(file.addFunction("Rel2", name, "Rel2"))
{
/// add axiom
// first we define what transitive means
declareTrans();
// then we define what a transitive closure is
// this is split into 3 assertions
// 1. assert r is in trans(r)
TermVar r = TermVar.var("Rel2", "r");
file.addAxiom(Term.call("subset_2", r, Term.call(name, r)).forall(r));
// 2. assert that the transitive closure is -in fact- transitive
file.addAxiom(Term.call("trans", Term.call(name, r)).forall(r));
// 3. assert iden in TCL
Term idenInTCL = Term.call("subset_2", Term.call("iden"), Term.call(name, r)).forall(r);
file.addAxiom(idenInTCL);
// 4. assert that tcl is minimal
TermVar r1 = TermVar.var("Rel2", "r1");
TermVar r2 = TermVar.var("Rel2", "r2");
// Term subsetAndTrans = Term.call("subset_2", r1, r2).and(Term.call("trans", r2));
Term subsetAndTransAndRefl = Term.call("subset_2", r1, r2).and(Term.call("trans", r2)).and(Term.call("subset_2", Term.call("iden"), r2));
Term minimalaxiom = subsetAndTransAndRefl.implies(Term.call("subset_2", Term.call(name, r1), r2)).forall(r1, r2);
file.addAxiom(minimalaxiom);
// don't forget our lemmas
assertLemmasTCL(name);
}
}
private void declareRel(int ar) {
file.addSort("(declare-sort Rel" + ar + ")");
}
/** declares the multiplicity constraint "some".
* Does not take any parameters because multiplicity constraints are always of arity = 1
*
* @throws ModelException
*/
public void declareSome(int ar) throws ModelException {
declareRel(1);
String name = "some_" + ar;
String relar = "Rel" + ar;
if(file.addFunction("Bool", name, relar))
{
// axiom: some means that there is any Atom/Tuple inside the argument expression
TermVar A = TermVar.var(relar, "A");
TermVar[] aTuple = makeTuple(ar, "a");
Term some = Term.call(name, A);
Term xInA = Term.reverseIn(A, aTuple);
Term axiom = some.iff(xInA.exists(aTuple)).forall(A);
file.addAxiom(axiom);
}
}
/** adds a declaration and theory for subset and subrel
* @param arity of the set expression
* @throws ModelException
*/
public void declareSubset(int ar) throws ModelException {
// declare prerequisite sorts
declareAtom();
declareRel(ar);
// declare subset function, e.g. (declare-fun subset_2 (Rel2, Rel2) bool)
// add declaration
String relSort = "Rel"+ar;
if(file.addFunction("Bool", "subset_" + ar, relSort, relSort)){
// if successfully added; add axiom(s) as well
// prepare parameter list for in()
List<TermVar> atomVars = new LinkedList<TermVar>();
for(int i = 0; i < ar; i++){
atomVars.add(TermVar.var("Atom", "a" + i));
}
// declare variables
TermVar x = TermVar.var(relSort, "x"); // a Set or Relation
TermVar y = TermVar.var(relSort, "y"); // another Set or Relation
Term subset = Term.call("subset_"+ar, x, y); // x is subset of y
Term inImpliesIn = Term.in(atomVars, x).implies(Term.in(atomVars, y)); // if an atom is in x, it is also in y
// now quantify the two expressions for all x, y and atoms
Term axiom = subset.equal(inImpliesIn.forall(atomVars)).forall(x, y);
axiom.setComment("subset axiom for " + relSort);
file.addAxiom(axiom); // add this axiom to the list of assertions
}
}
private void declareTrans() throws ModelException {
declareAtom();
declareRel(2);
declareIn(2);
if(file.addFunction("Bool", "trans", "Rel2")){
//
TermVar a1 = TermVar.var("Atom", "a1");
TermVar a2 = TermVar.var("Atom", "a2");
TermVar a3 = TermVar.var("Atom", "a3");
TermVar r = TermVar.var("Rel2", "r");
//
Term a12reachR = Term.reverseIn(r, a1, a2);
Term a23reachR = Term.reverseIn(r, a2, a3);
Term a13reachR = Term.reverseIn(r, a1, a3);
Term meaning = (a12reachR.and(a23reachR)).implies(a13reachR);
Term fun = Term.call("trans", r);
Term axiomtransitivity = fun.iff(meaning.forall(a1, a2, a3)).forall(r);
axiomtransitivity.setComment("this axiom defines transitivity");
file.addAxiom(axiomtransitivity);
}
}
// arity is always 2
public void declareTransitiveClosure() throws ModelException {
/* This should be something like here https://en.wikipedia.org/wiki/Closure_operator
* so we need 4 axioms:
* 1 transitive
* 2 extensive
* 3 increasing
* 4 idempotent
* | <math>X \subseteq \operatorname{cl}(X)</math>
| (cl is ''extensive'')
|-
| <math>X\subseteq Y \Rightarrow \operatorname{cl}(X) \subseteq \operatorname{cl}(Y)</math>
| (cl is ''increasing'')
|-
| <math> \operatorname{cl}(\operatorname{cl}(X))=\operatorname{cl}(X)</math>
| (cl is ''idempotent'')
* */
declareAtom();
declareIn(2);
declareRel(2);
// helper function to make transitive closure more readable and less redundant
declareTrans();
String name = "transClos";
if(file.addFunction("Rel2", name, "Rel2"))
{
/// add axiom
// we define what a transitive closure is
// this is split into 3 assertions
// 1. assert that the transitive closure is -in fact- transitive
TermVar r1 = TermVar.var("Rel2", "r1");
Term tcl = Term.call(name, r1);
Term transitive = Term.call("trans", tcl).forall(r1);
transitive.setComment("this axiom satisfies transitivity for transclos");
file.addAxiom(transitive);
// 2. assert that transcl(r) is extensive
Term extensive = Term.call("subset_2", r1, Term.call(name, r1)).forall(r1);
extensive.setComment("this axioms satisfies that tcl is extensive");
file.addAxiom(extensive);
// 3. assert that tcl is increasing
TermVar r2 = TermVar.var("Rel2", "r2");
Term subset = Term.call("subset_2", r1, r2);
Term increasing = subset.implies(Term.call("subset_2", tcl, r2)).forall(r1, r2);
increasing.setComment("this axiom satisfies that transclos is increasing");
file.addAxiom(increasing);
// 4. assert that tcl is idempotent
Term closclos = Term.call(name, tcl);
Term idempotent = closclos.equal(tcl).forall(r1);
idempotent.setComment("this axiom satisfies that tcl should be idempotent");
file.addAxiom(idempotent);
// also, add some lemma about in_2 and the transCl
assertLemmasTCL("transClos");
}
}
// arity is always 2
public void declareTranspose() throws ModelException {
declareAtom();
declareIn(2);
declareRel(2);
String name = "transp";
if(file.addFunction("Rel2", name, "Rel2"))
{
// ∀r: Rel2 , a1 , a2 : Atom | in2 (a1 , a2 , transpose 2 (r)) ⇔ in2 (a2 , a1 , r)
TermVar R = TermVar.var("Rel2", "R");
TermVar[] a = makeTuple(2, "a");
Term axiom = Term.reverseIn(Term.call(name, R), a).equal(Term.reverseIn(R, Util.reverse(a))).forall(Util.concat(a, R));
axiom.setComment("axiom for transposition");
file.addAxiom(axiom);
}
}
public void declareUnion(int ar) throws ModelException {
declareRel(ar);
String relar = "Rel" + ar;
String name = "union_" + ar;
if(file.addFunction(relar, name, relar, relar))
{
// x in union A B = { x in A or x in B }
List<TermVar> arglist = new LinkedList<TermVar>();
TermVar[] x = makeTuple(ar, "x");
TermVar A = TermVar.var(relar, "A");
TermVar B = TermVar.var(relar, "B");
Term xInA = Term.reverseIn(A, x);
Term xInB = Term.reverseIn(B, x);
Term orTerm = xInA.or(xInB);
Term call = Term.call(name, A, B);
arglist.addAll(Arrays.asList(x));
arglist.add(A);
arglist.add(B);
Term axiom = Term.reverseIn(call, x).iff(orTerm).forall(arglist);
axiom.setComment("axiom for union of " + relar);
file.addAxiom(axiom);
}
}
private TermVar[] makeTuple(int ar, String basename) {
TermVar[] x = new TermVar[ar];
for (int i = 0; i < x.length; i++) {
x[i] = TermVar.var("Atom", basename+i); // the atoms are named "a0" "a1" etc
}
return x;
}
public Term a2r(int ar, Term ... sub) throws ModelException {
declareA2r(ar);
return Term.call("a2r_"+ar, sub);
}
private Term a2r(TermVar[] vars) throws ModelException {
return a2r(vars.length, vars);
}
private void assertLemmasJoin(int lar, int rar) throws ModelException {
// lar <= rar is default case
int uniquerows = lar + rar -1;
int largerarity = lar > rar ? lar : rar;
TermVar r = TermVar.var("Rel"+largerarity, "r");
TermVar[] atoms = makeTuple(uniquerows, "a");
TermVar[] relmembers = Arrays.copyOf(atoms, largerarity);
TermVar[] singles = Arrays.copyOfRange(atoms, largerarity - 1, uniquerows);
TermVar[] result = new TermVar[uniquerows - 1];
for (int i = 0; i < relmembers.length -1; i++) {
result[i] = relmembers[i];
}
for (int i = 1; i < singles.length; i++) {
result[relmembers.length - 2 + i] = singles[i];
}
Term lhs, rhs;
if (lar > rar) {
lhs = r;
rhs = a2r(singles);
}
else {
// interestingly, the lemma holds for both cases if we just reverse the arrays
atoms = Util.reverse(atoms); // not really needed, but looks nicer
relmembers = Util.reverse(relmembers);
singles = Util.reverse(singles);
result = Util.reverse(result);
declareA2r(singles.length);
lhs = a2r(singles);
lhs.comment = "(swapped)";
rhs = r;
}
Term aInR = Term.reverseIn(r, relmembers);
String name = "join_" + lar + "x" + rar;
Term resultInJoin = Term.reverseIn(Term.call(name, lhs, rhs), result);
Term lemma = resultInJoin.implies(aInR).forall(Util.concat(atoms, r));
lemma.setComment("1. lemma for "+name+". direction: join to in");
file.addLemma(lemma);
lemma = aInR.implies(resultInJoin).forall(Util.concat(atoms, r));
lemma.setComment("2. lemma for "+name+". direction: in to join");
file.addLemma(lemma);
if(lar == 1 && rar == 2){
/* lemma for the com-theorem1
* ; R=(i.qi) S=iids
(assert (! (forall ((R Rel2)(S Rel2)(x Atom))
(=>
(no_2 (join_1x2 (a2r_1 x) R))
(no_2 (join_1x2 (a2r_1 x) (join_2x2 R S))))))
:named step21
)
*/
declareJoin(2, 2);
declareA2r(1);
declareNo(1);
TermVar R = TermVar.var("Rel2", "R");
TermVar S = TermVar.var("Rel2", "S");
TermVar x = TermVar.var("Atom", "x");
Term Xrel = Term.call("a2r_1", x);
Term joinRS = Term.call("join_2x2", R, S);
Term guard = Term.call("no_1", Term.call(name, Xrel, R));
Term body = Term.call("no_1", Term.call(name, Xrel, joinRS));
lemma = guard.implies(body).forall(R, S, x);
lemma.setComment("lemma for step 21 of the com-theorem1 for join_1x2: R=(i.qi) S=iids");
file.addLemma(lemma);
}
}
/**
* Adds lemmas for transitive closure to work properly.
* These lemmas are the result of experimentation with the z3 solver.
* @param name
* @throws ModelException
*/
private void assertLemmasTCL(String name) throws ModelException {
/* lemma 1 about the "second-last element":
* (forall ((a1 Atom)(a3 Atom)(r Rel2))
* (=>
* (in_2 a1 a3 (transClos r)) ; guard
* (exists ((a2 Atom))
* (or ; body
* (not (in_2 a1 a2 r)) ; not inR
* (and (in_2 a1 a2 r) (in_2 a2 a3 (transClos r))))))) ; inR && middleInTCL
*/
TermVar a1 = TermVar.var("Atom", "a1");
TermVar a2 = TermVar.var("Atom", "a2"); // "middle element"
TermVar a3 = TermVar.var("Atom", "a3");
TermVar R = TermVar.var("Rel2", "R");
Term tCl = Term.call(name, R);
Term guard = Term.reverseIn(tCl, a1, a3);
{
Term inR = Term.reverseIn(R, a1, a2);
Term middleInTCL = Term.reverseIn(tCl, a2, a3);
Term body = inR.not().or(inR.and(middleInTCL)).forall(a2);
Term lemma1 = guard.implies(body).forall(a1, a3, R);
lemma1.setComment("lemma 1 for " + name + " about the second-last 'middle element'");
file.addLemma(lemma1);
}
/* lemma 2 about the "second element":
* (forall ((a1 Atom)(a3 Atom)(r Rel2)) (=>
* (in_2 a1 a3 (transClos r)) ; guard
* (exists ((a2 Atom)) (or
* (not (in_2 a2 a3 r)) ; not inR
* (and (in_2 a2 a3 r) (in_2 a1 a2 (transClos r))))))
*/
{
Term inR = Term.reverseIn(R, a2, a3);
Term middleInTCL = Term.reverseIn(tCl, a1, a2);
Term body = inR.not().or(inR.and(middleInTCL)).forall(a2);
Term lemma2 = guard.implies(body).forall(a1, a3, R);
lemma2.setComment("lemma 1 for " + name + " about the second 'middle element'");
file.addLemma(lemma2);
}
}
}
| true | true | public void declareProduct(int lar, int rar) throws ModelException {
if(lar < 1 || rar < 1)
throw new ModelException("The product is not defined for arguments of arity 0.");
declareAtom();
declareRel(rar);
declareRel(lar);
declareRel(lar + rar);
declareIn(rar);
declareIn(lar);
declareIn(lar + rar);
// careful with overloaded + operator
String name = String.format("prod_%dx%d", lar, rar);
String leftRelar = "Rel"+lar;
String rightRelar = "Rel"+rar;
int resultArity = lar + /*sum*/ rar;
String resultRelar = "Rel" + /*concatenation*/ resultArity;
if(file.addFunction(resultRelar, name, leftRelar, rightRelar))
{
// add axiom
// these are the two parameters for the product function
TermVar A = TermVar.var(leftRelar, "A"),
B = TermVar.var(rightRelar, "B");
TermVar[] x = makeTuple(lar, "x"),
y = makeTuple(rar, "y"); // these are two elements, one of A and one of B
Term fn = Term.call(name, A, B);
Term somethingIsInProduct = Term.reverseIn(fn, Util.concat(x, y));
Term xInAandYInB = Term.reverseIn(A, x).and(Term.reverseIn(B, y));
Term axiom = somethingIsInProduct.iff(xInAandYInB).forall(A, B).forall(x).forall(y);
file.addAxiom(axiom);
if(lar == 1 && rar == 1)
{
/* something like:
* (assert
(forall ((R Rel2)(A Rel1)(B Rel1))
(=>
(subset_2 R (prod_1x1 A B)) ; R=(i.qi) A=IID B=Interface ; guard
(forall ((a0 Atom)) ; body
(=>
(in_1 a0 A) ; a in A
(= (not (in_1 a0 (join_2x1 R B))) ; exclusionB
(no_2 (join_1x2 (a2r_1 a0) R)))))))) ; exclusionA
*/
// lemma for subset and product
declareJoin(lar, resultArity);
declareJoin(resultArity, rar);
declareSubset(resultArity);
// declareIn?
declareNo((lar + resultArity - 2));
TermVar R = TermVar.var(resultRelar, "R");
TermVar[] a = makeTuple(lar, "a");
Term guard = Term.call("subset_" + resultArity , R, fn);
Term ainA = Term.reverseIn(A, a);
Term joinA = Term.call("join_" + lar + "x" + resultArity, Term.call("a2r_" + lar, a), R);
Term joinB = Term.call("join_" + resultArity + "x" + rar, R, B);
Term nojoinA = Term.call("no_" + (lar + resultArity - 2), joinA);
Term exclusionA = nojoinA;
Term exclusionB = Term.reverseIn(joinB, a).not();
Term body = ainA.implies((exclusionB.equal(exclusionA))).forall(a);
Term lemma = guard.implies(body).forall(R, A, B);
lemma.setComment("lemma about subset " + resultArity + " and product "+ lar + "x" + rar + " , using join");
file.addLemma(lemma);
}
}
}
| public void declareProduct(int lar, int rar) throws ModelException {
if(lar < 1 || rar < 1)
throw new ModelException("The product is not defined for arguments of arity 0.");
declareAtom();
declareRel(rar);
declareRel(lar);
declareRel(lar + rar);
declareIn(rar);
declareIn(lar);
declareIn(lar + rar);
// careful with overloaded + operator
String name = String.format("prod_%dx%d", lar, rar);
String leftRelar = "Rel"+lar;
String rightRelar = "Rel"+rar;
int resultArity = lar + /*sum*/ rar;
String resultRelar = "Rel" + /*concatenation*/ resultArity;
if(file.addFunction(resultRelar, name, leftRelar, rightRelar))
{
// add axiom
// these are the two parameters for the product function
TermVar A = TermVar.var(leftRelar, "A"),
B = TermVar.var(rightRelar, "B");
TermVar[] x = makeTuple(lar, "x"),
y = makeTuple(rar, "y"); // these are two elements, one of A and one of B
Term fn = Term.call(name, A, B);
Term somethingIsInProduct = Term.reverseIn(fn, Util.concat(x, y));
Term xInAandYInB = Term.reverseIn(A, x).and(Term.reverseIn(B, y));
Term axiom = somethingIsInProduct.iff(xInAandYInB).forall(A, B).forall(x).forall(y);
file.addAxiom(axiom);
if(lar == 1 && rar == 1)
{
/* something like:
* (assert
(forall ((R Rel2)(A Rel1)(B Rel1))
(=>
(subset_2 R (prod_1x1 A B)) ; R=(i.qi) A=IID B=Interface ; guard
(forall ((a0 Atom)) ; body
(=>
(in_1 a0 A) ; a in A
(= (not (in_1 a0 (join_2x1 R B))) ; exclusionB
(no_1 (join_1x2 (a2r_1 a0) R)))))))) ; exclusionA
*/
// lemma for subset and product
declareJoin(lar, resultArity);
declareJoin(resultArity, rar);
declareSubset(resultArity);
// declareIn?
declareNo((lar + resultArity - 2));
TermVar R = TermVar.var(resultRelar, "R");
TermVar[] a = makeTuple(lar, "a");
Term guard = Term.call("subset_" + resultArity , R, fn);
Term ainA = Term.reverseIn(A, a);
Term joinA = Term.call("join_" + lar + "x" + resultArity, Term.call("a2r_" + lar, a), R);
Term joinB = Term.call("join_" + resultArity + "x" + rar, R, B);
Term nojoinA = Term.call("no_" + (lar + resultArity - 2), joinA);
Term exclusionA = nojoinA;
Term exclusionB = Term.reverseIn(joinB, a).not();
Term body = ainA.implies((exclusionB.equal(exclusionA))).forall(a);
Term lemma = guard.implies(body).forall(R, A, B);
lemma.setComment("lemma about subset " + resultArity + " and product "+ lar + "x" + rar + " , using join");
file.addLemma(lemma);
}
}
}
|
diff --git a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
index 3fb40628..c1511aa5 100644
--- a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
+++ b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
@@ -1,1665 +1,1665 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.filter.initialization;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.zip.ZipInputStream;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import liquibase.changelog.ChangeSet;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.ImplementationId;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.APIException;
import org.openmrs.api.PasswordException;
import org.openmrs.api.context.Context;
import org.openmrs.module.MandatoryModuleException;
import org.openmrs.module.OpenmrsCoreModuleException;
import org.openmrs.module.web.WebModuleUtil;
import org.openmrs.scheduler.SchedulerUtil;
import org.openmrs.util.DatabaseUpdateException;
import org.openmrs.util.DatabaseUpdater;
import org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback;
import org.openmrs.util.DatabaseUtil;
import org.openmrs.util.InputRequiredException;
import org.openmrs.util.MemoryAppender;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.util.Security;
import org.openmrs.web.Listener;
import org.openmrs.web.WebConstants;
import org.openmrs.web.filter.StartupFilter;
import org.openmrs.web.filter.util.CustomResourseLoader;
import org.openmrs.web.filter.util.ErrorMessageConstants;
import org.openmrs.web.filter.util.FilterUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
/**
* This is the first filter that is processed. It is only active when starting OpenMRS for the very
* first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the
* {@link Listener} wasn't able to find any runtime properties
*/
public class InitializationFilter extends StartupFilter {
private static final Log log = LogFactory.getLog(InitializationFilter.class);
private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml";
private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml";
private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
/**
* The very first page of wizard, that asks user for select his preferred language
*/
private final String CHOOSE_LANG = "chooselang.vm";
/**
* The second page of the wizard that asks for simple or advanced installation.
*/
private final String INSTALL_METHOD = "installmethod.vm";
/**
* The simple installation setup page.
*/
private final String SIMPLE_SETUP = "simplesetup.vm";
/**
* The first page of the advanced installation of the wizard that asks for a current or past
* database
*/
private final String DATABASE_SETUP = "databasesetup.vm";
/**
* The page from where the user specifies the url to a production system
*/
private final String TESTING_PRODUCTION_URL_SETUP = "productionurl.vm";
/**
* The velocity macro page to redirect to if an error occurs or on initial startup
*/
private final String DEFAULT_PAGE = CHOOSE_LANG;
/**
* This page asks whether database tables/demo data should be inserted and what the
* username/password that will be put into the runtime properties is
*/
private final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
/**
* This page lets the user define the admin user
*/
private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
/**
* This page lets the user pick an implementation id
*/
private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
/**
* This page asks for settings that will be put into the runtime properties files
*/
private final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
/**
* A page that tells the user that everything is collected and will now be processed
*/
private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
/**
* A page that lists off what is happening while it is going on. This page has ajax that callst
* he {@value #PROGRESS_VM_AJAXREQUEST} page
*/
private static final String PROGRESS_VM = "progress.vm";
/**
* This url is called by javascript to get the status of the install
*/
private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
public static final String RELEASE_TESTING_MODULE_PATH = "/module/testing/";
/**
* The model object that holds all the properties that the rendered templates use. All
* attributes on this object are made available to all templates via reflection in the
* {@link #renderTemplate(String, Map, httpResponse)} method.
*/
private InitializationWizardModel wizardModel = null;
private InitializationCompletion initJob;
/**
* Variable set to true as soon as the installation begins and set to false when the process
* ends This thread should only be accesses through the synchronized method.
*/
private static boolean isInstallationStarted = false;
// the actual driver loaded by the DatabaseUpdater class
private String loadedDriverString;
/**
* Variable set at the end of the wizard when spring is being restarted
*/
private static boolean initializationComplete = false;
/**
* The login page when the testing install option is selected
*/
public static final String TESTING_AUTHENTICATION_SETUP = "authentication.vm";
synchronized protected void setInitializationComplete(boolean initializationComplete) {
InitializationFilter.initializationComplete = initializationComplete;
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
if (page == null) {
checkLocaleAttributesForFirstTime(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
// get props and render the second page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.currentDatabaseUsername);
wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
wizardModel.currentDatabasePassword);
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
// do step one of the wizard
httpResponse.setContentType("text/html");
// if any body has already started installation
if (isInstallationStarted()) {
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
} else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
httpResponse.setContentType("text/json");
httpResponse.setHeader("Cache-Control", "no-cache");
Map<String, Object> result = new HashMap<String, Object>();
if (initJob != null) {
result.put("hasErrors", initJob.hasErrors());
if (initJob.hasErrors()) {
result.put("errorPage", initJob.getErrorPage());
errors.putAll(initJob.getErrors());
}
result.put("initializationComplete", isInitializationComplete());
result.put("message", initJob.getMessage());
result.put("actionCounter", initJob.getStepsComplete());
if (!isInitializationComplete()) {
result.put("executingTask", initJob.getExecutingTask());
result.put("executedTasks", initJob.getExecutedTasks());
result.put("completedPercentage", initJob.getCompletedPercentage());
}
Appender appender = Logger.getRootLogger().getAppender("MEMORY_APPENDER");
if (appender instanceof MemoryAppender) {
MemoryAppender memoryAppender = (MemoryAppender) appender;
List<String> logLines = memoryAppender.getLogLines();
// truncate the list to the last 5 so we don't overwhelm jquery
if (logLines.size() > 5)
logLines = logLines.subList(logLines.size() - 5, logLines.size());
result.put("logLines", logLines);
} else {
result.put("logLines", new ArrayList<String>());
}
}
httpResponse.getWriter().write(toJSONString(result, true));
}
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 4;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 5;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
renderTemplate(TESTING_AUTHENTICATION_SETUP, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.currentStepNumber = 4;
} else {
wizardModel.currentStepNumber = 2;
}
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
- page = TESTING_AUTHENTICATION_SETUP;
+ page = DATABASE_TABLES_AND_USER;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = false;
wizardModel.addDemoData = false;
//if we have a runtime properties file
if (skipDatabaseSetupPage()) {
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.currentDatabaseUsername = props.getProperty("connection.username");
wizardModel.currentDatabasePassword = props.getProperty("connection.password");
wizardModel.createDatabaseUsername = wizardModel.currentDatabaseUsername;
wizardModel.createDatabasePassword = wizardModel.currentDatabasePassword;
}
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
wizardModel.currentStepNumber = 2;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty()) {
//If we have a runtime properties file, get the database setup details from it
if (skipDatabaseSetupPage()) {
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.databaseConnection = props.getProperty("connection.url");
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
page = TESTING_AUTHENTICATION_SETUP;
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.databaseName = InitializationWizardModel.DEFAULT_DATABASE_NAME;
page = WIZARD_COMPLETE;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 3;
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
/**
* This method should be called after the user has left wizard's first page (i.e. choose
* language). It checks if user has changed any of locale related parameters and makes
* appropriate corrections with filter's model or/and with locale attribute inside user's
* session.
*
* @param httpRequest the http request object
*/
private void checkLocaleAttributes(HttpServletRequest httpRequest) {
String localeParameter = httpRequest.getParameter(FilterUtil.LOCALE_ATTRIBUTE);
Boolean rememberLocale = false;
// we need to check if user wants that system will remember his selection of language
if (httpRequest.getParameter(FilterUtil.REMEMBER_ATTRIBUTE) != null)
rememberLocale = true;
if (localeParameter != null) {
String storedLocale = null;
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
storedLocale = httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE).toString();
}
// if user has changed locale parameter to new one
// or chooses it parameter at first page loading
if ((storedLocale == null) || (storedLocale != null && !storedLocale.equals(localeParameter))) {
log.info("Stored locale parameter to session " + localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
}
if (rememberLocale) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, true);
} else {
// we need to reset it if it was set before
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, null);
}
}
}
/**
* It sets locale parameter for current session when user is making first GET http request to
* application. It retrieves user locale from request object and checks if this locale is
* supported by application. If not, it uses {@link Locale#ENGLISH} by default
*
* @param httpRequest the http request object
*/
public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
Locale locale = httpRequest.getLocale();
if (CustomResourseLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
} else {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
}
}
/**
* Verify the database connection works.
*
* @param connectionUsername
* @param connectionPassword
* @param databaseConnectionFinalUrl
* @return true/false whether it was verified or not
*/
private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) {
try {
// verify connection
//Set Database Driver using driver String
Class.forName(loadedDriverString).newInstance();
DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
return true;
}
catch (Exception e) {
errors.put("User account " + connectionUsername + " does not work. " + e.getMessage()
+ " See the error log for more details", null); // TODO internationalize this
log.warn("Error while checking the connection user account", e);
return false;
}
}
/**
* Convenience method to load the runtime properties file.
*
* @return the runtime properties file.
*/
private File getRuntimePropertiesFile() {
File file = null;
String pathName = OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME);
if (pathName != null) {
file = new File(pathName);
} else
file = new File(OpenmrsUtil.getApplicationDataDirectory(), WebConstants.WEBAPP_NAME + "-runtime.properties");
log.debug("Using file: " + file.getAbsolutePath());
return file;
}
/**
* @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
*/
@Override
protected String getTemplatePrefix() {
return "org/openmrs/web/filter/initialization/";
}
/**
* @see org.openmrs.web.filter.StartupFilter#getModel()
*/
@Override
protected Object getModel() {
return wizardModel;
}
/**
* @see org.openmrs.web.filter.StartupFilter#skipFilter()
*/
@Override
public boolean skipFilter(HttpServletRequest httpRequest) {
// If progress.vm makes an ajax request even immediately after initialization has completed
// let the request pass in order to let progress.vm load the start page of OpenMRS
// (otherwise progress.vm is displayed "forever")
return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page")) && !initializationRequired();
}
/**
* Public method that returns true if database+runtime properties initialization is required
*
* @return true if this initialization wizard needs to run
*/
public static boolean initializationRequired() {
return !isInitializationComplete();
}
/**
* @param isInstallationStarted the value to set
*/
protected static synchronized void setInstallationStarted(boolean isInstallationStarted) {
InitializationFilter.isInstallationStarted = isInstallationStarted;
}
/**
* @return true if installation has been started
*/
protected static boolean isInstallationStarted() {
return isInstallationStarted;
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
wizardModel = new InitializationWizardModel();
//set whether need to do initialization work
if (isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
//if runtime-properties file doesn't exist, have to do initialization work
setInitializationComplete(false);
} else {
//if database is not empty, then let UpdaterFilter to judge whether need database update
setInitializationComplete(true);
}
}
private void importTestDataSet(InputStream in, String connectionUrl, String connectionUsername, String connectionPassword)
throws IOException {
File tempFile = null;
FileOutputStream fileOut = null;
try {
ZipInputStream zipIn = new ZipInputStream(in);
zipIn.getNextEntry();
tempFile = File.createTempFile("testDataSet", "dump");
fileOut = new FileOutputStream(tempFile);
IOUtils.copy(zipIn, fileOut);
fileOut.close();
zipIn.close();
URI uri = URI.create(connectionUrl.substring(5));
String host = uri.getHost();
int port = uri.getPort();
TestInstallUtil.addTestData(host, port, wizardModel.databaseName, connectionUsername, connectionPassword,
tempFile.getAbsolutePath());
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fileOut);
if (tempFile != null) {
tempFile.delete();
}
}
}
/**
* @param silent if this statement fails do not display stack trace or record an error in the
* wizard object.
* @param user username to connect with
* @param pw password to connect with
* @param sql String containing sql and question marks
* @param args the strings to fill into the question marks in the given sql
* @return result of executeUpdate or -1 for error
*/
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
Connection connection = null;
try {
String replacedSql = sql;
// TODO how to get the driver for the other dbs...
if (wizardModel.databaseConnection.contains("mysql")) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} else {
replacedSql = replacedSql.replaceAll("`", "\"");
}
String tempDatabaseConnection = "";
if (sql.contains("create database")) {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db
} else {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
}
connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
for (String arg : args) {
arg = arg.replace(";", "^"); // to prevent any sql injection
replacedSql = replacedSql.replaceFirst("\\?", arg);
}
// run the sql statement
Statement statement = connection.createStatement();
return statement.executeUpdate(replacedSql);
}
catch (SQLException sqlex) {
if (!silent) {
// log and add error
log.warn("error executing sql: " + sql, sqlex);
errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null);
}
}
catch (InstantiationException e) {
log.error("Error generated", e);
}
catch (IllegalAccessException e) {
log.error("Error generated", e);
}
catch (ClassNotFoundException e) {
log.error("Error generated", e);
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
log.warn("Error while closing connection", t);
}
}
return -1;
}
/**
* Convenience variable to know if this wizard has completed successfully and that this wizard
* does not need to be executed again
*
* @return true if this has been run already
*/
synchronized private static boolean isInitializationComplete() {
return initializationComplete;
}
/**
* Check if the given value is null or a zero-length String
*
* @param value the string to check
* @param errors the list of errors to append the errorMessage to if value is empty
* @param errorMessageCode the string with code of error message translation to append if value
* is empty
* @return true if the value is non-empty
*/
private boolean checkForEmptyValue(String value, Map<String, Object[]> errors, String errorMessageCode) {
if (value != null && !value.equals("")) {
return true;
}
errors.put(errorMessageCode, null);
return false;
}
/**
* Separate thread that will run through all tasks to complete the initialization. The database
* is created, user's created, etc here
*/
private class InitializationCompletion {
private Thread thread;
private int steps = 0;
private String message = "";
private Map<String, Object[]> errors = new HashMap<String, Object[]>();
private String errorPage = null;
private boolean erroneous = false;
private int completedPercentage = 0;
private WizardTask executingTask;
private List<WizardTask> executedTasks = new ArrayList<WizardTask>();
synchronized public void reportError(String error, String errorPage, Object... params) {
errors.put(error, params);
this.errorPage = errorPage;
erroneous = true;
}
synchronized public boolean hasErrors() {
return erroneous;
}
synchronized public String getErrorPage() {
return errorPage;
}
synchronized public Map<String, Object[]> getErrors() {
return errors;
}
/**
* Start the completion stage. This fires up the thread to do all the work.
*/
public void start() {
setStepsComplete(0);
setInitializationComplete(false);
thread.start();
}
public void waitForCompletion() {
try {
thread.join();
}
catch (InterruptedException e) {
log.error("Error generated", e);
}
}
synchronized protected void setStepsComplete(int steps) {
this.steps = steps;
}
synchronized protected int getStepsComplete() {
return steps;
}
synchronized public String getMessage() {
return message;
}
synchronized public void setMessage(String message) {
this.message = message;
setStepsComplete(getStepsComplete() + 1);
}
/**
* @return the executingTask
*/
synchronized protected WizardTask getExecutingTask() {
return executingTask;
}
/**
* @return the completedPercentage
*/
protected synchronized int getCompletedPercentage() {
return completedPercentage;
}
/**
* @param completedPercentage the completedPercentage to set
*/
protected synchronized void setCompletedPercentage(int completedPercentage) {
this.completedPercentage = completedPercentage;
}
/**
* Adds a task that has been completed to the list of executed tasks
*
* @param task
*/
synchronized protected void addExecutedTask(WizardTask task) {
this.executedTasks.add(task);
}
/**
* @param executingTask the executingTask to set
*/
synchronized protected void setExecutingTask(WizardTask executingTask) {
this.executingTask = executingTask;
}
/**
* @return the executedTasks
*/
synchronized protected List<WizardTask> getExecutedTasks() {
return this.executedTasks;
}
/**
* This class does all the work of creating the desired database, user, updates, etc
*/
public InitializationCompletion() {
Runnable r = new Runnable() {
/**
* TODO split this up into multiple testable methods
*
* @see java.lang.Runnable#run()
*/
public void run() {
try {
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
setMessage("Create database");
setExecutingTask(WizardTask.CREATE_SCHEMA);
// connect via jdbc and create a database
String sql = "create database if not exists `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername,
wizardModel.createDatabasePassword, sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_NEW, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_SCHEMA);
}
if (wizardModel.createDatabaseUser) {
setMessage("Create database user");
setExecutingTask(WizardTask.CREATE_DB_USER);
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
reportError(ErrorMessageConstants.ERROR_DB_CREATE_DB_USER, DEFAULT_PAGE);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_GRANT_PRIV, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername
+ " all privileges to database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_DB_USER);
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
setMessage("Verify that the database connection works");
// redirect to setup page if we got an error
reportError("Unable to connect to database", DEFAULT_PAGE);
return;
}
// save the properties for startup purposes
Properties runtimeProperties = new Properties();
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
if (StringUtils.hasText(wizardModel.databaseDriver))
runtimeProperties.put("connection.driver_class", wizardModel.databaseDriver);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY, Base64.encode(Security
.generateNewInitVector()));
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY, Base64.encode(Security
.generateNewSecretKey()));
Properties properties = Context.getRuntimeProperties();
properties.putAll(runtimeProperties);
runtimeProperties = properties;
Context.setRuntimeProperties(runtimeProperties);
/**
* A callback class that prints out info about liquibase changesets
*/
class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
private int i = 1;
private String message;
public PrintingChangeSetExecutorCallback(String message) {
this.message = message;
}
/**
* @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet,
* int)
*/
@Override
public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: "
+ changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: "
+ changeSet.getDescription());
setCompletedPercentage(Math.round(i * 100 / numChangeSetsToRun));
}
}
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
setMessage("Executing " + LIQUIBASE_SCHEMA_DATA);
setExecutingTask(WizardTask.CREATE_TABLES);
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS schema file"));
addExecutedTask(WizardTask.CREATE_TABLES);
//reset for this task
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_CORE_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS core data file"));
wizardModel.workLog.add("Created database tables and added core data");
addExecutedTask(WizardTask.ADD_CORE_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE, e
.getMessage());
log.warn("Error while trying to create tables and demo data", e);
}
}
if (wizardModel.importTestData) {
try {
setMessage("Importing test data");
setExecutingTask(WizardTask.IMPORT_TEST_DATA);
setCompletedPercentage(0);
try {
importTestDataSet(TestInstallUtil.getResourceInputStream(wizardModel.productionUrl
+ RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form",
wizardModel.productionUsername, wizardModel.productionPassword),
finalDatabaseConnectionString, connectionUsername, connectionPassword);
setMessage("Importing installed modules...");
if (!TestInstallUtil.addZippedTestModules(TestInstallUtil.getResourceInputStream(
wizardModel.productionUrl + RELEASE_TESTING_MODULE_PATH + "getModules.htm",
wizardModel.productionUsername, wizardModel.productionPassword))) {
reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_ADD_MODULES, DEFAULT_PAGE, "");
log.warn("Failed to add modules");
}
}
catch (APIAuthenticationException e) {
log.warn("Unable to authenticate as a User with the System Developer role");
reportError(ErrorMessageConstants.UPDATE_ERROR_UNABLE_AUTHENTICATE,
TESTING_AUTHENTICATION_SETUP, "");
return;
}
catch (APIException e) {
log.warn("An error occured on the remote server");
reportError(ErrorMessageConstants.ERROR_REMOTE_SERVER, DEFAULT_PAGE, "");
return;
}
wizardModel.workLog.add("Imported test data");
addExecutedTask(WizardTask.IMPORT_TEST_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to import test data", e);
return;
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
setMessage("Adding demo data");
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_DEMO_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms"));
wizardModel.workLog.add("Added demo data");
addExecutedTask(WizardTask.ADD_DEMO_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE, e
.getMessage());
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
setMessage("Updating the database to the latest version");
setCompletedPercentage(0);
setExecutingTask(WizardTask.UPDATE_TO_LATEST);
DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback(
"Updating database tables to latest version "));
addExecutedTask(WizardTask.UPDATE_TO_LATEST);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_UPDATE_TO_LATEST, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to update to the latest database version", e);
return;
}
setExecutingTask(null);
setMessage("Starting OpenMRS");
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
Context.openSession();
// load core modules so that required modules are known at openmrs startup
Listener.loadBundledModules(filterConfig.getServletContext());
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
reportError(ErrorMessageConstants.ERROR_DB_UPDATE, DEFAULT_PAGE, updateEx.getMessage());
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log
.warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now");
reportError(ErrorMessageConstants.ERROR_INPUT_REQ, DEFAULT_PAGE);
return;
}
catch (MandatoryModuleException mandatoryModEx) {
log.warn(
"A mandatory module failed to start. Fix the error or unmark it as mandatory to continue.",
mandatoryModEx);
reportError(ErrorMessageConstants.ERROR_MANDATORY_MOD_REQ, DEFAULT_PAGE, mandatoryModEx
.getMessage());
return;
}
catch (OpenmrsCoreModuleException coreModEx) {
log
.warn(
"A core module failed to start. Make sure that all core modules (with the required minimum versions) are installed and starting properly.",
coreModEx);
reportError(ErrorMessageConstants.ERROR_CORE_MOD_REQ, DEFAULT_PAGE, coreModEx.getMessage());
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
reportError(ErrorMessageConstants.ERROR_SET_INPL_ID, DEFAULT_PAGE, t.getMessage());
log.warn("Implementation ID could not be set.", t);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, t.getMessage());
log.warn("Unable to complete the startup.", t);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
OpenmrsUtil.storeProperties(runtimeProperties, fos,
"Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
Context.closeSession();
}
catch (IOException e) {
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
}
finally {
if (!hasErrors()) {
// set this so that the wizard isn't run again on next page load
setInitializationComplete(true);
// we should also try to store selected by user language
// if user wants to system will do it for him
FilterUtil.storeLocale(wizardModel.localeToSave);
}
setInstallationStarted(false);
}
}
};
thread = new Thread(r);
}
}
/**
* Check whether openmrs database is empty. Having just one non-liquibase table in the given
* database qualifies this as a non-empty database.
*
* @param props the runtime properties
* @return true/false whether openmrs database is empty or doesn't exist yet
*/
private static boolean isDatabaseEmpty(Properties props) {
if (props != null) {
String databaseConnectionFinalUrl = props.getProperty("connection.url");
if (databaseConnectionFinalUrl == null)
return true;
String connectionUsername = props.getProperty("connection.username");
if (connectionUsername == null)
return true;
String connectionPassword = props.getProperty("connection.password");
if (connectionPassword == null)
return true;
Connection connection = null;
try {
DatabaseUtil.loadDatabaseDriver(databaseConnectionFinalUrl);
connection = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
DatabaseMetaData dbMetaData = (DatabaseMetaData) connection.getMetaData();
String[] types = { "TABLE" };
//get all tables
ResultSet tbls = dbMetaData.getTables(null, null, null, types);
while (tbls.next()) {
String tableName = tbls.getString("TABLE_NAME");
//if any table exist besides "liquibasechangelog" or "liquibasechangeloglock", return false
if (!("liquibasechangelog".equals(tableName)) && !("liquibasechangeloglock".equals(tableName)))
return false;
}
return true;
}
catch (Exception e) {
//pass
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
//pass
}
}
//if catch an exception while query database, then consider as database is empty.
return true;
} else
return true;
}
/**
* Convenience method that loads the database driver
*
* @param connection the database connection string
* @param databaseDriver the database driver class name to load
* @return the loaded driver string
*/
public static String loadDriver(String connection, String databaseDriver) {
String loadedDriverString = null;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(connection, databaseDriver);
log.info("using database driver :" + loadedDriverString);
}
catch (ClassNotFoundException e) {
log.error("The given database driver class was not found. "
+ "Please ensure that the database driver jar file is on the class path "
+ "(like in the webapp's lib folder)");
}
return loadedDriverString;
}
/**
* Utility method that checks if there is a runtime properties file containing database connection
* credentials
*
* @return
*/
private static boolean skipDatabaseSetupPage() {
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
return (props != null && StringUtils.hasText(props.getProperty("connection.url"))
&& StringUtils.hasText(props.getProperty("connection.username")) && StringUtils.hasText(props
.getProperty("connection.password")));
}
}
| true | true | protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 4;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 5;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
renderTemplate(TESTING_AUTHENTICATION_SETUP, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.currentStepNumber = 4;
} else {
wizardModel.currentStepNumber = 2;
}
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = false;
wizardModel.addDemoData = false;
//if we have a runtime properties file
if (skipDatabaseSetupPage()) {
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.currentDatabaseUsername = props.getProperty("connection.username");
wizardModel.currentDatabasePassword = props.getProperty("connection.password");
wizardModel.createDatabaseUsername = wizardModel.currentDatabaseUsername;
wizardModel.createDatabasePassword = wizardModel.currentDatabasePassword;
}
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
wizardModel.currentStepNumber = 2;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty()) {
//If we have a runtime properties file, get the database setup details from it
if (skipDatabaseSetupPage()) {
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.databaseConnection = props.getProperty("connection.url");
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
page = TESTING_AUTHENTICATION_SETUP;
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.databaseName = InitializationWizardModel.DEFAULT_DATABASE_NAME;
page = WIZARD_COMPLETE;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 3;
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
| protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(
FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 4;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 1;
wizardModel.numberOfSteps = 5;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
renderTemplate(TESTING_AUTHENTICATION_SETUP, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.currentStepNumber = 4;
} else {
wizardModel.currentStepNumber = 2;
}
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = DATABASE_TABLES_AND_USER;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = false;
wizardModel.addDemoData = false;
//if we have a runtime properties file
if (skipDatabaseSetupPage()) {
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.currentDatabaseUsername = props.getProperty("connection.username");
wizardModel.currentDatabasePassword = props.getProperty("connection.password");
wizardModel.createDatabaseUsername = wizardModel.currentDatabaseUsername;
wizardModel.createDatabasePassword = wizardModel.currentDatabasePassword;
}
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
wizardModel.currentStepNumber = 2;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
wizardModel.currentStepNumber -= 1;
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty()) {
//If we have a runtime properties file, get the database setup details from it
if (skipDatabaseSetupPage()) {
Properties props = OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME);
wizardModel.databaseConnection = props.getProperty("connection.url");
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
page = TESTING_AUTHENTICATION_SETUP;
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.databaseName = InitializationWizardModel.DEFAULT_DATABASE_NAME;
page = WIZARD_COMPLETE;
} else {
page = DATABASE_SETUP;
wizardModel.currentStepNumber = 3;
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
|
diff --git a/src/cz/muni/stanse/automatonchecker/ErrorTracesListCreator.java b/src/cz/muni/stanse/automatonchecker/ErrorTracesListCreator.java
index 278b3ae..059aa40 100644
--- a/src/cz/muni/stanse/automatonchecker/ErrorTracesListCreator.java
+++ b/src/cz/muni/stanse/automatonchecker/ErrorTracesListCreator.java
@@ -1,227 +1,227 @@
/**
* @file .java
* @brief
*
* Copyright (c) 2008-2009 Marek Trtik
*
* Licensed under GPLv2.
*/
package cz.muni.stanse.automatonchecker;
import cz.muni.stanse.Stanse;
import cz.muni.stanse.checker.CheckerErrorTrace;
import cz.muni.stanse.checker.CheckerErrorTraceLocation;
import cz.muni.stanse.codestructures.CFGNode;
import cz.muni.stanse.codestructures.LazyInternalStructures;
import cz.muni.stanse.codestructures.traversal.CFGPathVisitor;
import cz.muni.stanse.utils.Pair;
import java.util.List;
import java.util.Vector;
import java.util.Map;
final class ErrorTracesListCreator extends CFGPathVisitor {
// public section
@Override
public boolean visit(final List<CFGNode> path,
final java.util.Stack<CFGNode> cfgContext) {
- if (getErrorTracesList().size() >= 20
+ if (getErrorTracesList().size() >= 20 || path.size() > 100
|| isLimitOfRejectedMeasureExceeded())
return false;
final CFGNode node = path.iterator().next();
if (getStartNode().equals(node) && path.size() == 1)
return true;
final Pair<PatternLocation,PatternLocation> locationPair =
getNodeLocationDictionary().get(node);
if (locationPair == null)
return true;
final PatternLocation location = locationPair.getSecond();
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getDeliveredAutomataStates(), cfgContext))) {
incrementNumRejectedMeasure(path.size());
return false;
}
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getProcessedAutomataStates(),cfgContext))) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorBeginMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
if (cfgContext.isEmpty() &&
getInternals().getNavigator().isStartNode(node)) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorEntryMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
return true;
}
@Override
public boolean onCFGchange(CFGNode from, CFGNode to) {
final SimpleAutomatonID transformedID =
getTransferor().transfer(from,getRule().getAutomatonID(),to);
if (transformedID == null)
return false;
updateRule(transformedID);
return true;
}
// package-private section
ErrorTracesListCreator(final ErrorRule rule,
final AutomatonStateTransferManager transferor,
final Map<CFGNode,Pair<PatternLocation,PatternLocation>>
nodeLocationDictionary,
final CFGNode startNode,
final LazyInternalStructures internals,
final java.util.List<FalsePositivesDetector> detectors,
final AutomatonCheckerLogger monitor) {
super();
this.rule = rule;
this.transferor = transferor;
this.nodeLocationDictionary = nodeLocationDictionary;
this.startNode = startNode;
this.internals = internals;
errorTracesList = new Vector<CheckerErrorTrace>();
this.detectors = detectors;
this.monitor = monitor;
numRejectedMeasure = 0;
}
Vector<CheckerErrorTrace> getErrorTracesList() {
return errorTracesList;
}
// private section
private boolean isFalsePositive(final List<CFGNode> path,
final java.util.Stack<CFGNode> cfgContext) {
for (final FalsePositivesDetector detector : detectors)
if (detector.isFalsePositive(path,cfgContext,getRule()))
return true;
return false;
}
private CheckerErrorTrace buildErrorTrace(final String beginMsg,
final String innerMsg,
final String endMsg,
final List<CFGNode> path,
final java.util.Stack<CFGNode> context) {
final Vector<CheckerErrorTraceLocation> trace =
new Vector<CheckerErrorTraceLocation>();
for (final CFGNode node : context)
trace.add(new CheckerErrorTraceLocation(getNodeUnitName(node),
getNodeLine(node),"<context>When called from here."));
trace.add(new CheckerErrorTraceLocation(getNodeUnitName(path.get(0)),
getNodeLine(path.get(0)),beginMsg));
if (path.size() > 1)
for (CFGNode item : path.subList(1,path.size() - 1))
trace.add(new CheckerErrorTraceLocation(getNodeUnitName(item),
getNodeLine(item),innerMsg));
trace.add(new CheckerErrorTraceLocation(
getNodeUnitName(path.get(path.size() - 1)),
getNodeLine(path.get(path.size() - 1)),endMsg));
return new CheckerErrorTrace(trace,
"error-trace [" + (getErrorTracesList().size()+1) + "]");
}
private ErrorRule getRule() {
return rule;
}
private void updateRule(final SimpleAutomatonID id) {
rule = new ErrorRule(getRule(),id);
}
private Map<CFGNode,Pair<PatternLocation,PatternLocation>>
getNodeLocationDictionary() {
return nodeLocationDictionary;
}
private CFGNode getStartNode() {
return startNode;
}
private AutomatonStateTransferManager getTransferor() {
return transferor;
}
private LazyInternalStructures getInternals() {
return internals;
}
private String getNodeUnitName(final CFGNode node) {
return Stanse.getUnitManager().getUnitName(getInternals().
getNodeToCFGdictionary().get(node));
}
private boolean isLimitOfRejectedMeasureExceeded() {
return numRejectedMeasure > 1000;
}
private void incrementNumRejectedMeasure(final int pathLen) {
numRejectedMeasure += pathLen;
if (isLimitOfRejectedMeasureExceeded())
getMonitor().note("*** FAILED: budget limit for error traces " +
"search exceeded. Search was early terminated!");
}
private void resetNumRejectedMeasure() {
numRejectedMeasure = 0;
}
public AutomatonCheckerLogger getMonitor() {
return monitor;
}
private int getNodeLine(final CFGNode node) {
// TODO: following lines can be removed, when there are no CFGNodes
// without XML element and each XML element has 'bl' attribute.
if (node.getElement() == null)
return 1;
String attr = node.getElement().attributeValue("bl");
if (attr == null)
return 1;
return Integer.parseInt(attr);
}
private ErrorRule rule;
private final AutomatonStateTransferManager transferor;
private final Map<CFGNode,Pair<PatternLocation,PatternLocation>>
nodeLocationDictionary;
private final CFGNode startNode;
private final LazyInternalStructures internals;
private final Vector<CheckerErrorTrace> errorTracesList;
private final java.util.List<FalsePositivesDetector> detectors;
private final AutomatonCheckerLogger monitor;
private int numRejectedMeasure;
}
| true | true | public boolean visit(final List<CFGNode> path,
final java.util.Stack<CFGNode> cfgContext) {
if (getErrorTracesList().size() >= 20
|| isLimitOfRejectedMeasureExceeded())
return false;
final CFGNode node = path.iterator().next();
if (getStartNode().equals(node) && path.size() == 1)
return true;
final Pair<PatternLocation,PatternLocation> locationPair =
getNodeLocationDictionary().get(node);
if (locationPair == null)
return true;
final PatternLocation location = locationPair.getSecond();
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getDeliveredAutomataStates(), cfgContext))) {
incrementNumRejectedMeasure(path.size());
return false;
}
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getProcessedAutomataStates(),cfgContext))) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorBeginMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
if (cfgContext.isEmpty() &&
getInternals().getNavigator().isStartNode(node)) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorEntryMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
return true;
}
| public boolean visit(final List<CFGNode> path,
final java.util.Stack<CFGNode> cfgContext) {
if (getErrorTracesList().size() >= 20 || path.size() > 100
|| isLimitOfRejectedMeasureExceeded())
return false;
final CFGNode node = path.iterator().next();
if (getStartNode().equals(node) && path.size() == 1)
return true;
final Pair<PatternLocation,PatternLocation> locationPair =
getNodeLocationDictionary().get(node);
if (locationPair == null)
return true;
final PatternLocation location = locationPair.getSecond();
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getDeliveredAutomataStates(), cfgContext))) {
incrementNumRejectedMeasure(path.size());
return false;
}
if (!getRule().checkForError(
AutomatonStateCFGcontextAlgo.filterStatesByContext(
location.getProcessedAutomataStates(),cfgContext))) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorBeginMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
if (cfgContext.isEmpty() &&
getInternals().getNavigator().isStartNode(node)) {
if (!isFalsePositive(path,cfgContext)) {
getErrorTracesList().add(buildErrorTrace(
getRule().getErrorEntryMessage(),
getRule().getErrorPropagMessage(),
getRule().getErrorEndMessage(),
path,cfgContext));
resetNumRejectedMeasure();
}
else
incrementNumRejectedMeasure(path.size());
return false;
}
return true;
}
|
diff --git a/TestProject/src/test/PlayerTest.java b/TestProject/src/test/PlayerTest.java
index 7dc5974..ce73389 100644
--- a/TestProject/src/test/PlayerTest.java
+++ b/TestProject/src/test/PlayerTest.java
@@ -1,56 +1,57 @@
package test;
import java.util.ArrayList;
import se.chalmers.dat255.risk.model.Card;
import se.chalmers.dat255.risk.model.Card.CardType;
import se.chalmers.dat255.risk.model.Deck;
import se.chalmers.dat255.risk.model.Player;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
public class PlayerTest {
@Test
public void testAddCard(){
ArrayList<String> provinces = new ArrayList<String>();
provinces.add("Hej");
provinces.add("Hejhopp");
provinces.add("Hejmamma");
Deck deck = Deck.getInstance(provinces, 3);
Player player = new Player(1, "Testare");
player.addCard();
assertTrue(player.getCards().size() == 1);
}
@Test
public void testProvinces(){
Player player = new Player(1, "Testare");
player.gainProvince();
player.gainProvince();
player.gainProvince();
player.loseProvince();
player.loseProvince();
assertTrue(player.getNrOfProvinces() == 1);
}
@Test
public void testExhangeCard(){
ArrayList<String> provinces = new ArrayList<String>();
provinces.add("Hej");
provinces.add("Hejhopp");
provinces.add("Hejmamma");
+ Deck deck = Deck.getInstance(provinces, 2);
Player player = new Player(1, "Testare");
player.addCard();
player.addCard();
player.addCard();
Card card1 = player.getCards().get(2);
Card card2 = player.getCards().get(1);
Card card3 = player.getCards().get(0);
assertTrue(player.exchangeCard(card1, card2, card3));
}
}
| true | true | public void testExhangeCard(){
ArrayList<String> provinces = new ArrayList<String>();
provinces.add("Hej");
provinces.add("Hejhopp");
provinces.add("Hejmamma");
Player player = new Player(1, "Testare");
player.addCard();
player.addCard();
player.addCard();
Card card1 = player.getCards().get(2);
Card card2 = player.getCards().get(1);
Card card3 = player.getCards().get(0);
assertTrue(player.exchangeCard(card1, card2, card3));
}
| public void testExhangeCard(){
ArrayList<String> provinces = new ArrayList<String>();
provinces.add("Hej");
provinces.add("Hejhopp");
provinces.add("Hejmamma");
Deck deck = Deck.getInstance(provinces, 2);
Player player = new Player(1, "Testare");
player.addCard();
player.addCard();
player.addCard();
Card card1 = player.getCards().get(2);
Card card2 = player.getCards().get(1);
Card card3 = player.getCards().get(0);
assertTrue(player.exchangeCard(card1, card2, card3));
}
|
diff --git a/CheckAppClient/src/com/android/task/picture/PhotoCapturer.java b/CheckAppClient/src/com/android/task/picture/PhotoCapturer.java
index 5ff9bc9..3ae9670 100755
--- a/CheckAppClient/src/com/android/task/picture/PhotoCapturer.java
+++ b/CheckAppClient/src/com/android/task/picture/PhotoCapturer.java
@@ -1,177 +1,177 @@
package com.android.task.picture;
import com.android.task.tools.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.android.task.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class PhotoCapturer extends Activity
{
private final String TAG = PhotoCapturer.class.getName();
SurfaceView sView;
SurfaceHolder surfaceHolder;
int imgWidth, imgHeight;
// ����ϵͳ���õ������
Camera camera;
//�Ƿ��������
boolean isPreview = false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// ����ȫ��
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cam_pic_layout);
sView = (SurfaceView) findViewById(R.id.pic_view);
surfaceHolder = sView.getHolder();
surfaceHolder.addCallback(new Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
public void surfaceCreated(SurfaceHolder holder)
{
// ������ͷ
initCamera();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
- Log.i(TAG,"surface destroyed");
+ Log.d(TAG,"surface destroyed");
// ���camera��Ϊnull ,�ͷ�����ͷ
if (camera != null)
{
if (isPreview)
{
camera.stopPreview();
isPreview = false;
}
camera.release();
camera = null;
}
}
});
// ���ø�SurfaceView�Լ���ά������
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// set button event
Button recBtn = (Button) findViewById(R.id.pic_rec_btn);
recBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(isPreview){
try {
// take picture and save
camera.takePicture(null, null, myPicture);
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "Error take picture: " + e.getMessage());
}
}
}
});
Button exitBtn = (Button) findViewById(R.id.pic_exit_btn);
exitBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
UploadMessage.set_upload_message(null);
PhotoCapturer.this.finish();
return;
}
});
}
private void initCamera()
{
if (!isPreview)
{
camera = Camera.open();
Log.d(TAG,"open camera");
}
if (camera != null && !isPreview)
{
try
{
CameraSetting.setCameraParameter(camera, surfaceHolder);
camera.startPreview();
camera.autoFocus(null);
}
catch (Exception e)
{
e.printStackTrace();
}
isPreview = true;
}
}
PictureCallback myPicture = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
final File picFile = Tools.getOutputMediaFile(Tools.MEDIA_TYPE_IMAGE);
if( picFile == null ){
Log.e(TAG, "Fail to generate image, check storage permission.");
return;
}
// save to file
try {
FileOutputStream fos = new FileOutputStream(picFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Error accessing file: " + e.getMessage());
Toast.makeText(PhotoCapturer.this, "������ͼ������洢����", Toast.LENGTH_SHORT).show();
}
final Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
if(bm == null) {
Log.e(TAG, "bitmap is null.");
return;
}
PhotoSaveDialog photo_save_dialog = new PhotoSaveDialog(PhotoCapturer.this,bm,picFile);
photo_save_dialog.getPhotoSaveDialog().show();
//�������
camera.stopPreview();
camera.startPreview();
isPreview = true;
}
};
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// ����ȫ��
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cam_pic_layout);
sView = (SurfaceView) findViewById(R.id.pic_view);
surfaceHolder = sView.getHolder();
surfaceHolder.addCallback(new Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
public void surfaceCreated(SurfaceHolder holder)
{
// ������ͷ
initCamera();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
Log.i(TAG,"surface destroyed");
// ���camera��Ϊnull ,�ͷ�����ͷ
if (camera != null)
{
if (isPreview)
{
camera.stopPreview();
isPreview = false;
}
camera.release();
camera = null;
}
}
});
// ���ø�SurfaceView�Լ���ά������
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// set button event
Button recBtn = (Button) findViewById(R.id.pic_rec_btn);
recBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(isPreview){
try {
// take picture and save
camera.takePicture(null, null, myPicture);
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "Error take picture: " + e.getMessage());
}
}
}
});
Button exitBtn = (Button) findViewById(R.id.pic_exit_btn);
exitBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
UploadMessage.set_upload_message(null);
PhotoCapturer.this.finish();
return;
}
});
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// ����ȫ��
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.cam_pic_layout);
sView = (SurfaceView) findViewById(R.id.pic_view);
surfaceHolder = sView.getHolder();
surfaceHolder.addCallback(new Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
}
public void surfaceCreated(SurfaceHolder holder)
{
// ������ͷ
initCamera();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
Log.d(TAG,"surface destroyed");
// ���camera��Ϊnull ,�ͷ�����ͷ
if (camera != null)
{
if (isPreview)
{
camera.stopPreview();
isPreview = false;
}
camera.release();
camera = null;
}
}
});
// ���ø�SurfaceView�Լ���ά������
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// set button event
Button recBtn = (Button) findViewById(R.id.pic_rec_btn);
recBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(isPreview){
try {
// take picture and save
camera.takePicture(null, null, myPicture);
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "Error take picture: " + e.getMessage());
}
}
}
});
Button exitBtn = (Button) findViewById(R.id.pic_exit_btn);
exitBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
UploadMessage.set_upload_message(null);
PhotoCapturer.this.finish();
return;
}
});
}
|
diff --git a/main/src/com/google/refine/expr/functions/ToString.java b/main/src/com/google/refine/expr/functions/ToString.java
index 7611b85f..ef66de61 100644
--- a/main/src/com/google/refine/expr/functions/ToString.java
+++ b/main/src/com/google/refine/expr/functions/ToString.java
@@ -1,88 +1,83 @@
/*
Copyright 2010, Google Inc.
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 Google Inc. nor the names of its
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
OWNER 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 com.google.refine.expr.functions;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONWriter;
import com.google.refine.grel.Function;
public class ToString implements Function {
public Object call(Properties bindings, Object[] args) {
if (args.length >= 1) {
Object o1 = args[0];
if (o1 != null) {
- if (o1 instanceof Date) {
- Calendar c = Calendar.getInstance();
- c.setTime((Date) o1);
- o1 = c;
- }
- if (o1 instanceof Calendar) {
+ if (o1 instanceof Calendar || o1 instanceof Date) {
DateFormat formatter = null;
if (args.length == 2) {
Object o2 = args[1];
if (o2 != null && o2 instanceof String) {
formatter = new SimpleDateFormat((String) o2);
}
}
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
- return formatter.format(((Calendar) o1).getTime());
+ return formatter.format(o1 instanceof Date ? ((Date) o1) : ((Calendar) o1).getTime());
} else {
return (o1 instanceof String) ? o1 : o1.toString();
}
}
}
return null;
}
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("description"); writer.value("Returns o converted to a string");
writer.key("params"); writer.value("o, string format (optional)");
writer.key("returns"); writer.value("string");
writer.endObject();
}
}
| false | true | public Object call(Properties bindings, Object[] args) {
if (args.length >= 1) {
Object o1 = args[0];
if (o1 != null) {
if (o1 instanceof Date) {
Calendar c = Calendar.getInstance();
c.setTime((Date) o1);
o1 = c;
}
if (o1 instanceof Calendar) {
DateFormat formatter = null;
if (args.length == 2) {
Object o2 = args[1];
if (o2 != null && o2 instanceof String) {
formatter = new SimpleDateFormat((String) o2);
}
}
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
return formatter.format(((Calendar) o1).getTime());
} else {
return (o1 instanceof String) ? o1 : o1.toString();
}
}
}
return null;
}
| public Object call(Properties bindings, Object[] args) {
if (args.length >= 1) {
Object o1 = args[0];
if (o1 != null) {
if (o1 instanceof Calendar || o1 instanceof Date) {
DateFormat formatter = null;
if (args.length == 2) {
Object o2 = args[1];
if (o2 != null && o2 instanceof String) {
formatter = new SimpleDateFormat((String) o2);
}
}
if (formatter == null) {
formatter = DateFormat.getDateInstance();
}
return formatter.format(o1 instanceof Date ? ((Date) o1) : ((Calendar) o1).getTime());
} else {
return (o1 instanceof String) ? o1 : o1.toString();
}
}
}
return null;
}
|
diff --git a/src/de/ololololo/test/DataSourceTest.java b/src/de/ololololo/test/DataSourceTest.java
index a1e4b76..5d12f1c 100644
--- a/src/de/ololololo/test/DataSourceTest.java
+++ b/src/de/ololololo/test/DataSourceTest.java
@@ -1,22 +1,22 @@
package de.ololololo.test;
import de.ololololo.*;
import java.util.*;
public class DataSourceTest {
private DataSource dataSource;
public DataSourceTest() {
}
public void main () {
-dataSource = new DataSource();
+ dataSource = DataSource.getInstance();
dataSource.printAllTasks();
dataSource.newTask("Test", new Date());
dataSource.newTask("neu 2", new Date());
dataSource.printAllTasks();
}
}
| true | true | public void main () {
dataSource = new DataSource();
dataSource.printAllTasks();
dataSource.newTask("Test", new Date());
dataSource.newTask("neu 2", new Date());
dataSource.printAllTasks();
}
| public void main () {
dataSource = DataSource.getInstance();
dataSource.printAllTasks();
dataSource.newTask("Test", new Date());
dataSource.newTask("neu 2", new Date());
dataSource.printAllTasks();
}
|
diff --git a/src/com/android/camera/ui/ScrollerView.java b/src/com/android/camera/ui/ScrollerView.java
index 37ba8c0a..0552516f 100644
--- a/src/com/android/camera/ui/ScrollerView.java
+++ b/src/com/android/camera/ui/ScrollerView.java
@@ -1,1849 +1,1851 @@
/*
* 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.camera.ui;
import android.content.Context;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.FocusFinder;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.OverScroller;
import android.widget.TextView;
import java.util.List;
/**
* Layout container for a view hierarchy that can be scrolled by the user,
* allowing it to be larger than the physical display. A ScrollView
* is a {@link FrameLayout}, meaning you should place one child in it
* containing the entire contents to scroll; this child may itself be a layout
* manager with a complex hierarchy of objects. A child that is often used
* is a {@link LinearLayout} in a vertical orientation, presenting a vertical
* array of top-level items that the user can scroll through.
*
* <p>The {@link TextView} class also
* takes care of its own scrolling, so does not require a ScrollView, but
* using the two together is possible to achieve the effect of a text view
* within a larger container.
*
* <p>ScrollView only supports vertical scrolling.
*
* @attr ref android.R.styleable#ScrollView_fillViewport
*/
public class ScrollerView extends FrameLayout {
static final int ANIMATED_SCROLL_GAP = 250;
static final float MAX_SCROLL_FACTOR = 0.5f;
private long mLastScroll;
private final Rect mTempRect = new Rect();
protected OverScroller mScroller;
/**
* Position of the last motion event.
*/
private float mLastMotionY;
/**
* True when the layout has changed but the traversal has not come through yet.
* Ideally the view hierarchy would keep track of this for us.
*/
private boolean mIsLayoutDirty = true;
/**
* The child to give focus to in the event that a child has requested focus while the
* layout is dirty. This prevents the scroll from being wrong if the child has not been
* laid out before requesting focus.
*/
protected View mChildToScrollTo = null;
/**
* True if the user is currently dragging this ScrollView around. This is
* not the same as 'is being flinged', which can be checked by
* mScroller.isFinished() (flinging begins when the user lifts his finger).
*/
protected boolean mIsBeingDragged = false;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
/**
* When set to true, the scroll view measure its child to make it fill the currently
* visible area.
*/
@ViewDebug.ExportedProperty(category = "layout")
private boolean mFillViewport;
/**
* Whether arrow scrolling is animated.
*/
private boolean mSmoothScrollingEnabled = true;
private int mTouchSlop;
protected int mMinimumVelocity;
private int mMaximumVelocity;
private int mOverscrollDistance;
private int mOverflingDistance;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
private int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* orientation of the scrollview
*/
protected boolean mHorizontal;
protected boolean mIsOrthoDragged;
private float mLastOrthoCoord;
private View mDownView;
private PointF mDownCoords;
private float mScrollFactor;
private boolean mIgnoreScroll;
public ScrollerView(Context context) {
this(context, null);
}
public ScrollerView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.scrollViewStyle);
}
public ScrollerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initScrollView();
}
private void initScrollView() {
mScroller = new OverScroller(getContext());
setFocusable(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setWillNotDraw(false);
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mOverscrollDistance = configuration.getScaledOverscrollDistance();
mOverflingDistance = configuration.getScaledOverflingDistance();
mDownCoords = new PointF();
mScrollFactor = 5;
TypedValue outValue = new TypedValue();
if (!getContext().getTheme().resolveAttribute(
android.R.attr.listPreferredItemHeight, outValue, true)) {
throw new IllegalStateException(
"Expected theme to define listPreferredItemHeight.");
}
mScrollFactor = outValue.getDimension(
getContext().getResources().getDisplayMetrics());
}
public void setOrientation(int orientation) {
mHorizontal = (orientation == LinearLayout.HORIZONTAL);
requestLayout();
}
public boolean ignoreScroll() {
return mIgnoreScroll;
}
@Override
public boolean shouldDelayChildPressedState() {
return true;
}
@Override
protected float getTopFadingEdgeStrength() {
if (getChildCount() == 0) {
return 0.0f;
}
if (mHorizontal) {
final int length = getHorizontalFadingEdgeLength();
if (getScrollX() < length) {
return getScrollX() / (float) length;
}
} else {
final int length = getVerticalFadingEdgeLength();
if (getScrollY() < length) {
return getScrollY() / (float) length;
}
}
return 1.0f;
}
@Override
protected float getBottomFadingEdgeStrength() {
if (getChildCount() == 0) {
return 0.0f;
}
if (mHorizontal) {
final int length = getHorizontalFadingEdgeLength();
final int bottomEdge = getWidth() - getPaddingRight();
final int span = getChildAt(0).getRight() - getScrollX() - bottomEdge;
if (span < length) {
return span / (float) length;
}
} else {
final int length = getVerticalFadingEdgeLength();
final int bottomEdge = getHeight() - getPaddingBottom();
final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
if (span < length) {
return span / (float) length;
}
}
return 1.0f;
}
/**
* @return The maximum amount this scroll view will scroll in response to
* an arrow event.
*/
public int getMaxScrollAmount() {
return (int) (MAX_SCROLL_FACTOR * (mHorizontal
? (getRight() - getLeft()) : (getBottom() - getTop())));
}
@Override
public void addView(View child) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(child);
}
@Override
public void addView(View child, int index) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(child, index);
}
@Override
public void addView(View child, ViewGroup.LayoutParams params) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(child, params);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (getChildCount() > 0) {
throw new IllegalStateException("ScrollView can host only one direct child");
}
super.addView(child, index, params);
}
/**
* @return Returns true this ScrollView can be scrolled
*/
private boolean canScroll() {
View child = getChildAt(0);
if (child != null) {
if (mHorizontal) {
return getWidth() < child.getWidth() + getPaddingLeft() + getPaddingRight();
} else {
return getHeight() < child.getHeight() + getPaddingTop() + getPaddingBottom();
}
}
return false;
}
/**
* Indicates whether this ScrollView's content is stretched to fill the viewport.
*
* @return True if the content fills the viewport, false otherwise.
*
* @attr ref android.R.styleable#ScrollView_fillViewport
*/
public boolean isFillViewport() {
return mFillViewport;
}
/**
* Indicates this ScrollView whether it should stretch its content height to fill
* the viewport or not.
*
* @param fillViewport True to stretch the content's height to the viewport's
* boundaries, false otherwise.
*
* @attr ref android.R.styleable#ScrollView_fillViewport
*/
public void setFillViewport(boolean fillViewport) {
if (fillViewport != mFillViewport) {
mFillViewport = fillViewport;
requestLayout();
}
}
/**
* @return Whether arrow scrolling will animate its transition.
*/
public boolean isSmoothScrollingEnabled() {
return mSmoothScrollingEnabled;
}
/**
* Set whether arrow scrolling will animate its transition.
* @param smoothScrollingEnabled whether arrow scrolling will animate its transition
*/
public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
mSmoothScrollingEnabled = smoothScrollingEnabled;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!mFillViewport) {
return;
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode == MeasureSpec.UNSPECIFIED) {
return;
}
if (getChildCount() > 0) {
final View child = getChildAt(0);
if (mHorizontal) {
int width = getMeasuredWidth();
if (child.getMeasuredWidth() < width) {
final FrameLayout.LayoutParams lp = (LayoutParams) child
.getLayoutParams();
int childHeightMeasureSpec = getChildMeasureSpec(
heightMeasureSpec, getPaddingTop() + getPaddingBottom(),
lp.height);
width -= getPaddingLeft();
width -= getPaddingRight();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
} else {
int height = getMeasuredHeight();
if (child.getMeasuredHeight() < height) {
final FrameLayout.LayoutParams lp = (LayoutParams) child
.getLayoutParams();
int childWidthMeasureSpec = getChildMeasureSpec(
widthMeasureSpec, getPaddingLeft() + getPaddingRight(),
lp.width);
height -= getPaddingTop();
height -= getPaddingBottom();
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
/**
* You can call this function yourself to have the scroll view perform
* scrolling from a key event, just as if the event had been dispatched to
* it by the view hierarchy.
*
* @param event The key event to execute.
* @return Return true if the event was handled, else false.
*/
public boolean executeKeyEvent(KeyEvent event) {
mTempRect.setEmpty();
if (!canScroll()) {
if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
View nextFocused = FocusFinder.getInstance().findNextFocus(this,
currentFocused, View.FOCUS_DOWN);
return nextFocused != null
&& nextFocused != this
&& nextFocused.requestFocus(View.FOCUS_DOWN);
}
return false;
}
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_UP);
} else {
handled = fullScroll(View.FOCUS_UP);
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_DOWN);
} else {
handled = fullScroll(View.FOCUS_DOWN);
}
break;
case KeyEvent.KEYCODE_SPACE:
pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
break;
}
}
return handled;
}
private boolean inChild(int x, int y) {
if (getChildCount() > 0) {
final int scrollY = getScrollY();
final View child = getChildAt(0);
return !(y < child.getTop() - scrollY
|| y >= child.getBottom() - scrollY
|| x < child.getLeft()
|| x >= child.getRight());
}
return false;
}
private void initOrResetVelocityTracker() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
}
private void initVelocityTrackerIfNotExists() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
}
private void recycleVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept) {
recycleVelocityTracker();
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onMotionEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging state
* and he is moving his finger. We want to intercept this motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
return true;
}
if ((action == MotionEvent.ACTION_MOVE) && (mIsOrthoDragged)) {
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have
* caught it. Check whether the user has moved far enough from his
* original down touch.
*/
/*
* Locally do absolute value. mLastMotionY is set to the y value of
* the down event.
*/
final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
// If we don't have a valid id, the touch down wasn't on
// content.
break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId);
final float y = mHorizontal ? ev.getX(pointerIndex) : ev
.getY(pointerIndex);
final int yDiff = (int) Math.abs(y - mLastMotionY);
if (yDiff > mTouchSlop) {
mIsBeingDragged = true;
mLastMotionY = y;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
} else {
final float ocoord = mHorizontal ? ev.getY(pointerIndex) : ev
.getX(pointerIndex);
if (Math.abs(ocoord - mLastOrthoCoord) > mTouchSlop) {
mIsOrthoDragged = true;
mLastOrthoCoord = ocoord;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
final float y = mHorizontal ? ev.getX() : ev.getY();
mDownCoords.x = ev.getX();
mDownCoords.y = ev.getY();
if (!inChild((int) ev.getX(), (int) ev.getY())) {
mIsBeingDragged = false;
recycleVelocityTracker();
break;
}
/*
* Remember location of down touch. ACTION_DOWN always refers to
* pointer index 0.
*/
mLastMotionY = y;
mActivePointerId = ev.getPointerId(0);
initOrResetVelocityTracker();
mVelocityTracker.addMovement(ev);
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when being
* flinged.
*/
mIsBeingDragged = !mScroller.isFinished();
mIsOrthoDragged = false;
final float ocoord = mHorizontal ? ev.getY() : ev.getX();
mLastOrthoCoord = ocoord;
mDownView = findViewAt((int) ev.getX(), (int) ev.getY());
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
onScrollUp();
}
/* Release the drag */
mIsBeingDragged = false;
mIsOrthoDragged = false;
mActivePointerId = INVALID_POINTER;
recycleVelocityTracker();
// TODO: this upset the single tap; need to fix later
//if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
// getScrollRange())) {
// invalidate();
//}
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mIsBeingDragged || mIsOrthoDragged;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mIsBeingDragged = getChildCount() != 0;
if (!mIsBeingDragged) {
return false;
}
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionY = mHorizontal ? ev.getX() : ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
if (mIsOrthoDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(activePointerIndex);
final float y = ev.getY(activePointerIndex);
if (isOrthoMove(x - mDownCoords.x, y - mDownCoords.y)) {
onOrthoDrag(mDownView, mHorizontal
? y - mDownCoords.y
: x - mDownCoords.x);
}
} else if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float y = mHorizontal ? ev.getX(activePointerIndex)
: ev.getY(activePointerIndex);
final int deltaY = (int) (mLastMotionY - y);
mLastMotionY = y;
final int oldX = getScrollX();
final int oldY = getScrollY();
final int range = getScrollRange();
if (mHorizontal) {
if (overScrollBy(deltaY, 0, getScrollX(), 0, range, 0,
mOverscrollDistance, 0, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
} else {
if (overScrollBy(0, deltaY, 0, getScrollY(), 0, range,
0, mOverscrollDistance, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
}
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
final int overscrollMode = getOverScrollMode();
if (overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
final int pulledToY = mHorizontal ? oldX + deltaY : oldY + deltaY;
if (pulledToY < 0) {
onPull(pulledToY);
} else if (pulledToY > range) {
onPull(pulledToY - range);
} else {
onPull(0);
}
}
} else {
return false;
}
break;
case MotionEvent.ACTION_UP:
final VelocityTracker vtracker = mVelocityTracker;
vtracker.computeCurrentVelocity(1000, mMaximumVelocity);
if (isOrthoMove(vtracker.getXVelocity(mActivePointerId),
vtracker.getYVelocity(mActivePointerId))
&& mMinimumVelocity < Math.abs((mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity()))) {
onOrthoFling(mDownView, mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity());
break;
}
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = mHorizontal
? (int) velocityTracker.getXVelocity(mActivePointerId)
: (int) velocityTracker.getYVelocity(mActivePointerId);
if (getChildCount() > 0) {
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
fling(-initialVelocity);
} else {
final int bottom = getScrollRange();
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, bottom, 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, bottom)) {
invalidate();
}
}
onScrollUp();
}
onPull(0);
}
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged && getChildCount() > 0) {
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, getScrollRange(), 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
invalidate();
}
}
+ // when touch is cancelled, treat it as up to allow icons to snap back
+ onScrollUp();
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
final float y = mHorizontal ? ev.getX(index) : ev.getY(index);
mLastMotionY = y;
mLastOrthoCoord = mHorizontal ? ev.getY(index) : ev.getX(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = mHorizontal
? ev.getX(ev.findPointerIndex(mActivePointerId))
: ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
return true;
}
protected void onScrollUp() {
}
protected View findViewAt(int x, int y) {
// subclass responsibility
return null;
}
protected void onPull(int delta) {
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionY = mHorizontal ? ev.getX(newPointerIndex) : ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
mLastOrthoCoord = mHorizontal ? ev.getY(newPointerIndex)
: ev.getX(newPointerIndex);
}
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL: {
if (!mIsBeingDragged) {
if (mHorizontal) {
final float hscroll = event
.getAxisValue(MotionEvent.AXIS_HSCROLL);
if (hscroll != 0) {
final int delta = (int) (hscroll * mScrollFactor);
final int range = getScrollRange();
int oldScrollX = getScrollX();
int newScrollX = oldScrollX - delta;
if (newScrollX < 0) {
newScrollX = 0;
} else if (newScrollX > range) {
newScrollX = range;
}
if (newScrollX != oldScrollX) {
super.scrollTo(newScrollX, getScrollY());
return true;
}
}
} else {
final float vscroll = event
.getAxisValue(MotionEvent.AXIS_VSCROLL);
if (vscroll != 0) {
final int delta = (int) (vscroll * mScrollFactor);
final int range = getScrollRange();
int oldScrollY = getScrollY();
int newScrollY = oldScrollY - delta;
if (newScrollY < 0) {
newScrollY = 0;
} else if (newScrollY > range) {
newScrollY = range;
}
if (newScrollY != oldScrollY) {
super.scrollTo(getScrollX(), newScrollY);
return true;
}
}
}
}
}
}
}
return super.onGenericMotionEvent(event);
}
protected void onOrthoDrag(View draggedView, float distance) {
}
protected void onOrthoDragFinished(View draggedView) {
}
protected void onOrthoFling(View draggedView, float velocity) {
}
@Override
protected void onOverScrolled(int scrollX, int scrollY,
boolean clampedX, boolean clampedY) {
// Treat animating scrolls differently; see #computeScroll() for why.
if (!mScroller.isFinished()) {
// workaround
// need to do this because can't set scroll offset before API 14
mIgnoreScroll = true;
super.scrollTo(scrollX, scrollY);
mIgnoreScroll = false;
// original code:
// mScrollX = scrollX;
// mScrollY = scrollY;
// invalidateParentIfNeeded();
if (mHorizontal && clampedX) {
mScroller.springBack(getScrollX(), getScrollY(), 0, getScrollRange(), 0, 0);
} else if (!mHorizontal && clampedY) {
mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange());
}
} else {
super.scrollTo(scrollX, scrollY);
}
awakenScrollBars();
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setScrollable(true);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setScrollable(true);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
// Do not append text content to scroll events they are fired frequently
// and the client has already received another event type with the text.
if (event.getEventType() != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
super.dispatchPopulateAccessibilityEvent(event);
}
return false;
}
private int getScrollRange() {
int scrollRange = 0;
if (getChildCount() > 0) {
View child = getChildAt(0);
if (mHorizontal) {
scrollRange = Math.max(0,
child.getWidth() - (getWidth() - getPaddingRight() - getPaddingLeft()));
} else {
scrollRange = Math.max(0,
child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop()));
}
}
return scrollRange;
}
/**
* <p>
* Finds the next focusable component that fits in this View's bounds
* (excluding fading edges) pretending that this View's top is located at
* the parameter top.
* </p>
*
* @param topFocus look for a candidate at the top of the bounds if topFocus is true,
* or at the bottom of the bounds if topFocus is false
* @param top the top offset of the bounds in which a focusable must be
* found (the fading edge is assumed to start at this position)
* @param preferredFocusable the View that has highest priority and will be
* returned if it is within my bounds (null is valid)
* @return the next focusable component in the bounds or null if none can be found
*/
private View findFocusableViewInMyBounds(final boolean topFocus,
final int top, View preferredFocusable) {
/*
* The fading edge's transparent side should be considered for focus
* since it's mostly visible, so we divide the actual fading edge length
* by 2.
*/
final int fadingEdgeLength = (mHorizontal
? getHorizontalFadingEdgeLength()
: getVerticalFadingEdgeLength()) / 2;
final int topWithoutFadingEdge = top + fadingEdgeLength;
final int bottomWithoutFadingEdge = top + (mHorizontal ? getWidth() : getHeight()) - fadingEdgeLength;
if ((preferredFocusable != null)
&& ((mHorizontal ? preferredFocusable.getLeft() : preferredFocusable.getTop())
< bottomWithoutFadingEdge)
&& ((mHorizontal ? preferredFocusable.getRight() : preferredFocusable.getBottom()) > topWithoutFadingEdge)) {
return preferredFocusable;
}
return findFocusableViewInBounds(topFocus, topWithoutFadingEdge,
bottomWithoutFadingEdge);
}
/**
* <p>
* Finds the next focusable component that fits in the specified bounds.
* </p>
*
* @param topFocus look for a candidate is the one at the top of the bounds
* if topFocus is true, or at the bottom of the bounds if topFocus is
* false
* @param top the top offset of the bounds in which a focusable must be
* found
* @param bottom the bottom offset of the bounds in which a focusable must
* be found
* @return the next focusable component in the bounds or null if none can
* be found
*/
private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
List<View> focusables = getFocusables(View.FOCUS_FORWARD);
View focusCandidate = null;
/*
* A fully contained focusable is one where its top is below the bound's
* top, and its bottom is above the bound's bottom. A partially
* contained focusable is one where some part of it is within the
* bounds, but it also has some part that is not within bounds. A fully contained
* focusable is preferred to a partially contained focusable.
*/
boolean foundFullyContainedFocusable = false;
int count = focusables.size();
for (int i = 0; i < count; i++) {
View view = focusables.get(i);
int viewTop = mHorizontal ? view.getLeft() : view.getTop();
int viewBottom = mHorizontal ? view.getRight() : view.getBottom();
if (top < viewBottom && viewTop < bottom) {
/*
* the focusable is in the target area, it is a candidate for
* focusing
*/
final boolean viewIsFullyContained = (top < viewTop) &&
(viewBottom < bottom);
if (focusCandidate == null) {
/* No candidate, take this one */
focusCandidate = view;
foundFullyContainedFocusable = viewIsFullyContained;
} else {
final int ctop = mHorizontal ? focusCandidate.getLeft() : focusCandidate.getTop();
final int cbot = mHorizontal ? focusCandidate.getRight() : focusCandidate.getBottom();
final boolean viewIsCloserToBoundary =
(topFocus && viewTop < ctop) ||
(!topFocus && viewBottom > cbot);
if (foundFullyContainedFocusable) {
if (viewIsFullyContained && viewIsCloserToBoundary) {
/*
* We're dealing with only fully contained views, so
* it has to be closer to the boundary to beat our
* candidate
*/
focusCandidate = view;
}
} else {
if (viewIsFullyContained) {
/* Any fully contained view beats a partially contained view */
focusCandidate = view;
foundFullyContainedFocusable = true;
} else if (viewIsCloserToBoundary) {
/*
* Partially contained view beats another partially
* contained view if it's closer
*/
focusCandidate = view;
}
}
}
}
}
return focusCandidate;
}
// i was here
/**
* <p>Handles scrolling in response to a "page up/down" shortcut press. This
* method will scroll the view by one page up or down and give the focus
* to the topmost/bottommost component in the new visible area. If no
* component is a good candidate for focus, this scrollview reclaims the
* focus.</p>
*
* @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
* to go one page up or
* {@link android.view.View#FOCUS_DOWN} to go one page down
* @return true if the key event is consumed by this method, false otherwise
*/
public boolean pageScroll(int direction) {
boolean down = direction == View.FOCUS_DOWN;
int height = getHeight();
if (down) {
mTempRect.top = getScrollY() + height;
int count = getChildCount();
if (count > 0) {
View view = getChildAt(count - 1);
if (mTempRect.top + height > view.getBottom()) {
mTempRect.top = view.getBottom() - height;
}
}
} else {
mTempRect.top = getScrollY() - height;
if (mTempRect.top < 0) {
mTempRect.top = 0;
}
}
mTempRect.bottom = mTempRect.top + height;
return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
}
/**
* <p>Handles scrolling in response to a "home/end" shortcut press. This
* method will scroll the view to the top or bottom and give the focus
* to the topmost/bottommost component in the new visible area. If no
* component is a good candidate for focus, this scrollview reclaims the
* focus.</p>
*
* @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
* to go the top of the view or
* {@link android.view.View#FOCUS_DOWN} to go the bottom
* @return true if the key event is consumed by this method, false otherwise
*/
public boolean fullScroll(int direction) {
boolean down = direction == View.FOCUS_DOWN;
int height = getHeight();
mTempRect.top = 0;
mTempRect.bottom = height;
if (down) {
int count = getChildCount();
if (count > 0) {
View view = getChildAt(count - 1);
mTempRect.bottom = view.getBottom() + getPaddingBottom();
mTempRect.top = mTempRect.bottom - height;
}
}
return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
}
/**
* <p>Scrolls the view to make the area defined by <code>top</code> and
* <code>bottom</code> visible. This method attempts to give the focus
* to a component visible in this area. If no component can be focused in
* the new visible area, the focus is reclaimed by this ScrollView.</p>
*
* @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
* to go upward, {@link android.view.View#FOCUS_DOWN} to downward
* @param top the top offset of the new area to be made visible
* @param bottom the bottom offset of the new area to be made visible
* @return true if the key event is consumed by this method, false otherwise
*/
private boolean scrollAndFocus(int direction, int top, int bottom) {
boolean handled = true;
int height = getHeight();
int containerTop = getScrollY();
int containerBottom = containerTop + height;
boolean up = direction == View.FOCUS_UP;
View newFocused = findFocusableViewInBounds(up, top, bottom);
if (newFocused == null) {
newFocused = this;
}
if (top >= containerTop && bottom <= containerBottom) {
handled = false;
} else {
int delta = up ? (top - containerTop) : (bottom - containerBottom);
doScrollY(delta);
}
if (newFocused != findFocus()) newFocused.requestFocus(direction);
return handled;
}
/**
* Handle scrolling in response to an up or down arrow click.
*
* @param direction The direction corresponding to the arrow key that was
* pressed
* @return True if we consumed the event, false otherwise
*/
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
final int maxJump = getMaxScrollAmount();
if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
nextFocused.getDrawingRect(mTempRect);
offsetDescendantRectToMyCoords(nextFocused, mTempRect);
int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
doScrollY(scrollDelta);
nextFocused.requestFocus(direction);
} else {
// no new focus
int scrollDelta = maxJump;
if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
scrollDelta = getScrollY();
} else if (direction == View.FOCUS_DOWN) {
if (getChildCount() > 0) {
int daBottom = getChildAt(0).getBottom();
int screenBottom = getScrollY() + getHeight() - getPaddingBottom();
if (daBottom - screenBottom < maxJump) {
scrollDelta = daBottom - screenBottom;
}
}
}
if (scrollDelta == 0) {
return false;
}
doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
}
if (currentFocused != null && currentFocused.isFocused()
&& isOffScreen(currentFocused)) {
// previously focused item still has focus and is off screen, give
// it up (take it back to ourselves)
// (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
// sure to
// get it)
final int descendantFocusability = getDescendantFocusability(); // save
setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
requestFocus();
setDescendantFocusability(descendantFocusability); // restore
}
return true;
}
private boolean isOrthoMove(float moveX, float moveY) {
return mHorizontal && Math.abs(moveY) > Math.abs(moveX)
|| !mHorizontal && Math.abs(moveX) > Math.abs(moveY);
}
/**
* @return whether the descendant of this scroll view is scrolled off
* screen.
*/
private boolean isOffScreen(View descendant) {
if (mHorizontal) {
return !isWithinDeltaOfScreen(descendant, getWidth(), 0);
} else {
return !isWithinDeltaOfScreen(descendant, 0, getHeight());
}
}
/**
* @return whether the descendant of this scroll view is within delta
* pixels of being on the screen.
*/
private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
descendant.getDrawingRect(mTempRect);
offsetDescendantRectToMyCoords(descendant, mTempRect);
if (mHorizontal) {
return (mTempRect.right + delta) >= getScrollX()
&& (mTempRect.left - delta) <= (getScrollX() + height);
} else {
return (mTempRect.bottom + delta) >= getScrollY()
&& (mTempRect.top - delta) <= (getScrollY() + height);
}
}
/**
* Smooth scroll by a Y delta
*
* @param delta the number of pixels to scroll by on the Y axis
*/
private void doScrollY(int delta) {
if (delta != 0) {
if (mSmoothScrollingEnabled) {
if (mHorizontal) {
smoothScrollBy(0, delta);
} else {
smoothScrollBy(delta, 0);
}
} else {
if (mHorizontal) {
scrollBy(0, delta);
} else {
scrollBy(delta, 0);
}
}
}
}
/**
* Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
*
* @param dx the number of pixels to scroll by on the X axis
* @param dy the number of pixels to scroll by on the Y axis
*/
public final void smoothScrollBy(int dx, int dy) {
if (getChildCount() == 0) {
// Nothing to do.
return;
}
long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
if (duration > ANIMATED_SCROLL_GAP) {
if (mHorizontal) {
final int width = getWidth() - getPaddingRight() - getPaddingLeft();
final int right = getChildAt(0).getWidth();
final int maxX = Math.max(0, right - width);
final int scrollX = getScrollX();
dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX;
mScroller.startScroll(scrollX, getScrollY(), dx, 0);
} else {
final int height = getHeight() - getPaddingBottom() - getPaddingTop();
final int bottom = getChildAt(0).getHeight();
final int maxY = Math.max(0, bottom - height);
final int scrollY = getScrollY();
dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
mScroller.startScroll(getScrollX(), scrollY, 0, dy);
}
invalidate();
} else {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
scrollBy(dx, dy);
}
mLastScroll = AnimationUtils.currentAnimationTimeMillis();
}
/**
* Like {@link #scrollTo}, but scroll smoothly instead of immediately.
*
* @param x the position where to scroll on the X axis
* @param y the position where to scroll on the Y axis
*/
public final void smoothScrollTo(int x, int y) {
smoothScrollBy(x - getScrollX(), y - getScrollY());
}
/**
* <p>
* The scroll range of a scroll view is the overall height of all of its
* children.
* </p>
*/
@Override
protected int computeVerticalScrollRange() {
if (mHorizontal) {
return super.computeVerticalScrollRange();
}
final int count = getChildCount();
final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop();
if (count == 0) {
return contentHeight;
}
int scrollRange = getChildAt(0).getBottom();
final int scrollY = getScrollY();
final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
if (scrollY < 0) {
scrollRange -= scrollY;
} else if (scrollY > overscrollBottom) {
scrollRange += scrollY - overscrollBottom;
}
return scrollRange;
}
/**
* <p>
* The scroll range of a scroll view is the overall height of all of its
* children.
* </p>
*/
@Override
protected int computeHorizontalScrollRange() {
if (!mHorizontal) {
return super.computeHorizontalScrollRange();
}
final int count = getChildCount();
final int contentWidth = getWidth() - getPaddingRight() - getPaddingLeft();
if (count == 0) {
return contentWidth;
}
int scrollRange = getChildAt(0).getRight();
final int scrollX = getScrollX();
final int overscrollBottom = Math.max(0, scrollRange - contentWidth);
if (scrollX < 0) {
scrollRange -= scrollX;
} else if (scrollX > overscrollBottom) {
scrollRange += scrollX - overscrollBottom;
}
return scrollRange;
}
@Override
protected int computeVerticalScrollOffset() {
return Math.max(0, super.computeVerticalScrollOffset());
}
@Override
protected int computeHorizontalScrollOffset() {
return Math.max(0, super.computeHorizontalScrollOffset());
}
@Override
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
ViewGroup.LayoutParams lp = child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
if (mHorizontal) {
childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, getPaddingTop()
+ getPaddingBottom(), lp.height);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
} else {
childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft()
+ getPaddingRight(), lp.width);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
if (mHorizontal) {
childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);
} else {
childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
// This is called at drawing time by ViewGroup. We don't want to
// re-show the scrollbars at this point, which scrollTo will do,
// so we replicate most of scrollTo here.
//
// It's a little odd to call onScrollChanged from inside the drawing.
//
// It is, except when you remember that computeScroll() is used to
// animate scrolling. So unless we want to defer the onScrollChanged()
// until the end of the animated scrolling, we don't really have a
// choice here.
//
// I agree. The alternative, which I think would be worse, is to post
// something and tell the subclasses later. This is bad because there
// will be a window where getScrollX()/Y is different from what the app
// thinks it is.
//
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
if (mHorizontal) {
overScrollBy(x - oldX, y - oldY, oldX, oldY, getScrollRange(), 0,
mOverflingDistance, 0, false);
} else {
overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(),
0, mOverflingDistance, false);
}
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
}
awakenScrollBars();
// Keep on drawing until the animation has finished.
postInvalidate();
}
}
/**
* Scrolls the view to the given child.
*
* @param child the View to scroll to
*/
private void scrollToChild(View child) {
child.getDrawingRect(mTempRect);
/* Offset from child's local coordinates to ScrollView coordinates */
offsetDescendantRectToMyCoords(child, mTempRect);
scrollToChildRect(mTempRect, true);
}
/**
* If rect is off screen, scroll just enough to get it (or at least the
* first screen size chunk of it) on screen.
*
* @param rect The rectangle.
* @param immediate True to scroll immediately without animation
* @return true if scrolling was performed
*/
private boolean scrollToChildRect(Rect rect, boolean immediate) {
final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
final boolean scroll = delta != 0;
if (scroll) {
if (immediate) {
if (mHorizontal) {
scrollBy(delta, 0);
} else {
scrollBy(0, delta);
}
} else {
if (mHorizontal) {
smoothScrollBy(delta, 0);
} else {
smoothScrollBy(0, delta);
}
}
}
return scroll;
}
/**
* Compute the amount to scroll in the Y direction in order to get
* a rectangle completely on the screen (or, if taller than the screen,
* at least the first screen size chunk of it).
*
* @param rect The rect.
* @return The scroll delta.
*/
protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
if (mHorizontal) {
return computeScrollDeltaToGetChildRectOnScreenHorizontal(rect);
} else {
return computeScrollDeltaToGetChildRectOnScreenVertical(rect);
}
}
private int computeScrollDeltaToGetChildRectOnScreenVertical(Rect rect) {
if (getChildCount() == 0) return 0;
int height = getHeight();
int screenTop = getScrollY();
int screenBottom = screenTop + height;
int fadingEdge = getVerticalFadingEdgeLength();
// leave room for top fading edge as long as rect isn't at very top
if (rect.top > 0) {
screenTop += fadingEdge;
}
// leave room for bottom fading edge as long as rect isn't at very bottom
if (rect.bottom < getChildAt(0).getHeight()) {
screenBottom -= fadingEdge;
}
int scrollYDelta = 0;
if (rect.bottom > screenBottom && rect.top > screenTop) {
// need to move down to get it in view: move down just enough so
// that the entire rectangle is in view (or at least the first
// screen size chunk).
if (rect.height() > height) {
// just enough to get screen size chunk on
scrollYDelta += (rect.top - screenTop);
} else {
// get entire rect at bottom of screen
scrollYDelta += (rect.bottom - screenBottom);
}
// make sure we aren't scrolling beyond the end of our content
int bottom = getChildAt(0).getBottom();
int distanceToBottom = bottom - screenBottom;
scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
} else if (rect.top < screenTop && rect.bottom < screenBottom) {
// need to move up to get it in view: move up just enough so that
// entire rectangle is in view (or at least the first screen
// size chunk of it).
if (rect.height() > height) {
// screen size chunk
scrollYDelta -= (screenBottom - rect.bottom);
} else {
// entire rect at top
scrollYDelta -= (screenTop - rect.top);
}
// make sure we aren't scrolling any further than the top our content
scrollYDelta = Math.max(scrollYDelta, -getScrollY());
}
return scrollYDelta;
}
private int computeScrollDeltaToGetChildRectOnScreenHorizontal(Rect rect) {
if (getChildCount() == 0) return 0;
int width = getWidth();
int screenLeft = getScrollX();
int screenRight = screenLeft + width;
int fadingEdge = getHorizontalFadingEdgeLength();
// leave room for left fading edge as long as rect isn't at very left
if (rect.left > 0) {
screenLeft += fadingEdge;
}
// leave room for right fading edge as long as rect isn't at very right
if (rect.right < getChildAt(0).getWidth()) {
screenRight -= fadingEdge;
}
int scrollXDelta = 0;
if (rect.right > screenRight && rect.left > screenLeft) {
// need to move right to get it in view: move right just enough so
// that the entire rectangle is in view (or at least the first
// screen size chunk).
if (rect.width() > width) {
// just enough to get screen size chunk on
scrollXDelta += (rect.left - screenLeft);
} else {
// get entire rect at right of screen
scrollXDelta += (rect.right - screenRight);
}
// make sure we aren't scrolling beyond the end of our content
int right = getChildAt(0).getRight();
int distanceToRight = right - screenRight;
scrollXDelta = Math.min(scrollXDelta, distanceToRight);
} else if (rect.left < screenLeft && rect.right < screenRight) {
// need to move right to get it in view: move right just enough so that
// entire rectangle is in view (or at least the first screen
// size chunk of it).
if (rect.width() > width) {
// screen size chunk
scrollXDelta -= (screenRight - rect.right);
} else {
// entire rect at left
scrollXDelta -= (screenLeft - rect.left);
}
// make sure we aren't scrolling any further than the left our content
scrollXDelta = Math.max(scrollXDelta, -getScrollX());
}
return scrollXDelta;
}
@Override
public void requestChildFocus(View child, View focused) {
if (!mIsLayoutDirty) {
scrollToChild(focused);
} else {
// The child may not be laid out yet, we can't compute the scroll yet
mChildToScrollTo = focused;
}
super.requestChildFocus(child, focused);
}
/**
* When looking for focus in children of a scroll view, need to be a little
* more careful not to give focus to something that is scrolled off screen.
*
* This is more expensive than the default {@link android.view.ViewGroup}
* implementation, otherwise this behavior might have been made the default.
*/
@Override
protected boolean onRequestFocusInDescendants(int direction,
Rect previouslyFocusedRect) {
// convert from forward / backward notation to up / down / left / right
// (ugh).
if (mHorizontal) {
if (direction == View.FOCUS_FORWARD) {
direction = View.FOCUS_RIGHT;
} else if (direction == View.FOCUS_BACKWARD) {
direction = View.FOCUS_LEFT;
}
} else {
if (direction == View.FOCUS_FORWARD) {
direction = View.FOCUS_DOWN;
} else if (direction == View.FOCUS_BACKWARD) {
direction = View.FOCUS_UP;
}
}
final View nextFocus = previouslyFocusedRect == null ?
FocusFinder.getInstance().findNextFocus(this, null, direction) :
FocusFinder.getInstance().findNextFocusFromRect(this,
previouslyFocusedRect, direction);
if (nextFocus == null) {
return false;
}
if (isOffScreen(nextFocus)) {
return false;
}
return nextFocus.requestFocus(direction, previouslyFocusedRect);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
boolean immediate) {
// offset into coordinate space of this scroll view
rectangle.offset(child.getLeft() - child.getScrollX(),
child.getTop() - child.getScrollY());
return scrollToChildRect(rectangle, immediate);
}
@Override
public void requestLayout() {
mIsLayoutDirty = true;
super.requestLayout();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mIsLayoutDirty = false;
// Give a child focus if it needs it
if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
scrollToChild(mChildToScrollTo);
}
mChildToScrollTo = null;
// Calling this with the present values causes it to re-clam them
scrollTo(getScrollX(), getScrollY());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
View currentFocused = findFocus();
if (null == currentFocused || this == currentFocused)
return;
// If the currently-focused view was visible on the screen when the
// screen was at the old height, then scroll the screen to make that
// view visible with the new screen height.
if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
currentFocused.getDrawingRect(mTempRect);
offsetDescendantRectToMyCoords(currentFocused, mTempRect);
int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
doScrollY(scrollDelta);
}
}
/**
* Return true if child is an descendant of parent, (or equal to the parent).
*/
private boolean isViewDescendantOf(View child, View parent) {
if (child == parent) {
return true;
}
final ViewParent theParent = child.getParent();
return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
}
/**
* Fling the scroll view
*
* @param velocityY The initial velocity in the Y direction. Positive
* numbers mean that the finger/cursor is moving down the screen,
* which means we want to scroll towards the top.
*/
public void fling(int velocityY) {
if (getChildCount() > 0) {
if (mHorizontal) {
int width = getWidth() - getPaddingRight() - getPaddingLeft();
int right = getChildAt(0).getWidth();
mScroller.fling(getScrollX(), getScrollY(), velocityY, 0,
0, Math.max(0, right - width), 0, 0, width/2, 0);
} else {
int height = getHeight() - getPaddingBottom() - getPaddingTop();
int bottom = getChildAt(0).getHeight();
mScroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0,
Math.max(0, bottom - height), 0, height/2);
}
invalidate();
}
}
private void endDrag() {
mIsBeingDragged = false;
mIsOrthoDragged = false;
mDownView = null;
recycleVelocityTracker();
}
/**
* {@inheritDoc}
*
* <p>This version also clamps the scrolling to the bounds of our child.
*/
@Override
public void scrollTo(int x, int y) {
// we rely on the fact the View.scrollBy calls scrollTo.
if (getChildCount() > 0) {
View child = getChildAt(0);
x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth());
y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight());
if (x != getScrollX() || y != getScrollY()) {
super.scrollTo(x, y);
}
}
}
private int clamp(int n, int my, int child) {
if (my >= child || n < 0) {
/* my >= child is this case:
* |--------------- me ---------------|
* |------ child ------|
* or
* |--------------- me ---------------|
* |------ child ------|
* or
* |--------------- me ---------------|
* |------ child ------|
*
* n < 0 is this case:
* |------ me ------|
* |-------- child --------|
* |-- mScrollX --|
*/
return 0;
}
if ((my+n) > child) {
/* this case:
* |------ me ------|
* |------ child ------|
* |-- mScrollX --|
*/
return child-my;
}
return n;
}
}
| true | true | public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mIsBeingDragged = getChildCount() != 0;
if (!mIsBeingDragged) {
return false;
}
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionY = mHorizontal ? ev.getX() : ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
if (mIsOrthoDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(activePointerIndex);
final float y = ev.getY(activePointerIndex);
if (isOrthoMove(x - mDownCoords.x, y - mDownCoords.y)) {
onOrthoDrag(mDownView, mHorizontal
? y - mDownCoords.y
: x - mDownCoords.x);
}
} else if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float y = mHorizontal ? ev.getX(activePointerIndex)
: ev.getY(activePointerIndex);
final int deltaY = (int) (mLastMotionY - y);
mLastMotionY = y;
final int oldX = getScrollX();
final int oldY = getScrollY();
final int range = getScrollRange();
if (mHorizontal) {
if (overScrollBy(deltaY, 0, getScrollX(), 0, range, 0,
mOverscrollDistance, 0, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
} else {
if (overScrollBy(0, deltaY, 0, getScrollY(), 0, range,
0, mOverscrollDistance, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
}
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
final int overscrollMode = getOverScrollMode();
if (overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
final int pulledToY = mHorizontal ? oldX + deltaY : oldY + deltaY;
if (pulledToY < 0) {
onPull(pulledToY);
} else if (pulledToY > range) {
onPull(pulledToY - range);
} else {
onPull(0);
}
}
} else {
return false;
}
break;
case MotionEvent.ACTION_UP:
final VelocityTracker vtracker = mVelocityTracker;
vtracker.computeCurrentVelocity(1000, mMaximumVelocity);
if (isOrthoMove(vtracker.getXVelocity(mActivePointerId),
vtracker.getYVelocity(mActivePointerId))
&& mMinimumVelocity < Math.abs((mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity()))) {
onOrthoFling(mDownView, mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity());
break;
}
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = mHorizontal
? (int) velocityTracker.getXVelocity(mActivePointerId)
: (int) velocityTracker.getYVelocity(mActivePointerId);
if (getChildCount() > 0) {
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
fling(-initialVelocity);
} else {
final int bottom = getScrollRange();
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, bottom, 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, bottom)) {
invalidate();
}
}
onScrollUp();
}
onPull(0);
}
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged && getChildCount() > 0) {
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, getScrollRange(), 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
invalidate();
}
}
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
final float y = mHorizontal ? ev.getX(index) : ev.getY(index);
mLastMotionY = y;
mLastOrthoCoord = mHorizontal ? ev.getY(index) : ev.getX(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = mHorizontal
? ev.getX(ev.findPointerIndex(mActivePointerId))
: ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
return true;
}
| public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
mIsBeingDragged = getChildCount() != 0;
if (!mIsBeingDragged) {
return false;
}
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionY = mHorizontal ? ev.getX() : ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
if (mIsOrthoDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(activePointerIndex);
final float y = ev.getY(activePointerIndex);
if (isOrthoMove(x - mDownCoords.x, y - mDownCoords.y)) {
onOrthoDrag(mDownView, mHorizontal
? y - mDownCoords.y
: x - mDownCoords.x);
}
} else if (mIsBeingDragged) {
// Scroll to follow the motion event
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
final float y = mHorizontal ? ev.getX(activePointerIndex)
: ev.getY(activePointerIndex);
final int deltaY = (int) (mLastMotionY - y);
mLastMotionY = y;
final int oldX = getScrollX();
final int oldY = getScrollY();
final int range = getScrollRange();
if (mHorizontal) {
if (overScrollBy(deltaY, 0, getScrollX(), 0, range, 0,
mOverscrollDistance, 0, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
} else {
if (overScrollBy(0, deltaY, 0, getScrollY(), 0, range,
0, mOverscrollDistance, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
}
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
final int overscrollMode = getOverScrollMode();
if (overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
final int pulledToY = mHorizontal ? oldX + deltaY : oldY + deltaY;
if (pulledToY < 0) {
onPull(pulledToY);
} else if (pulledToY > range) {
onPull(pulledToY - range);
} else {
onPull(0);
}
}
} else {
return false;
}
break;
case MotionEvent.ACTION_UP:
final VelocityTracker vtracker = mVelocityTracker;
vtracker.computeCurrentVelocity(1000, mMaximumVelocity);
if (isOrthoMove(vtracker.getXVelocity(mActivePointerId),
vtracker.getYVelocity(mActivePointerId))
&& mMinimumVelocity < Math.abs((mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity()))) {
onOrthoFling(mDownView, mHorizontal ? vtracker.getYVelocity()
: vtracker.getXVelocity());
break;
}
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = mHorizontal
? (int) velocityTracker.getXVelocity(mActivePointerId)
: (int) velocityTracker.getYVelocity(mActivePointerId);
if (getChildCount() > 0) {
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
fling(-initialVelocity);
} else {
final int bottom = getScrollRange();
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, bottom, 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, bottom)) {
invalidate();
}
}
onScrollUp();
}
onPull(0);
}
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsOrthoDragged) {
onOrthoDragFinished(mDownView);
mActivePointerId = INVALID_POINTER;
endDrag();
} else if (mIsBeingDragged && getChildCount() > 0) {
if (mHorizontal) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, getScrollRange(), 0, 0)) {
invalidate();
}
} else {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
invalidate();
}
}
// when touch is cancelled, treat it as up to allow icons to snap back
onScrollUp();
mActivePointerId = INVALID_POINTER;
endDrag();
} else {
return false;
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
final float y = mHorizontal ? ev.getX(index) : ev.getY(index);
mLastMotionY = y;
mLastOrthoCoord = mHorizontal ? ev.getY(index) : ev.getX(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = mHorizontal
? ev.getX(ev.findPointerIndex(mActivePointerId))
: ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
return true;
}
|
diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
index cd80e94b0..fb6edb452 100644
--- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
+++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java
@@ -1,148 +1,148 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.portfolio.search.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.search.data.SearchConditions;
import org.mifosplatform.portfolio.search.data.SearchData;
import org.mifosplatform.useradministration.domain.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class SearchReadPlatformServiceImpl implements SearchReadPlatformService {
private final NamedParameterJdbcTemplate namedParameterjdbcTemplate;
private final PlatformSecurityContext context;
@Autowired
public SearchReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) {
this.context = context;
this.namedParameterjdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
@Override
public Collection<SearchData> retriveMatchingData(final SearchConditions searchConditions) {
AppUser currentUser = context.authenticatedUser();
String hierarchy = currentUser.getOffice().getHierarchy();
SearchMapper rm = new SearchMapper();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("hierarchy", hierarchy + "%");
params.addValue("search", searchConditions.getSearchQuery());
params.addValue("partialSearch", "%" + searchConditions.getSearchQuery() + "%");
return this.namedParameterjdbcTemplate.query(rm.searchSchema(searchConditions), params, rm);
}
private static final class SearchMapper implements RowMapper<SearchData> {
public String searchSchema(final SearchConditions searchConditions) {
- String union = " union all ";
+ String union = " union ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
@Override
public SearchData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long entityId = JdbcSupport.getLong(rs, "entityId");
final String entityAccountNo = rs.getString("entityAccountNo");
final String entityExternalId = rs.getString("entityExternalId");
final String entityName = rs.getString("entityName");
final String entityType = rs.getString("entityType");
final Long parentId = JdbcSupport.getLong(rs, "parentId");
final String parentName = rs.getString("parentName");
return new SearchData(entityId, entityAccountNo, entityExternalId, entityName, entityType, parentId, parentName);
}
}
}
| true | true | public String searchSchema(final SearchConditions searchConditions) {
String union = " union all ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
| public String searchSchema(final SearchConditions searchConditions) {
String union = " union ";
String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) ";
String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo "
+ " , c.office_id as parentId, o.name as parentName "
+ " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or "
+ "(c.display_name like :partialSearch and c.display_name not like :search) or "
+ "(c.external_id like :partialSearch and c.external_id not like :search))";
String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) ";
String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo "
+ " , c.id as parentId, c.display_name as parentName "
+ " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) ";
String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :search) ";
String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, "
+ " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName "
+ " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id "
+ " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) ";
String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) ";
String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo "
+ " , g.office_id as parentId, o.name as parentName "
+ " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) ";
StringBuffer sql = new StringBuffer();
// first include all exact matches
if (searchConditions.isClientSearch()) {
sql.append(clientExactMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanExactMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierExactMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupExactMatchSql).append(union);
}
// include all matching records
if (searchConditions.isClientSearch()) {
sql.append(clientMatchSql).append(union);
}
if (searchConditions.isLoanSeach()) {
sql.append(loanMatchSql).append(union);
}
if(searchConditions.isClientIdentifierSearch()){
sql.append(clientIdentifierMatchSql).append(union);
}
if (searchConditions.isGroupSearch()) {
sql.append(groupMatchSql).append(union);
}
sql.replace(sql.lastIndexOf(union), sql.length(), "");
// remove last occurrence of "union all" string
return sql.toString();
}
|
diff --git a/src/com/google/sitebricks/rendering/control/HeaderWidget.java b/src/com/google/sitebricks/rendering/control/HeaderWidget.java
index 17c0156..091748c 100644
--- a/src/com/google/sitebricks/rendering/control/HeaderWidget.java
+++ b/src/com/google/sitebricks/rendering/control/HeaderWidget.java
@@ -1,44 +1,45 @@
package com.google.sitebricks.rendering.control;
import com.google.sitebricks.Renderable;
import com.google.sitebricks.Respond;
import com.google.sitebricks.compiler.EvaluatorCompiler;
import com.google.sitebricks.compiler.ExpressionCompileException;
import com.google.sitebricks.compiler.Token;
import com.google.sitebricks.rendering.SelfRendering;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Dhanji R. Prasanna ([email protected])
*/
@SelfRendering
class HeaderWidget implements Renderable {
private final WidgetChain widgetChain;
private Map<String, List<Token>> attribs;
public HeaderWidget(WidgetChain widgetChain, Map<String, String> attribs,
EvaluatorCompiler compiler) throws ExpressionCompileException {
this.widgetChain = widgetChain;
this.attribs = XmlWidget.compile(attribs, compiler);
}
public void render(Object bound, Respond respond) {
XmlWidget.writeOpenTag(bound, respond, "head", attribs);
+ respond.write('>');
//render children (as necessary)
widgetChain.render(bound, respond);
respond.withHtml()
.headerPlaceholder(); //TODO replace placeholder with an index?
respond.write("</head>");
}
public <T extends Renderable> Set<T> collect(Class<T> clazz) {
return widgetChain.collect(clazz);
}
}
| true | true | public void render(Object bound, Respond respond) {
XmlWidget.writeOpenTag(bound, respond, "head", attribs);
//render children (as necessary)
widgetChain.render(bound, respond);
respond.withHtml()
.headerPlaceholder(); //TODO replace placeholder with an index?
respond.write("</head>");
}
| public void render(Object bound, Respond respond) {
XmlWidget.writeOpenTag(bound, respond, "head", attribs);
respond.write('>');
//render children (as necessary)
widgetChain.render(bound, respond);
respond.withHtml()
.headerPlaceholder(); //TODO replace placeholder with an index?
respond.write("</head>");
}
|
diff --git a/src/org/opensolaris/opengrok/configuration/Configuration.java b/src/org/opensolaris/opengrok/configuration/Configuration.java
index 8763fd3..1e3cd79 100644
--- a/src/org/opensolaris/opengrok/configuration/Configuration.java
+++ b/src/org/opensolaris/opengrok/configuration/Configuration.java
@@ -1,474 +1,475 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.configuration;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.opensolaris.opengrok.history.RepositoryInfo;
import org.opensolaris.opengrok.index.IgnoredNames;
/**
* Placeholder class for all configuration variables. Due to the multithreaded
* nature of the web application, each thread will use the same instance of the
* configuration object for each page request. Class and methods should have
* package scope, but that didn't work with the XMLDecoder/XMLEncoder.
*/
public final class Configuration {
private String ctags;
/** Should the history log be cached? */
private boolean historyCache;
/**
* The maximum time in milliseconds {@code HistoryCache.get()} can take
* before its result is cached.
*/
private int historyCacheTime;
/** Should the history cache be stored in a database? */
private boolean historyCacheInDB;
private List<Project> projects;
private String sourceRoot;
private String dataRoot;
private List<RepositoryInfo> repositories;
private String urlPrefix;
private boolean generateHtml;
private Project defaultProject;
private int indexWordLimit;
private boolean verbose;
private boolean allowLeadingWildcard;
private IgnoredNames ignoredNames;
private String userPage;
private String bugPage;
private String bugPattern;
private String reviewPage;
private String reviewPattern;
private String webappLAF;
private boolean remoteScmSupported;
private boolean optimizeDatabase;
private boolean useLuceneLocking;
private boolean compressXref;
private boolean indexVersionedFilesOnly;
private int hitsPerPage;
private int cachePages;
private String databaseDriver;
private String databaseUrl;
/** Creates a new instance of Configuration */
public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
- setIndexWordLimit(60000);
+ //below can cause an outofmemory error, since it is defaulting to NO LIMIT
+ setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
public String getCtags() {
return ctags;
}
public void setCtags(String ctags) {
this.ctags = ctags;
}
public int getCachePages() {
return cachePages;
}
public void setCachePages(int cachePages) {
this.cachePages = cachePages;
}
public int getHitsPerPage() {
return hitsPerPage;
}
public void setHitsPerPage(int hitsPerPage) {
this.hitsPerPage = hitsPerPage;
}
/**
* Should the history log be cached?
* @return {@code true} if a {@code HistoryCache} implementation should
* be used, {@code false} otherwise
*/
public boolean isHistoryCache() {
return historyCache;
}
/**
* Set whether history should be cached.
* @param historyCache if {@code true} enable history cache
*/
public void setHistoryCache(boolean historyCache) {
this.historyCache = historyCache;
}
/**
* How long can a history request take before it's cached? If the time
* is exceeded, the result is cached. This setting only affects
* {@code FileHistoryCache}.
*
* @return the maximum time in milliseconds a history request can take
* before it's cached
*/
public int getHistoryCacheTime() {
return historyCacheTime;
}
/**
* Set the maximum time a history request can take before it's cached.
* This setting is only respected if {@code FileHistoryCache} is used.
*
* @param historyCacheTime maximum time in milliseconds
*/
public void setHistoryCacheTime(int historyCacheTime) {
this.historyCacheTime = historyCacheTime;
}
/**
* Should the history cache be stored in a database? If yes,
* {@code JDBCHistoryCache} will be used to cache the history; otherwise,
* {@code FileHistoryCache} is used.
*
* @return whether the history cache should be stored in a database
*/
public boolean isHistoryCacheInDB() {
return historyCacheInDB;
}
/**
* Set whether the history cache should be stored in a database, and
* {@code JDBCHistoryCache} should be used instead of {@code
* FileHistoryCache}.
*
* @param historyCacheInDB whether the history cached should be stored in
* a database
*/
public void setHistoryCacheInDB(boolean historyCacheInDB) {
this.historyCacheInDB = historyCacheInDB;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public String getSourceRoot() {
return sourceRoot;
}
public void setSourceRoot(String sourceRoot) {
this.sourceRoot = sourceRoot;
}
public String getDataRoot() {
return dataRoot;
}
public void setDataRoot(String dataRoot) {
this.dataRoot = dataRoot;
}
public List<RepositoryInfo> getRepositories() {
return repositories;
}
public void setRepositories(List<RepositoryInfo> repositories) {
this.repositories = repositories;
}
public String getUrlPrefix() {
return urlPrefix;
}
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public void setGenerateHtml(boolean generateHtml) {
this.generateHtml = generateHtml;
}
public boolean isGenerateHtml() {
return generateHtml;
}
public void setDefaultProject(Project defaultProject) {
this.defaultProject = defaultProject;
}
public Project getDefaultProject() {
return defaultProject;
}
public int getIndexWordLimit() {
return indexWordLimit;
}
public void setIndexWordLimit(int indexWordLimit) {
this.indexWordLimit = indexWordLimit;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
this.allowLeadingWildcard = allowLeadingWildcard;
}
public boolean isAllowLeadingWildcard() {
return allowLeadingWildcard;
}
private boolean quickContextScan;
public boolean isQuickContextScan() {
return quickContextScan;
}
public void setQuickContextScan(boolean quickContextScan) {
this.quickContextScan = quickContextScan;
}
public void setIgnoredNames(IgnoredNames ignoredNames) {
this.ignoredNames = ignoredNames;
}
public IgnoredNames getIgnoredNames() {
return ignoredNames;
}
public void setUserPage(String userPage) {
this.userPage = userPage;
}
public String getUserPage() {
return userPage;
}
public void setBugPage(String bugPage) {
this.bugPage = bugPage;
}
public String getBugPage() {
return bugPage;
}
public void setBugPattern(String bugPattern) {
this.bugPattern = bugPattern;
}
public String getBugPattern() {
return bugPattern;
}
public String getReviewPage() {
return reviewPage;
}
public void setReviewPage(String reviewPage) {
this.reviewPage = reviewPage;
}
public String getReviewPattern() {
return reviewPattern;
}
public void setReviewPattern(String reviewPattern) {
this.reviewPattern = reviewPattern;
}
public String getWebappLAF() {
return webappLAF;
}
public void setWebappLAF(String webappLAF) {
this.webappLAF = webappLAF;
}
public boolean isRemoteScmSupported() {
return remoteScmSupported;
}
public void setRemoteScmSupported(boolean remoteScmSupported) {
this.remoteScmSupported = remoteScmSupported;
}
public boolean isOptimizeDatabase() {
return optimizeDatabase;
}
public void setOptimizeDatabase(boolean optimizeDatabase) {
this.optimizeDatabase = optimizeDatabase;
}
public boolean isUsingLuceneLocking() {
return useLuceneLocking;
}
public void setUsingLuceneLocking(boolean useLuceneLocking) {
this.useLuceneLocking = useLuceneLocking;
}
public void setCompressXref(boolean compressXref) {
this.compressXref = compressXref;
}
public boolean isCompressXref() {
return compressXref;
}
public boolean isIndexVersionedFilesOnly() {
return indexVersionedFilesOnly;
}
public void setIndexVersionedFilesOnly(boolean indexVersionedFilesOnly) {
this.indexVersionedFilesOnly = indexVersionedFilesOnly;
}
public Date getDateForLastIndexRun() {
File timestamp = new File(getDataRoot(), "timestamp");
return new Date(timestamp.lastModified());
}
public String getDatabaseDriver() {
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabaseUrl() {
if (databaseUrl == null) {
return "jdbc:derby://localhost/cachedb;create=true";
}
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
/**
* Write the current configuration to a file
* @param file the file to write the configuration into
* @throws IOException if an error occurs
*/
public void write(File file) throws IOException {
final FileOutputStream out = new FileOutputStream(file);
try {
this.encodeObject(out);
} finally {
out.close();
}
}
public String getXMLRepresentationAsString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
this.encodeObject(bos);
return bos.toString();
}
private void encodeObject(OutputStream out) {
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
e.writeObject(this);
e.close();
}
public static Configuration read(File file) throws IOException {
final FileInputStream in = new FileInputStream(file);
try {
return decodeObject(in);
} finally {
in.close();
}
}
public static Configuration makeXMLStringAsConfiguration(String xmlconfig) throws IOException {
final Configuration ret;
final ByteArrayInputStream in = new ByteArrayInputStream(xmlconfig.getBytes());
ret = decodeObject(in);
return ret;
}
private static Configuration decodeObject(InputStream in) throws IOException {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(in));
final Object ret = d.readObject();
d.close();
if (!(ret instanceof Configuration)) {
throw new IOException("Not a valid config file");
}
return (Configuration)ret;
}
}
| true | true | public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
setIndexWordLimit(60000);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
| public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags("ctags");
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://www.opensolaris.org/os/community/arc/caselog/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setDatabaseDriver("org.apache.derby.jdbc.ClientDriver");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.