answer
stringlengths 17
10.2M
|
|---|
package com.mcgoodtime.gti.common.core;
import com.mcgoodtime.gti.common.GtiPotion;
import com.mcgoodtime.gti.common.blocks.fluid.Gas;
import com.mcgoodtime.gti.common.entity.EntityPackagedSalt;
import com.mcgoodtime.gti.common.entity.EntityUran238;
import com.mcgoodtime.gti.common.entity.GtiEntity;
import com.mcgoodtime.gti.common.init.*;
import com.mcgoodtime.gti.common.nei.NEIGtiConfig;
import com.mcgoodtime.gti.common.worldgen.GtiWorldGen;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import ic2.core.Ic2Items;
import net.minecraft.client.renderer.entity.RenderSnowball;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.common.AchievementPage;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.FluidRegistry;
@Mod(
modid = Gti.MOD_ID,
name = Gti.MOD_NAME,
version = Gti.VERSION,
dependencies = "required-after:"
+ "Forge@[10.13.4.1558,);"
+ "required-after:"
+ "IC2@[2.2.748,);",
useMetadata = true
)
public final class Gti {
public static final String MOD_ID = "gti";
public static final String MOD_NAME = "GoodTime-Industrial";
public static final String VERSION = "Dev.0.1.1";
public static final String RESOURCE_DOMAIN = "gti";
public static final String GUI_PREFIX = "gui.gti.";
public static final CreativeTabs creativeTabGti = new CreativeTabs(MOD_NAME) {
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem() {
return GtiItems.diamondApple;
}
};
@Mod.Metadata
public ModMetadata meta = new ModMetadata();
@Instance(Gti.MOD_ID)
public static Gti instance;
@SidedProxy(
modId = MOD_ID,
serverSide = "com.mcgoodtime.gti.common.core.Gti$CommonProxy",
clientSide = "com.mcgoodtime.gti.common.core.Gti$ClientProxy"
)
public static CommonProxy proxy;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
setupMeta();
GtiConfig.configFile = event.getSuggestedConfigurationFile();
GtiConfig.init();
//register Blocks.
GtiBlocks.init();
FluidRegistry.registerFluid(Gas.gasNatural);
//register Items.
GtiItems.init();
GtiPotion.initPotion();
proxy.init();
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
GtiOreDictionary.init();
GtiEntity.init();
// register Recipes.
GtiRecipes.init();
//register gui handler
NetworkRegistry.INSTANCE.registerGuiHandler(instance, GuiHandler.getInstance());
//register achievement
GtiAchievement.init();
//register achievement page
AchievementPage.registerAchievementPage(GtiAchievement.pageGti);
//register ore gen bus.
GtiWorldGen.init();
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
//register Event.
FMLCommonHandler.instance().bus().register(new GtiEvent());
MinecraftForge.EVENT_BUS.register(new GtiEvent());
if (Loader.isModLoaded("NotEnoughItems")) {
new NEIGtiConfig().loadConfig();
}
}
private void setupMeta() {
this.meta.modId = MOD_ID;
this.meta.name = MOD_NAME;
this.meta.version = "dev 0.1.1";
this.meta.url = "https://github.com/Minecraft-GoodTime/GoodTime-Industrial";
this.meta.updateUrl = this.meta.url;
this.meta.authorList.add("BestOwl");
this.meta.authorList.add("liach");
this.meta.authorList.add("Seedking");
this.meta.authorList.add("JAVA0");
this.meta.authorList.add("GoodTime Studio");
this.meta.credits = "GoodTime Studio";
}
public static class CommonProxy {
public void init() {}
}
public static class ClientProxy extends CommonProxy {
@Override
public void init() {
RenderingRegistry.registerEntityRenderingHandler(EntityUran238.class, new RenderSnowball(Ic2Items.Uran238.getItem()));
RenderingRegistry.registerEntityRenderingHandler(EntityPackagedSalt.class, new RenderSnowball(GtiItems.packagedSalt));
}
}
}
|
package com.ociweb.iot.maker;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.iot.hardware.HardwareImpl;
import com.ociweb.iot.hardware.impl.edison.GroveV3EdisonImpl;
import com.ociweb.iot.hardware.impl.grovepi.GrovePiHardwareImpl;
import com.ociweb.iot.hardware.impl.test.TestHardware;
import com.ociweb.pronghorn.iot.ReactiveListenerStage;
import com.ociweb.pronghorn.iot.i2c.I2CBacking;
import com.ociweb.pronghorn.iot.schema.GroveRequestSchema;
import com.ociweb.pronghorn.iot.schema.GroveResponseSchema;
import com.ociweb.pronghorn.iot.schema.I2CCommandSchema;
import com.ociweb.pronghorn.iot.schema.I2CResponseSchema;
import com.ociweb.pronghorn.iot.schema.TrafficOrderSchema;
import com.ociweb.pronghorn.pipe.DataInputBlobReader;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.pipe.util.hash.IntHashTable;
import com.ociweb.pronghorn.schema.MessagePubSub;
import com.ociweb.pronghorn.schema.MessageSubscription;
import com.ociweb.pronghorn.schema.NetRequestSchema;
import com.ociweb.pronghorn.schema.NetResponseSchema;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.NonThreadScheduler;
import com.ociweb.pronghorn.stage.scheduling.StageScheduler;
public class DeviceRuntime {
//TODO: we may need a static singleton accessory for this.
private static final int nsPerMS = 1_000_000;
/*
* Caution: in order to make good use of ProGuard we need to make an effort to avoid using static so
* dependencies can be traced and kept in the jar.
*
*/
private static final Logger logger = LoggerFactory.getLogger(DeviceRuntime.class);
protected HardwareImpl hardware;
private StageScheduler scheduler;
private final GraphManager gm;
private final int defaultCommandChannelLength = 16;
private final int defaultCommandChannelMaxPayload = 256; //largest i2c request or pub sub payload
private final int i2cDefaultLength = 300;
private final int i2cDefaultMaxPayload = 16;
//Pipes for requesting GPIO operations both Analog and Digital
private final PipeConfig<GroveRequestSchema> requestPipeConfig = new PipeConfig<GroveRequestSchema>(GroveRequestSchema.instance, defaultCommandChannelLength);
///Pipes for writing to I2C bus
private final PipeConfig<I2CCommandSchema> i2cPayloadPipeConfig = new PipeConfig<I2CCommandSchema>(I2CCommandSchema.instance, i2cDefaultLength,i2cDefaultMaxPayload);
///Pipes for subscribing to and sending messages this is MQTT, StateChanges and many others
private final PipeConfig<MessagePubSub> messagePubSubConfig = new PipeConfig<MessagePubSub>(MessagePubSub.instance, defaultCommandChannelLength,defaultCommandChannelMaxPayload);
//Each of the above pipes are paired with TrafficOrder pipe to group commands togetehr in atomic groups and to enforce order across the pipes.
private final PipeConfig<TrafficOrderSchema> goPipeConfig = new PipeConfig<TrafficOrderSchema>(TrafficOrderSchema.instance, defaultCommandChannelLength);
///Pipes containing response data from the I2C bus, this primarily is polled at a fixed rate on startup
private final PipeConfig<I2CResponseSchema> reponseI2CConfig = new PipeConfig<I2CResponseSchema>(I2CResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload);
//Pipes containing response data from the GPIO pins both digital and analog, this is primarily polled at a fixed rate on startup.
private final PipeConfig<GroveResponseSchema> responsePinsConfig = new PipeConfig<GroveResponseSchema>(GroveResponseSchema.instance, defaultCommandChannelLength);
//Pipes containing response data from HTTP requests.
private final PipeConfig<NetResponseSchema> responseNetConfig = new PipeConfig<NetResponseSchema>(NetResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload);
//Pipes containing HTTP requests.
private final PipeConfig<NetRequestSchema> requestNetConfig = new PipeConfig<NetRequestSchema>(NetRequestSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload);
//Pipes for receiving messages, this includes MQTT, State and many others
private final PipeConfig<MessageSubscription> messageSubscriptionConfig = new PipeConfig<MessageSubscription>(MessageSubscription.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload);
private int netResponsePipeIdx = 0;//this implementation is dependent upon graphManager returning the pipes in the order created!
private int subscriptionPipeIdx = 0; //this implementation is dependent upon graphManager returning the pipes in the order created!
private int defaultSleepRateNS = 10_000_000; //we will only check for new work 100 times per second to keep CPU usage low.
private static final byte piI2C = 1;
private static final byte edI2C = 6;
private final IntHashTable subscriptionPipeLookup = new IntHashTable(10);//NOTE: this is a maximum of 1024 listeners
private final IntHashTable netPipeLookup = new IntHashTable(10);//NOTE: this is a maximum of 1024 listeners
public DeviceRuntime() {
gm = new GraphManager();
}
public static String getOptArg(String longName, String shortName, String[] args, String defaultValue) {
String prev = null;
for (String token : args) {
if (longName.equals(prev) || shortName.equals(prev)) {
if (token == null || token.trim().length() == 0 || token.startsWith("-")) {
return defaultValue;
}
return reportChoice(longName, shortName, token.trim());
}
prev = token;
}
return reportChoice(longName, shortName, defaultValue);
}
public static String reportChoice(final String longName, final String shortName, final String value) {
System.out.print(longName);
System.out.print(" ");
System.out.print(shortName);
System.out.print(" ");
System.out.println(value);
return value;
}
public HardwareImpl getHardware(){
if(this.hardware==null){
//setup system for binary binding in case Zulu is found on Arm
//must populate os.arch as "arm" instead of "aarch32" or "aarch64" in that case, JIFFI is dependent on this value.
if (System.getProperty("os.arch", "unknown").contains("aarch")) {
System.setProperty("os.arch", "arm"); //TODO: investigate if this a bug against jiffi or zulu and inform them
}
//The best way to detect the pi or edison is to first check for the expected matching i2c implmentation
I2CBacking i2cBacking = null;
i2cBacking = HardwareImpl.getI2CBacking(edI2C);
if (null != i2cBacking) {
this.hardware = new GroveV3EdisonImpl(gm, i2cBacking);
System.out.println("Detected running on Edison");
} else {
i2cBacking = HardwareImpl.getI2CBacking(piI2C);
if (null != i2cBacking) {
this.hardware = new GrovePiHardwareImpl(gm, i2cBacking);
System.out.println("Detected running on Pi");
}
else {
this.hardware = new TestHardware(gm);
System.out.println("Unrecognized hardware, test mock hardware will be used");
}
}
}
return this.hardware;
}
public CommandChannel newCommandChannel() {
return this.hardware.newCommandChannel((requestPipeConfig ),
(i2cPayloadPipeConfig),
messagePubSubConfig,
requestNetConfig,
(goPipeConfig));
}
public CommandChannel newCommandChannel(int customChannelLength) {
return this.hardware.newCommandChannel((new PipeConfig<GroveRequestSchema>(GroveRequestSchema.instance, customChannelLength) ),
(new PipeConfig<I2CCommandSchema>(I2CCommandSchema.instance, customChannelLength,defaultCommandChannelMaxPayload)),
(new PipeConfig<MessagePubSub>(MessagePubSub.instance, customChannelLength,defaultCommandChannelMaxPayload)),
requestNetConfig,
(new PipeConfig<TrafficOrderSchema>(TrafficOrderSchema.instance, customChannelLength)));
}
public ListenerFilter addRotaryListener(RotaryListener listener) {
return registerListener(listener);
}
public ListenerFilter addStartupListener(StartupListener listener) {
return registerListener(listener);
}
public ListenerFilter addAnalogListener(AnalogListener listener) {
return registerListener(listener);
}
public ListenerFilter addDigitalListener(DigitalListener listener) {
return registerListener(listener);
}
public ListenerFilter addTimeListener(TimeListener listener) {
return registerListener(listener);
}
public ListenerFilter addI2CListener(I2CListener listener) {
return registerListener(listener);
}
public ListenerFilter addPubSubListener(PubSubListener listener) {
return registerListener(listener);
}
public <E extends Enum<E>> ListenerFilter addStateChangeListener(StateChangeListener<E> listener) {
return registerListener(listener);
}
public ListenerFilter addListener(Object listener) {
return registerListener(listener);
}
public ListenerFilter registerListener(Object listener) {
//TODO: convert to stack based implementation for a single pass.
//pre-count how many pipes will be needed so the array can be built to the right size
int pipesCount = 0;
if (this.hardware.isListeningToI2C(listener) && this.hardware.hasI2CInputs()) {
pipesCount++;
}
if (this.hardware.isListeningToPins(listener) && this.hardware.hasDigitalOrAnalogInputs()) {
pipesCount++;
}
if (this.hardware.isListeningToHTTPResponse(listener)) {
pipesCount++;
}
if (this.hardware.isListeningToSubscription(listener)) {
pipesCount++;
}
Pipe<?>[] inputPipes = new Pipe<?>[pipesCount];
//Populate the inputPipes array with the required pipes
if (this.hardware.isListeningToI2C(listener) && this.hardware.hasI2CInputs()) {
inputPipes[--pipesCount] = (new Pipe<I2CResponseSchema>(reponseI2CConfig.grow2x())); //must double since used by splitter
}
if (this.hardware.isListeningToPins(listener) && this.hardware.hasDigitalOrAnalogInputs()) {
inputPipes[--pipesCount] = (new Pipe<GroveResponseSchema>(responsePinsConfig.grow2x())); //must double since used by splitter
}
if (this.hardware.isListeningToHTTPResponse(listener)) {
Pipe<NetResponseSchema> netResponsePipe = new Pipe<NetResponseSchema>(responseNetConfig) {
@SuppressWarnings("unchecked")
@Override
protected DataInputBlobReader<NetResponseSchema> createNewBlobReader() {
return new PayloadReader(this);
}
};
int pipeIdx = netResponsePipeIdx++;
inputPipes[--pipesCount] = netResponsePipe;
boolean addedItem = IntHashTable.setItem(netPipeLookup, System.identityHashCode(listener), pipeIdx);
if (!addedItem) {
throw new RuntimeException("Could not find unique identityHashCode for "+listener.getClass().getCanonicalName());
}
}
int subPipeIdx = -1;
int testId = -1;
if (this.hardware.isListeningToSubscription(listener)) {
Pipe<MessageSubscription> subscriptionPipe = new Pipe<MessageSubscription>(messageSubscriptionConfig) {
@SuppressWarnings("unchecked")
@Override
protected DataInputBlobReader<MessageSubscription> createNewBlobReader() {
return new PayloadReader(this);
}
};
subPipeIdx = subscriptionPipeIdx++;
testId = subscriptionPipe.id;
inputPipes[--pipesCount]=(subscriptionPipe);
//store this value for lookup later
//logger.debug("adding hash listener {} to pipe {} ",System.identityHashCode(listener), subPipeIdx);
boolean addedItem = IntHashTable.setItem(subscriptionPipeLookup, System.identityHashCode(listener), subPipeIdx);
if (!addedItem) {
throw new RuntimeException("Could not find unique identityHashCode for "+listener.getClass().getCanonicalName());
}
}
//StartupListener is not driven by any response data and is called when the stage is started up. no pipe needed.
//TimeListener, time rate signals are sent from the stages its self and therefore does not need a pipe to consume.
Pipe<?>[] outputPipes = extractPipesUsedByListener(listener);
ReactiveListenerStage reactiveListener = hardware.createReactiveListener(gm, listener, inputPipes, outputPipes);
configureStageRate(listener,reactiveListener);
Pipe<MessageSubscription>[] subsPipes = GraphManager.allPipesOfType(gm, MessageSubscription.instance);
assert(-1==testId || subsPipes[subPipeIdx].id==testId) : "GraphManager has returned the pipes out of the expected order";
return reactiveListener;
}
//only build this when assertions are on
private static IntHashTable cmdChannelUsageChecker;
static {
assert(setupForChannelAssertCheck());
}
private static boolean setupForChannelAssertCheck() {
cmdChannelUsageChecker = new IntHashTable(9);
return true;
}
private boolean channelNotPreviouslyUsed(CommandChannel cmdChnl) {
int hash = cmdChnl.hashCode();
if (IntHashTable.hasItem(cmdChannelUsageChecker, hash)) {
//this was already assigned somewhere so this is an error
logger.error("A CommandChannel instance can only be used exclusivly by one object or lambda. Double check where CommandChannels are passed in.", new UnsupportedOperationException());
return false;
}
//keep so this is detected later if use;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IntHashTable.setItem(cmdChannelUsageChecker, hash, 42);
return true;
}
private Pipe<?>[] extractPipesUsedByListener(Object listener) {
//TODO: convert to recursive in order to a llocate once
Pipe<?>[] outputPipes = new Pipe<?>[0];
Class<? extends Object> c = listener.getClass();
Field[] fields = c.getDeclaredFields();
int f = fields.length;
while (--f >= 0) {
try {
fields[f].setAccessible(true);
if (CommandChannel.class == fields[f].getType()) {
CommandChannel cmdChnl = (CommandChannel)fields[f].get(listener);
assert(channelNotPreviouslyUsed(cmdChnl)) : "A CommandChannel instance can only be used exclusivly by one object or lambda. Double check where CommandChannels are passed in.";
cmdChnl.setListener(listener);
Pipe<?>[] chnlPipes = cmdChnl.getOutputPipes();
int i = chnlPipes.length;
while (--i>=0) {
if (null!=chnlPipes[i]) {
outputPipes = PronghornStage.join(outputPipes, chnlPipes[i]);
}
}
}
} catch (Throwable e) {
logger.debug("unable to find CommandChannel",e);
}
}
return outputPipes;
}
protected void configureStageRate(Object listener, ReactiveListenerStage stage) {
//if we have a time event turn it on.
long rate = hardware.getTriggerRate();
if (rate>0 && listener instanceof TimeListener) {
stage.setTimeEventSchedule(rate, hardware.getTriggerStart());
//Since we are using the time schedule we must set the stage to be faster
long customRate = (rate*nsPerMS)/NonThreadScheduler.granularityMultiplier;// in ns and guanularityXfaster than clock trigger
long appliedRate = Math.min(customRate,defaultSleepRateNS);
GraphManager.addNota(gm, GraphManager.SCHEDULE_RATE, appliedRate, stage);
}
}
private void start() {
hardware.coldSetup(); //TODO: should we add LCD init in the PI hardware code? How do we know when its used?
hardware.buildStages(subscriptionPipeLookup,
netPipeLookup,
GraphManager.allPipesOfType(gm, GroveResponseSchema.instance),
GraphManager.allPipesOfType(gm, I2CResponseSchema.instance),
GraphManager.allPipesOfType(gm, MessageSubscription.instance),
GraphManager.allPipesOfType(gm, NetResponseSchema.instance),
GraphManager.allPipesOfType(gm, TrafficOrderSchema.instance),
GraphManager.allPipesOfType(gm, GroveRequestSchema.instance),
GraphManager.allPipesOfType(gm, I2CCommandSchema.instance),
GraphManager.allPipesOfType(gm, MessagePubSub.instance),
GraphManager.allPipesOfType(gm, NetRequestSchema.instance)
);
//find all the instances of CommandChannel stage to startup first, note they are also unscheduled.
logStageScheduleRates();
//exportGraphDotFile();
scheduler = hardware.createScheduler(this);
}
private void logStageScheduleRates() {
int totalStages = GraphManager.countStages(gm);
for(int i=1;i<=totalStages;i++) {
PronghornStage s = GraphManager.getStage(gm, i);
if (null != s) {
Object rate = GraphManager.getNota(gm, i, GraphManager.SCHEDULE_RATE, null);
if (null == rate) {
logger.debug("{} is running without breaks",s);
} else {
logger.debug("{} is running at rate of {}",s,rate);
}
}
}
}
//TODO: required for testing only
public StageScheduler getScheduler() {
return scheduler;
}
/**
* Export file so GraphVis can be used to view the internal graph.
*
* To view this file install: sudo apt-get install graphviz
*
*/
private void exportGraphDotFile() {
FileOutputStream fost;
try {
fost = new FileOutputStream("deviceGraph.dot");
PrintWriter pw = new PrintWriter(fost);
gm.writeAsDOT(gm, pw);
pw.close();
//to produce the png we must call
// dot -Tpng -O deviceGraph.dot
Process result = Runtime.getRuntime().exec("dot -Tsvg -odeviceGraph.dot.svg deviceGraph.dot");
if (0==result.waitFor()) {
logger.info("Built deviceGraph.dot.png to view the runtime graph.");
}
result = Runtime.getRuntime().exec("circo -Tsvg -odeviceGraph.circo.svg deviceGraph.dot");
if (0==result.waitFor()) {
logger.info("Built deviceGraph.circo.png to view the runtime graph.");
}
} catch (Exception e) {
logger.debug("No runtime graph produced.",e);;
System.out.println("No runtime graph produced.");
}
}
public void shutdownDevice() {
//clean shutdown providing time for the pipe to empty
scheduler.shutdown();
scheduler.awaitTermination(10, TimeUnit.SECONDS); //timeout error if this does not exit cleanly withing this time.
//all the software has now stopped so now shutdown the hardware.
hardware.shutdown();
}
public void shutdownDevice(int timeoutInSeconds) {
//clean shutdown providing time for the pipe to empty
scheduler.shutdown();
scheduler.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS); //timeout error if this does not exit cleanly withing this time.
//all the software has now stopped so now shutdown the hardware.
hardware.shutdown();
}
public static DeviceRuntime test(IoTSetup app) {
DeviceRuntime runtime = new DeviceRuntime();
//force hardware to TestHardware regardless of where or what platform its run on.
//this is done because this is the test() method and must behave the same everywhere.
runtime.hardware = new TestHardware(runtime.gm);
TestHardware hardware = (TestHardware)runtime.getHardware();
hardware.isInUnitTest = true;
try {
app.declareConnections(runtime.getHardware());
establishDefaultRate(runtime);
app.declareBehavior(runtime);
runtime.start();
//for test we do not call startup and wait instead for this to be done by test.
} catch (Throwable t) {
t.printStackTrace();
System.exit(-1);
}
return runtime;
}
public static DeviceRuntime run(IoTSetup app) {
DeviceRuntime runtime = new DeviceRuntime();
return run(app, runtime);
}
private static DeviceRuntime run(IoTSetup app, DeviceRuntime runtime) {
try {
app.declareConnections(runtime.getHardware());
establishDefaultRate(runtime);
app.declareBehavior(runtime);
System.out.println("To exit app press Ctrl-C");
runtime.start();
runtime.scheduler.startup();
} catch (Throwable t) {
t.printStackTrace();
System.exit(-1);
}
return runtime;
}
private static void establishDefaultRate(DeviceRuntime runtime) {
//NOTE: this must be a prime factor of all things going on !!
//TODO: based on the connected twigs we must choose an appropriate default, may need schedule!!!
//runtime.defaultSleepRateNS = 100_000;
//by default, unless explicitly set the stages will use this sleep rate
GraphManager.addDefaultNota(runtime.gm, GraphManager.SCHEDULE_RATE, runtime.defaultSleepRateNS);
}
}
|
package com.redfin.hudson;
import hudson.Extension;
import hudson.Util;
import hudson.FilePath;
import static hudson.Util.*;
import hudson.model.BuildableItem;
import hudson.model.Item;
import hudson.scheduler.CronTabList;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.apache.commons.io.FileUtils;
import antlr.ANTLRException;
/** Triggers a build when the data at a particular URL has changed. */
public class UrlChangeTrigger extends Trigger<BuildableItem> {
URL url;
public UrlChangeTrigger(String url) throws MalformedURLException {
this(new URL(url));
}
public UrlChangeTrigger(URL url) {
this.url = url;
}
@Override
public void start(BuildableItem project, boolean newInstance) {
super.start(project, newInstance);
try {
this.tabs = CronTabList.create("* * * * *");
} catch (ANTLRException e) {
throw new RuntimeException("Bug! couldn't schedule poll");
}
}
private static final Logger LOGGER =
Logger.getLogger(UrlChangeTrigger.class.getName());
private File getFingerprintFile() {
return new File(job.getRootDir(), "url-change-trigger-oldmd5");
}
@Override
public void run() {
try {
LOGGER.log(Level.FINER, "Testing the file {0}", url);
String currentMd5 = Util.getDigestOf(url.openStream());
String oldMd5;
File file = getFingerprintFile();
if (!file.exists()) {
oldMd5 = "null";
} else {
oldMd5 = new FilePath(file).readToString().trim();
}
if (!currentMd5.equalsIgnoreCase(oldMd5)) {
LOGGER.log(Level.FINE,
"Differences found in the file {0}. >{1}< != >{2}<",
new Object[]{
url, oldMd5, currentMd5,
});
FileUtils.writeStringToFile(file, currentMd5);
job.scheduleBuild(new UrlChangeCause(url));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public URL getUrl() {
return url;
}
@Extension
public static final class DescriptorImpl extends TriggerDescriptor {
public DescriptorImpl() {
super(UrlChangeTrigger.class);
}
@Override
public boolean isApplicable(Item item) {
return true;
}
@Override
public String getDisplayName() {
return "Build when a URL's content changes";
}
@Override
public String getHelpFile() {
return "/plugin/url-change-trigger/help-whatIsUrlChangeTrigger.html";
}
/**
* Performs syntax check.
*/
public FormValidation doCheck(@QueryParameter("urlChangeTrigger.url") String url) {
try {
new URL(fixNull(url));
return FormValidation.ok();
} catch (MalformedURLException e) {
return FormValidation.error(e.getMessage());
}
}
@Override
public UrlChangeTrigger newInstance(StaplerRequest req, JSONObject formData) throws FormException {
String url = formData.getString("url");
try {
return new UrlChangeTrigger(url);
} catch (MalformedURLException e) {
throw new FormException("Invalid URL: " + url, e, "");
}
}
}
}
|
package com.sandwell.JavaSimulation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;
import com.jaamsim.basicsim.ClonesOfIterable;
import com.jaamsim.basicsim.InstanceIterable;
import com.jaamsim.basicsim.ReflectionTarget;
import com.jaamsim.events.ConditionalHandle;
import com.jaamsim.events.EventHandle;
import com.jaamsim.events.EventManager;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.input.AttributeDefinitionListInput;
import com.jaamsim.input.AttributeHandle;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.OutputHandle;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.units.TimeUnit;
/**
* Abstract class that encapsulates the methods and data needed to create a
* simulation object. Encapsulates the basic system objects to achieve discrete
* event execution.
*/
public class Entity {
private static AtomicLong entityCount = new AtomicLong(0);
private static final ArrayList<Entity> allInstances;
private static final HashMap<String, Entity> namedEntities;
private String entityName;
private String entityInputName; // Name input by user
private final long entityNumber;
//public static final int FLAG_TRACE = 0x01; // reserved in case we want to treat tracing like the other flags
//public static final int FLAG_TRACEREQUIRED = 0x02;
//public static final int FLAG_TRACESTATE = 0x04;
public static final int FLAG_LOCKED = 0x08;
//public static final int FLAG_TRACKEVENTS = 0x10;
public static final int FLAG_ADDED = 0x20;
public static final int FLAG_EDITED = 0x40;
public static final int FLAG_GENERATED = 0x80;
public static final int FLAG_DEAD = 0x0100;
private int flags;
protected boolean traceFlag = false;
private final ArrayList<Input<?>> editableInputs = new ArrayList<Input<?>>();
private final ArrayList<SynRecord> synonyms = new ArrayList<SynRecord>();
private final HashMap<String, AttributeHandle> attributeMap = new HashMap<String, AttributeHandle>();
private final BooleanInput trace;
@Keyword(description = "A free form string describing the Entity",
example = "Entity1 Description { 'A very useful entity' }")
private final StringInput desc;
@Keyword(description = "The list of user defined attributes for this entity.\n" +
" The attribute name is followed by its initial value. The unit provided for" +
"this value will determine the attribute's unit type.",
example = "Entity1 AttributeDefinitionList { { A 20.0 s } { alpha 42 } }")
private final AttributeDefinitionListInput attributeDefinitionList;
// constants used when scheduling events using the Entity wrappers
public static final int PRIO_DEFAULT = 5;
public static final int PRIO_LOWEST = 11;
static {
allInstances = new ArrayList<Entity>(100);
namedEntities = new HashMap<String, Entity>(100);
}
{
trace = new BooleanInput("Trace", "Key Inputs", false);
trace.setHidden(true);
this.addInput(trace);
desc = new StringInput("Description", "Key Inputs", "");
this.addInput(desc);
attributeDefinitionList = new AttributeDefinitionListInput(this, "AttributeDefinitionList",
"Key Inputs", new ArrayList<AttributeHandle>());
this.addInput(attributeDefinitionList);
}
/**
* Constructor for entity initializing members.
*/
public Entity() {
entityNumber = getNextID();
synchronized(allInstances) {
allInstances.add(this);
}
flags = 0;
}
private static long getNextID() {
return entityCount.incrementAndGet();
}
public static ArrayList<? extends Entity> getAll() {
synchronized(allInstances) {
return allInstances;
}
}
public static <T extends Entity> ArrayList<T> getInstancesOf(Class<T> proto) {
ArrayList<T> instanceList = new ArrayList<T>();
for (Entity each : allInstances) {
if (proto == each.getClass()) {
instanceList.add(proto.cast(each));
}
}
return instanceList;
}
public static <T extends Entity> InstanceIterable<T> getInstanceIterator(Class<T> proto){
return new InstanceIterable<T>(proto);
}
public static <T extends Entity> ClonesOfIterable<T> getClonesOfIterator(Class<T> proto){
return new ClonesOfIterable<T>(proto);
}
public static <T extends Entity> ArrayList<T> getClonesOf(Class<T> proto) {
ArrayList<T> cloneList = new ArrayList<T>();
for (Entity each : allInstances) {
if (proto.isAssignableFrom(each.getClass())) {
cloneList.add(proto.cast(each));
}
}
return cloneList;
}
public static Entity idToEntity(long id) {
synchronized (allInstances) {
for (Entity e : allInstances) {
if (e.getEntityNumber() == id) {
return e;
}
}
return null;
}
}
// This is defined for handlers only
public void validate() throws InputErrorException {}
/**
* Initialises the entity prior to the start of the model run.
* <p>
* This method must not depend on any other entities so that it can be
* called for each entity in any sequence.
*/
public void earlyInit() {
// Reset the attributes to their initial values
for (AttributeHandle h : attributeMap.values()) {
h.setValue(h.getInitialValue());
}
}
/**
* Starts the execution of the model run for this entity.
* <p>
* If required, initialisation that depends on another entity can be
* performed in this method. It is called after earlyInit().
*/
public void startUp() {}
public void kill() {
synchronized (allInstances) {
allInstances.remove(this);
}
removeInputName();
setFlag(FLAG_DEAD);
}
public void doEnd() {}
public static long getEntitySequence() {
long seq = (long)allInstances.size() << 32;
seq += entityCount.get();
return seq;
}
/**
* Get the current Simulation ticks value.
* @return the current simulation tick
*/
public final long getSimTicks() {
return EventManager.current().getSimTicks();
}
/**
* Get the current Simulation time.
* @return the current time in seconds
*/
public final double getSimTime() {
return EventManager.current().getSimSeconds();
}
public final double getCurrentTime() {
long ticks = getSimTicks();
return ticks / Simulation.getSimTimeFactor();
}
protected void addInput(Input<?> in) {
for (int i = 0; i < editableInputs.size(); i++) {
Input<?> ein = editableInputs.get(i);
if (ein.getKeyword().equalsIgnoreCase(in.getKeyword())) {
System.out.format("WARN: keyword handled twice, %s:%s\n", this.getClass().getName(), in.getKeyword());
return;
}
}
editableInputs.add(in);
}
private static class SynRecord {
final String syn;
final Input<?> in;
SynRecord(String s, Input<?> i) {
syn = s;
in = i;
}
}
protected void addSynonym(Input<?> in, String synonym) {
for (int i = 0; i < editableInputs.size(); i++) {
Input<?> ein = editableInputs.get(i);
if (ein.getKeyword().equalsIgnoreCase(synonym)) {
System.out.format("WARN: keyword handled twice, %s:%s\n", this.getClass().getName(), synonym);
return;
}
}
for (int i = 0; i < synonyms.size(); i++) {
SynRecord rec = synonyms.get(i);
if (rec.syn.equalsIgnoreCase(synonym)) {
System.out.format("WARN: keyword handled twice, %s:%s\n", this.getClass().getName(), synonym);
return;
}
}
synonyms.add(new SynRecord(synonym, in));
}
public Input<?> getInput(String key) {
for (int i = 0; i < editableInputs.size(); i++) {
Input<?> in = editableInputs.get(i);
if (in.getKeyword().equalsIgnoreCase(key))
return in;
}
for (int i = 0; i < synonyms.size(); i++) {
SynRecord rec = synonyms.get(i);
if (rec.syn.equalsIgnoreCase(key))
return rec.in;
}
return null;
}
/**
* Copy the inputs for each keyword to the caller. Any inputs that have already
* been set for the caller are overwritten by those for the entity being copied.
* @param ent = entity whose inputs are to be copied
*/
public void copyInputs(Entity ent) {
for(Input<?> sourceInput: ent.getEditableInputs() ){
Input<?> targetInput = this.getInput(sourceInput.getKeyword());
String val = sourceInput.getValueString();
if( val.isEmpty() ) {
if( ! targetInput.getValueString().isEmpty() )
targetInput.reset();
}
else {
InputAgent.processEntity_Keyword_Value(this, targetInput, val);
}
}
}
public void setFlag(int flag) {
flags |= flag;
}
public void clearFlag(int flag) {
flags &= ~flag;
}
public boolean testFlag(int flag) {
return (flags & flag) != 0;
}
public void setTraceFlag() {
traceFlag = true;
}
public void clearTraceFlag() {
traceFlag = false;
}
/**
* Static method to get the eventManager for all entities.
*/
private EventManager getEventManager() {
return EventManager.current();
}
/**
* Method to return the name of the entity.
* Note that the name of the entity may not be the unique identifier used in the namedEntityHashMap; see Entity.toString()
*/
public String getName() {
if (entityName == null)
return "Entity-" + entityNumber;
else
return entityName;
}
/**
* Get the unique number for this entity
* @return
*/
public long getEntityNumber() {
return entityNumber;
}
/**
* Method to set the name of the entity.
*/
public void setName(String newName) {
entityName = newName;
}
/**
* Method to return the unique identifier of the entity. Used when building Edit tree labels
* @return entityName
*/
@Override
public String toString() {
return getInputName();
}
public static Entity getNamedEntity(String name) {
synchronized (namedEntities) {
return namedEntities.get(name);
}
}
private void removeInputName() {
synchronized (namedEntities) {
if (namedEntities.get(entityInputName) == this)
namedEntities.remove(entityInputName);
entityInputName = null;
}
}
/**
* Method to set the input name of the entity.
*/
public void setInputName(String newName) {
synchronized (namedEntities) {
namedEntities.remove(entityInputName);
entityInputName = newName;
namedEntities.put(entityInputName, this);
}
String name = newName;
if (newName.contains("/"))
name = newName.substring(newName.indexOf("/") + 1);
this.setName(name);
}
/**
* Method to get the input name of the entity.
*/
public String getInputName() {
if (entityInputName == null) {
return this.getName();
}
else {
return entityInputName;
}
}
/**
* This method updates the Entity for changes in the given input
*/
public void updateForInput( Input<?> in ) {
if (in == trace) {
if (trace.getValue())
this.setTraceFlag();
else
this.clearTraceFlag();
return;
}
if (in == attributeDefinitionList) {
attributeMap.clear();
for (AttributeHandle h : attributeDefinitionList.getValue()) {
this.addAttribute(h.getName(), h);
}
// Update the OutputBox
FrameBox.reSelectEntity();
return;
}
}
static long calculateDelayLength(double waitLength) {
return Math.round(waitLength * Simulation.getSimTimeFactor());
}
public double calculateDiscreteTime(double time) {
long discTime = calculateDelayLength(time);
return discTime / Simulation.getSimTimeFactor();
}
public double calculateEventTime(double waitLength) {
long eventTime = getSimTicks() + calculateDelayLength(waitLength);
return eventTime / Simulation.getSimTimeFactor();
}
public double calculateEventTimeBefore(double waitLength) {
long eventTime = getSimTicks() + (long)Math.floor(waitLength * Simulation.getSimTimeFactor());
return eventTime / Simulation.getSimTimeFactor();
}
public double calculateEventTimeAfter(double waitLength) {
long eventTime = getSimTicks() + (long)Math.ceil(waitLength * Simulation.getSimTimeFactor());
return eventTime / Simulation.getSimTimeFactor();
}
public final void startProcess(String methodName, Object... args) {
ProcessTarget t = new ReflectionTarget(this, methodName, args);
startProcess(t);
}
public final void startProcess(ProcessTarget t) {
getEventManager().start(t);
}
public final void scheduleProcess(ProcessTarget t) {
getEventManager().scheduleProcess(0, Entity.PRIO_DEFAULT, false, t);
}
public final void scheduleProcess(double secs, int priority, ProcessTarget t) {
EventManager evt = getEventManager();
long ticks = evt.secondsToNearestTick(secs);
evt.scheduleProcess(ticks, priority, false, t);
}
public final void scheduleProcess(double secs, int priority, ProcessTarget t, EventHandle handle) {
EventManager evt = getEventManager();
long ticks = evt.secondsToNearestTick(secs);
evt.scheduleProcess(ticks, priority, false, t, handle);
}
public final void scheduleProcessTicks(long ticks, int priority, ProcessTarget t) {
getEventManager().scheduleProcess(ticks, priority, false, t);
}
public final void scheduleSingleProcess(ProcessTarget t) {
getEventManager().scheduleSingleProcess(0, Entity.PRIO_LOWEST, true, t);
}
public final void scheduleSingleProcess(ProcessTarget t, double secs) {
EventManager evt = getEventManager();
long ticks = evt.secondsToNearestTick(secs);
getEventManager().scheduleSingleProcess(ticks, Entity.PRIO_LOWEST, true, t);
}
public final void scheduleSingleProcess(ProcessTarget t, int priority) {
getEventManager().scheduleSingleProcess(0, priority, false, t);
}
public final void scheduleSingleProcess(ProcessTarget t, int priority, boolean fifo) {
getEventManager().scheduleSingleProcess(0, priority, fifo, t);
}
/**
* Wait a number of simulated seconds.
* @param secs
*/
public final void simWait(double secs) {
this.simWait(secs, Entity.PRIO_DEFAULT, false, null);
}
/**
* Wait a number of simulated seconds and a given priority.
* @param secs
* @param priority
*/
public final void simWait(double secs, int priority) {
this.simWait(secs, priority, false, null);
}
/**
* Wait a number of simulated seconds and a given priority.
* @param secs
* @param priority
*/
public final void simWait(double secs, int priority, EventHandle handle) {
this.simWait(secs, priority, false, handle);
}
/**
* Wait a number of simulated seconds and a given priority.
* @param secs
* @param priority
*/
public final void simWait(double secs, int priority, boolean fifo, EventHandle handle) {
EventManager evt = getEventManager();
long ticks = evt.secondsToNearestTick(secs);
evt.waitTicks(ticks, priority, fifo, handle);
}
/**
* Wait a number of discrete simulation ticks.
* @param secs
*/
public final void simWaitTicks(long ticks) {
this.simWaitTicks(ticks, Entity.PRIO_DEFAULT);
}
/**
* Wait a number of discrete simulation ticks and a given priority.
* @param secs
* @param priority
*/
public final void simWaitTicks(long ticks, int priority) {
this.simWaitTicks(ticks, priority, false, null);
}
/**
* Wait a number of discrete simulation ticks and a given priority.
* @param secs
* @param priority
* @param fifo
* @param handle
*/
public final void simWaitTicks(long ticks, int priority, boolean fifo, EventHandle handle) {
getEventManager().waitTicks(ticks, priority, fifo, handle);
}
/**
* Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for
* calling the wait method.
*
* @param duration The duration to wait
*/
public final void scheduleWait(double duration) {
long waitLength = calculateDelayLength(duration);
if (waitLength == 0)
return;
this.simWaitTicks(waitLength, Entity.PRIO_DEFAULT, false, null);
}
/**
* Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for
* calling the wait method.
*
* @param duration The duration to wait
* @param priority The relative priority of the event scheduled
*/
public final void scheduleWait( double duration, int priority ) {
long waitLength = calculateDelayLength(duration);
if (waitLength == 0)
return;
this.simWaitTicks(waitLength, priority, false, null);
}
/**
* Wrapper of eventManager.scheduleWait(). Used as a syntax nicity for
* calling the wait method.
*
* @param duration The duration to wait
* @param priority The relative priority of the event scheduled
*/
public final void scheduleWait( double duration, int priority, EventHandle handle ) {
long waitLength = calculateDelayLength(duration);
if (waitLength == 0)
return;
this.simWaitTicks(waitLength, priority, false, handle);
}
/**
* Schedules an event to happen as the last event at the current time.
* Additional calls to scheduleLast will place a new event as the last event.
*/
public final void scheduleLastFIFO() {
this.simWaitTicks(0, Entity.PRIO_LOWEST, true, null);
}
/**
* Schedules an event to happen as the last event at the current time.
* Additional calls to scheduleLast will place a new event as the last event.
*/
public final void scheduleLastLIFO() {
this.simWaitTicks(0, Entity.PRIO_LOWEST, false, null);
}
public final void waitUntil() {
getEventManager().waitUntil(null);
}
public final void waitUntil(ConditionalHandle handle) {
getEventManager().waitUntil(handle);
}
public final void waitUntilEnded() {
getEventManager().waitUntilEnded();
}
public final void killEvent(EventHandle handle) {
getEventManager().killEvent(handle);
}
public final void killEvent(ConditionalHandle handle) {
getEventManager().killEvent(handle);
}
public final void interruptEvent(EventHandle handle) {
getEventManager().interruptEvent(handle);
}
// EDIT TABLE METHODS
public ArrayList<Input<?>> getEditableInputs() {
return editableInputs;
}
// TRACING METHODS
/**
* Track the given subroutine.
*/
public void trace(String meth) {
if (traceFlag) InputAgent.trace(0, this, meth);
}
/**
* Track the given subroutine.
*/
public void trace(int level, String meth) {
if (traceFlag) InputAgent.trace(level, this, meth);
}
/**
* Track the given subroutine (one line of text).
*/
public void trace(String meth, String text1) {
if (traceFlag) InputAgent.trace(0, this, meth, text1);
}
/**
* Track the given subroutine (two lines of text).
*/
public void trace(String meth, String text1, String text2) {
if (traceFlag) InputAgent.trace(0, this, meth, text1, text2);
}
/**
* Print an addition line of tracing.
*/
public void traceLine(String text) {
this.trace( 1, text );
}
/**
* Print an error message.
*/
public void error( String meth, String text1, String text2 ) {
double time = 0.0d;
if (EventManager.hasCurrent())
time = getCurrentTime();
InputAgent.logError("Time:%.5f Entity:%s%n%s%n%s%n%s%n",
time, getName(),
meth, text1, text2);
// We don't want the model to keep executing, throw an exception and let
// the higher layers figure out if we should terminate the run or not.
throw new ErrorException("ERROR: %s", getName());
}
/**
* Print a warning message.
*/
public void warning( String meth, String text1, String text2 ) {
double time = 0.0d;
if (EventManager.hasCurrent())
time = getCurrentTime();
InputAgent.logWarning("Time:%.5f Entity:%s%n%s%n%s%n%s%n",
time, getName(),
meth, text1, text2);
}
public OutputHandle getOutputHandle(String outputName) {
if (hasAttribute(outputName))
return attributeMap.get(outputName);
if (hasOutput(outputName))
return new OutputHandle(this, outputName);
return null;
}
public boolean hasOutput(String outputName) {
if (OutputHandle.hasOutput(this.getClass(), outputName))
return true;
if (attributeMap.containsKey(outputName))
return true;
return false;
}
@Output(name = "Name",
description="The unique input name for this entity.")
public String getNameOutput(double simTime) {
return entityName;
}
@Output(name = "Description",
description="A string describing this entity.")
public String getDescription(double simTime) {
return desc.getValue();
}
@Output(name = "SimTime",
description = "The present simulation time.",
unitType = TimeUnit.class)
public double getSimTime(double simTime) {
return simTime;
}
private void addAttribute(String name, AttributeHandle h) {
attributeMap.put(name, h);
}
public boolean hasAttribute(String name) {
return attributeMap.containsKey(name);
}
public void setAttribute(String name, double value) {
AttributeHandle h = attributeMap.get(name);
if (h == null) return; // TODO: report this as an error?
h.setValue(value);
}
public ArrayList<String> getAttributeNames(){
ArrayList<String> ret = new ArrayList<String>();
for (String name : attributeMap.keySet()) {
ret.add(name);
}
return ret;
}
}
|
package com.sorakasugano.pasteboard;
import java.util.*;
import redis.clients.jedis.*;
import com.sorakasugano.pasteboard.Reader;
public class Getter extends Reader<Map<String, String>> {
@Override
public Map<String, String> call(Jedis jedis) throws Exception {
String key = type + ":" + id;
if (!jedis.exists(key)) return null;
Map<String, String> out = jedis.hgetAll(key);
out.put("id", id);
return out;
}
}
|
package cpw.mods.fml.client;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.FileResourcePack;
import net.minecraft.client.resources.FolderResourcePack;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.crash.CrashReport;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.SharedDrawable;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ICrashCallable;
import cpw.mods.fml.common.ProgressManager;
import cpw.mods.fml.common.ProgressManager.ProgressBar;
import cpw.mods.fml.common.asm.FMLSanityChecker;
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public class SplashProgress
{
private static Drawable d;
private static volatile boolean pause = false;
private static volatile boolean done = false;
private static Thread thread;
private static volatile Throwable threadError;
private static int angle = 0;
private static final Lock lock = new ReentrantLock(true);
private static SplashFontRenderer fontRenderer;
private static final IResourcePack mcPack = Minecraft.getMinecraft().mcDefaultResourcePack;
private static final IResourcePack fmlPack = createFmlResourcePack();
private static int fontTexture;
private static ResourceLocation fontLocation = new ResourceLocation("textures/font/ascii.png");
private static int logoTexture;
private static ResourceLocation logoLocation = new ResourceLocation("textures/gui/title/mojang.png");
private static int forgeTexture;
private static ResourceLocation forgeLocation = new ResourceLocation("fml", "textures/gui/forge.png");
private static ResourceLocation configLocation = new ResourceLocation("fml", "splash.properties");
private static final Properties config = loadConfig();
private static final boolean enabled = Boolean.parseBoolean(config.getProperty("enabled"));
private static final int backgroundColor = getInt("background");
private static final int fontColor = getInt("font");
private static final int barBorderColor = getInt("barBorder");
private static final int barColor = getInt("bar");
private static final int barBackgroundColor = getInt("barBackground");
public static void start()
{
if(!enabled) return;
// getting debug info out of the way, while we still can
FMLCommonHandler.instance().registerCrashCallable(new ICrashCallable()
{
public String call() throws Exception
{
return "' Vendor: '" + GL11.glGetString(GL11.GL_VENDOR) +
"' Version: '" + GL11.glGetString(GL11.GL_VERSION) +
"' Renderer: '" + GL11.glGetString(GL11.GL_RENDERER) +
"'";
}
public String getLabel()
{
return "GL info";
}
});
CrashReport report = CrashReport.makeCrashReport(new Throwable(), "Loading screen debug info");
System.out.println(report.getCompleteReport());
fontTexture = GL11.glGenTextures();
loadTexture(mcPack, fontTexture, fontLocation);
logoTexture = GL11.glGenTextures();
loadTexture(mcPack, logoTexture, logoLocation);
forgeTexture = GL11.glGenTextures();
loadTexture(fmlPack, forgeTexture, forgeLocation);
try
{
d = new SharedDrawable(Display.getDrawable());
Display.getDrawable().releaseContext();
d.makeCurrent();
}
catch (LWJGLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
Thread mainThread = Thread.currentThread();
thread = new Thread(new Runnable()
{
private final int barWidth = 400;
private final int barHeight = 20;
private final int textHeight2 = 20;
private final int barOffset = 55;
public void run()
{
setGL();
while(!done)
{
ProgressBar first = null, penult = null, last = null;
Iterator<ProgressBar> i = ProgressManager.barIterator();
while(i.hasNext())
{
if(first == null) first = i.next();
else
{
penult = last;
last = i.next();
}
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
// matrix setup
int w = Display.getWidth();
int h = Display.getHeight();
GL11.glViewport(0, 0, w, h);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(320 - w/2, 320 + w/2, 240 + h/2, 240 - h/2, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
// mojang logo
setColor(backgroundColor);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, logoTexture);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(320 - 256, 240 - 256);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(320 - 256, 240 + 256);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(320 + 256, 240 + 256);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(320 + 256, 240 - 256);
GL11.glEnd();
GL11.glDisable(GL11.GL_TEXTURE_2D);
// bars
if(first != null)
{
GL11.glPushMatrix();
GL11.glTranslatef(320 - (float)barWidth / 2, 310, 0);
drawBar(first);
if(penult != null)
{
GL11.glTranslatef(0, barOffset, 0);
drawBar(penult);
}
if(last != null)
{
GL11.glTranslatef(0, barOffset, 0);
drawBar(last);
}
GL11.glPopMatrix();
}
angle += 1;
// forge logo
setColor(backgroundColor);
GL11.glTranslatef(680, 420, 0);
GL11.glRotatef(angle, 0, 0, 1);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, forgeTexture);
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(-50, -50);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(-50, 50);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(50, 50);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(50, -50);
GL11.glEnd();
GL11.glDisable(GL11.GL_TEXTURE_2D);
Display.update();
if(pause)
{
clearGL();
setGL();
}
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
}
clearGL();
}
private void setColor(int color)
{
GL11.glColor3ub((byte)((color >> 16) & 0xFF), (byte)((color >> 8) & 0xFF), (byte)(color & 0xFF));
}
private void drawBox(int w, int h)
{
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2f(0, 0);
GL11.glVertex2f(0, h);
GL11.glVertex2f(w, h);
GL11.glVertex2f(w, 0);
GL11.glEnd();
}
private void drawBar(ProgressBar b)
{
GL11.glPushMatrix();
// title - message
setColor(fontColor);
GL11.glScalef(2, 2, 1);
GL11.glEnable(GL11.GL_TEXTURE_2D);
fontRenderer.drawString(b.getTitle() + " - " + b.getMessage(), 0, 0, 0x000000);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glPopMatrix();
// border
GL11.glPushMatrix();
GL11.glTranslatef(0, textHeight2, 0);
setColor(barBorderColor);
drawBox(barWidth, barHeight);
// interior
setColor(barBackgroundColor);
GL11.glTranslatef(1, 1, 0);
drawBox(barWidth - 2, barHeight - 2);
// slidy part
setColor(barColor);
drawBox((barWidth - 2) * b.getStep() / b.getSteps(), barHeight - 2);
// progress text
String progress = "" + b.getStep() + "/" + b.getSteps();
GL11.glTranslatef(((float)barWidth - 2 - fontRenderer.getStringWidth(progress))/ 2, 2, 0);
setColor(fontColor);
GL11.glScalef(2, 2, 1);
GL11.glEnable(GL11.GL_TEXTURE_2D);
fontRenderer.drawString(progress, 0, 0, 0x000000);
GL11.glPopMatrix();
}
private void setGL()
{
lock.lock();
try
{
Display.getDrawable().makeCurrent();
}
catch (LWJGLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
GL11.glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_TEXTURE_2D);
if(fontRenderer == null)
{
fontRenderer = new SplashFontRenderer();
}
GL11.glDisable(GL11.GL_TEXTURE_2D);
}
private void clearGL()
{
Minecraft mc = Minecraft.getMinecraft();
mc.displayWidth = Display.getWidth();
mc.displayHeight = Display.getHeight();
mc.resize(mc.displayWidth, mc.displayHeight);
GL11.glClearColor(1, 1, 1, 1);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glAlphaFunc(GL11.GL_GREATER, .1f);
try
{
Display.getDrawable().releaseContext();
}
catch (LWJGLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
finally
{
lock.unlock();
}
}
});
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
FMLLog.log(Level.ERROR, e, "Splash thread Exception");
threadError = e;
}
});
thread.start();
checkThreadState();
}
private static void checkThreadState()
{
if(thread.getState() == Thread.State.TERMINATED || threadError != null)
{
throw new IllegalStateException("Splash thread", threadError);
}
}
/**
* Call before you need to explicitly modify GL context state during loading.
* Resource loading doesn't usually require this call.
* Call {@link #resume()} when you're done.
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static void pause()
{
if(!enabled) return;
checkThreadState();
pause = true;
lock.lock();
try
{
d.releaseContext();
Display.getDrawable().makeCurrent();
}
catch (LWJGLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* @deprecated not a stable API, will break, don't use this yet
*/
@Deprecated
public static void resume()
{
if(!enabled) return;
checkThreadState();
pause = false;
try
{
Display.getDrawable().releaseContext();
d.makeCurrent();
}
catch (LWJGLException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
lock.unlock();
}
public static void finish()
{
if(!enabled) return;
checkThreadState();
try
{
done = true;
thread.join();
d.releaseContext();
Display.getDrawable().makeCurrent();
GL11.glDeleteTextures(fontTexture);
GL11.glDeleteTextures(logoTexture);
GL11.glDeleteTextures(forgeTexture);
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
}
private static IResourcePack createFmlResourcePack()
{
if(FMLSanityChecker.fmlLocation.isDirectory())
{
return new FolderResourcePack(FMLSanityChecker.fmlLocation);
}
else
{
return new FileResourcePack(FMLSanityChecker.fmlLocation);
}
}
private static Properties loadConfig()
{
InputStream s = null;
try
{
s = fmlPack.getInputStream(configLocation);
Properties config = new Properties();
config.load(s);
return config;
}
catch(IOException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
finally
{
IOUtils.closeQuietly(s);
}
}
private static int getInt(String name)
{
return Integer.decode(config.getProperty(name));
}
private static void loadTexture(IResourcePack pack, int name, ResourceLocation location)
{
InputStream s = null;
try
{
s = pack.getInputStream(location);
TextureUtil.uploadTextureImageAllocate(name, ImageIO.read(pack.getInputStream(location)), false, false);
}
catch(IOException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
finally
{
IOUtils.closeQuietly(s);
}
}
private static class SplashFontRenderer extends FontRenderer
{
public SplashFontRenderer()
{
super(Minecraft.getMinecraft().gameSettings, fontLocation, null, false);
super.onResourceManagerReload(null);
}
@Override
protected void bindTexture(ResourceLocation location)
{
if(location != locationFontTexture) throw new IllegalArgumentException();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTexture);
}
@Override
protected InputStream getResourceInputStream(ResourceLocation location) throws IOException
{
return Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(location);
}
}
public static void drawVanillaScreen() throws LWJGLException
{
if(!enabled)
{
Minecraft.getMinecraft().loadScreen();
}
}
public static void clearVanillaResources(TextureManager renderEngine, ResourceLocation mojangLogo)
{
if(!enabled)
{
renderEngine.deleteTexture(mojangLogo);
}
}
}
|
package de.davherrmann.immutable;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.emptyList;
import static org.apache.commons.lang3.ClassUtils.isAssignable;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.base.Defaults;
import com.google.common.collect.ImmutableMap;
@com.google.gson.annotations.JsonAdapter(ImmutableTypeAdapter.class)
public class Immutable<I>
{
private final Class<I> type;
private final NextImmutable nextImmutable = new NextImmutable();
private final PathRecorder<I> pathRecorder;
private final Map<String, Object> values;
public Immutable(Class<I> type)
{
this(type, newHashMap(), new PathRecorder<>(type));
}
private Immutable(Class<I> type, Map<String, Object> initialValues, PathRecorder<I> pathRecorder)
{
this.values = initialValues;
this.type = type;
this.pathRecorder = pathRecorder;
}
public I path()
{
return pathRecorder.path();
}
public I asObject()
{
return immutableFor(type, emptyList());
}
public <T> In<T> in(Function<I, Supplier<T>> pathToMethod)
{
return in(pathToMethod.apply(path()));
}
public <T> In<T> in(Supplier<T> method)
{
// TODO can we rely on method as defaultValue?
final T defaultValue = method.get();
return new In<>(pathRecorder.pathFor(method), defaultValue);
}
public <T> InList<T> inList(Function<I, Supplier<List<T>>> pathToMethod)
{
return inList(pathToMethod.apply(path()));
}
public <T> InList<T> inList(Supplier<List<T>> method)
{
final List<T> defaultValue = method.get();
return new InList<>(pathRecorder.pathFor(method), defaultValue);
}
public <T> T get(Function<I, Supplier<T>> method)
{
return get(method.apply(path()));
}
@SuppressWarnings("unchecked")
public <T> T get(Supplier<T> method)
{
return (T) nextImmutable.getInPath(values, pathRecorder.pathFor(method));
}
public Immutable<I> diff(Immutable<I> immutable)
{
return new Immutable<>(type, nextImmutable.diff(values, immutable.values()), pathRecorder);
}
public Immutable<I> clear()
{
return new Immutable<>(type, ImmutableMap.of(), pathRecorder);
}
public class In<T>
{
private final List<String> path;
private final Object defaultValue;
public In(List<String> path, Object defaultValue)
{
this.path = path;
this.defaultValue = defaultValue;
}
public Immutable<I> set(T value)
{
return new Immutable<>(type, nextImmutable.setIn(values, path, immutableNodeOr(value)), pathRecorder);
}
public Immutable<I> set(Immutable<T> immutableValue)
{
return set(immutableValue.asObject());
}
@SuppressWarnings("unchecked")
public Immutable<I> update(Function<T, T> updater)
{
return new Immutable<>(
type,
nextImmutable.updateIn(
values,
path,
value -> updater.apply((T) (value == null
? defaultValue
: value))),
pathRecorder);
}
private Object immutableNodeOr(T value)
{
return value instanceof ImmutableNode
? ((ImmutableNode) value).values()
: value;
}
}
public class InList<LT>
{
private final List<String> path;
private final List<LT> defaultValue;
public InList(List<String> path, List<LT> defaultValue)
{
this.path = path;
this.defaultValue = defaultValue;
}
public Immutable<I> set(List<LT> value)
{
return new Immutable<>(type, nextImmutable.setIn(values, path, value), pathRecorder);
}
public Immutable<I> set(ImmutableList<LT> value)
{
return set(value.asList());
}
@SuppressWarnings("unchecked")
public Immutable<I> update(Function<ImmutableList<LT>, ImmutableList<LT>> updater)
{
return new Immutable<>(
type,
nextImmutable.updateIn(
values,
path,
value -> updater.apply(value == null
? new ImmutableList<>()
: new ImmutableList<LT>()
.addAll((List<LT>) value))
.asList()),
pathRecorder);
}
// TODO check for redundant code!
@SuppressWarnings("unchecked")
public Immutable<I> updateList(Function<List<LT>, List<LT>> updater)
{
return new Immutable<>(
type,
nextImmutable.updateIn(
values,
path,
value -> updater.apply(value == null
? defaultValue
: (List<LT>) value)),
pathRecorder);
}
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Immutable<?> immutable = (Immutable<?>) o;
return Objects.equals(type, immutable.type) && Objects.equals(values, immutable.values);
}
@Override
public int hashCode()
{
return Objects.hash(type, values);
}
protected Map<String, Object> values()
{
return values;
}
@SuppressWarnings("unchecked")
private <T> T immutableFor(Class<T> type, List<String> nestedPath)
{
return (T) Proxy.newProxyInstance(
ImmutableNode.class.getClassLoader(),
new Class<?>[]{type, ImmutableNode.class},
new ImmutableObjectInvocationHandler(nestedPath)
);
}
private class ImmutableObjectInvocationHandler extends AbstractPathInvocationHandler
{
public ImmutableObjectInvocationHandler(List<String> path)
{
super(path);
}
@Override
protected Object handleInvocation(List<String> path, Method method) throws Throwable
{
if (method.getName().equals("values"))
{
return path.isEmpty()
? values
: nextImmutable.getInPath(values, path);
}
final List<String> pathWithMethod = pathWith(method);
final Class<?> returnType = method.getReturnType();
final Object value = nextImmutable.getInPath(values, pathWithMethod);
final Object returnValue = value == null
? Defaults.defaultValue(returnType)
: value;
final boolean isCastable = returnValue == null || isAssignable(returnValue.getClass(), returnType);
return isCastable
? returnValue
: immutableFor(returnType, pathWithMethod);
}
}
interface ImmutableNode
{
Map<String, Object> values();
}
}
|
package de.tblsoft.solr.pipeline;
import de.tblsoft.solr.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class XmlReader extends AbstractReader {
private static Logger LOG = LoggerFactory.getLogger(XmlReader.class);
@Override
public void read() {
String currentFileName = null;
try {
String deprecatedFilename = getProperty("filename", null);
List<String> filenames = getPropertyAsList("filenames", new ArrayList<>());
if(deprecatedFilename != null) {
filenames.add(deprecatedFilename);
}
List<String> fileList = new ArrayList<>();
for(String filename : filenames) {
String absoluteFilename = IOUtils.getAbsoluteFile(getBaseDir(), filename);
fileList.addAll(IOUtils.getFiles(absoluteFilename));
}
XMLReader myReader = XMLReaderFactory.createXMLReader();
ContentHandler mySerializer = new PipelineSaxContentHandler(executer);
boolean firstFile = true;
TransformerHandler lastHandler = null;
List<String> transformationFiles = getPropertyAsList("transformations", new ArrayList<>());
for (String file : transformationFiles) {
TransformerHandler currentHandler = getTransformerHandler(file);
if (firstFile) {
firstFile = false;
myReader.setContentHandler(currentHandler);
lastHandler = currentHandler;
continue;
}
lastHandler.setResult(new SAXResult(currentHandler));
lastHandler = currentHandler;
}
if (lastHandler == null) {
myReader.setContentHandler(mySerializer);
} else {
lastHandler.setResult(new SAXResult(mySerializer));
}
for (String sourceFile : fileList) {
currentFileName = sourceFile;
InputStream in = IOUtils.getInputStream(sourceFile);
myReader.parse(new InputSource(in));
in.close();
}
} catch(Exception e){
LOG.error("Could not process file: " + currentFileName + " because of: " + e.getMessage(), e );
throw new RuntimeException(e);
}
}
TransformerHandler getTransformerHandler(String fileName) throws TransformerConfigurationException {
fileName = IOUtils.getAbsoluteFile(getBaseDir(),fileName);
if(fileName.endsWith(".stx")) {
SAXTransformerFactory stxFactory = new net.sf.joost.trax.TransformerFactoryImpl();
return stxFactory.newTransformerHandler(new StreamSource(fileName));
}
if(fileName.endsWith(".xsl")) {
SAXTransformerFactory xslFactory = (SAXTransformerFactory) TransformerFactory.newInstance();;
return xslFactory.newTransformerHandler(new StreamSource(fileName));
}
throw new IllegalArgumentException("Only the filetypes xsl and stx are supported.");
}
}
|
package edu.isi.karma.rdf;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;
import edu.isi.karma.imp.json.JsonImport;
import edu.isi.karma.kr2rml.ErrorReport;
import edu.isi.karma.kr2rml.KR2RMLMapping;
import edu.isi.karma.kr2rml.KR2RMLWorksheetRDFGenerator;
import edu.isi.karma.kr2rml.R2RMLMappingIdentifier;
import edu.isi.karma.kr2rml.WorksheetR2RMLJenaModelParser;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.rep.WorkspaceManager;
import edu.isi.karma.util.JSONUtil;
import edu.isi.karma.webserver.ExecutionController;
import edu.isi.karma.webserver.KarmaException;
import edu.isi.karma.webserver.WorkspaceRegistry;
public class JSONRDFGenerator {
private HashMap<String, R2RMLMappingIdentifier> modelIdentifiers;
private HashMap<String, WorksheetR2RMLJenaModelParser> readModelParsers;
private Workspace workspace;
private JSONRDFGenerator() {
this.modelIdentifiers = new HashMap<String, R2RMLMappingIdentifier>();
this.readModelParsers = new HashMap<String, WorksheetR2RMLJenaModelParser>();
this.workspace = WorkspaceManager.getInstance().createWorkspace();
WorkspaceRegistry.getInstance().register(new ExecutionController(this.workspace));
}
private static JSONRDFGenerator instance = null;
public static JSONRDFGenerator getInstance() {
if(instance == null) {
instance = new JSONRDFGenerator();
}
return instance;
}
public void addModel(R2RMLMappingIdentifier modelIdentifier) {
this.modelIdentifiers.put(modelIdentifier.getName(), modelIdentifier);
}
public void generateRDF(String sourceName, String jsonData, boolean addProvenance, PrintWriter pw) throws KarmaException, JSONException, IOException {
R2RMLMappingIdentifier id = this.modelIdentifiers.get(sourceName);
if(id == null) {
throw new KarmaException("Cannot generate RDF. Model named " + sourceName + " does not exist");
}
//Generate worksheet from the json data
Object json = JSONUtil.createJson(jsonData);
JsonImport imp = new JsonImport(json, sourceName, workspace, "utf-8", -1);
Worksheet worksheet = imp.generateWorksheet();
//Check if the parser for this model exists, else create one
WorksheetR2RMLJenaModelParser modelParser = readModelParsers.get(sourceName);
if(modelParser == null) {
modelParser = loadModel(id);
}
//Generate mappping data for the worksheet using the model parser
KR2RMLMapping mapping = modelParser.parse(worksheet, workspace);
//Generate RDF using the mapping data
ErrorReport errorReport = new ErrorReport();
KR2RMLWorksheetRDFGenerator rdfGen = new KR2RMLWorksheetRDFGenerator(worksheet,
workspace.getFactory(), workspace.getOntologyManager(), pw,
mapping.getAuxInfo(), errorReport, addProvenance);
rdfGen.generateRDF(false);
}
private WorksheetR2RMLJenaModelParser loadModel(R2RMLMappingIdentifier modelIdentifier) throws JSONException, KarmaException {
WorksheetR2RMLJenaModelParser parser = new WorksheetR2RMLJenaModelParser(modelIdentifier);
this.readModelParsers.put(modelIdentifier.getName(), parser);
return parser;
}
}
|
package edu.uib.info310.util;
import java.io.File;
import java.io.FileOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import edu.uib.info310.sparql.QueryEndPoint;
import edu.uib.info310.sparql.QueryEndPointImp;
/**
* Class for getting artist information from BBC and DBPedia
* @author torsteinthune
*/
public abstract class GetArtistInfo implements QueryEndPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(GetArtistInfo.class);
public static String prefix = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
"PREFIX mo: <http://purl.org/ontology/mo/>" +
"PREFIX dbpedia: <http://dbpedia.org/property/>" +
"PREFIX dbont: <http://dbpedia.org/ontology/>" +
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema
"PREFIX owl: <http://www.w3.org/2002/07/owl
/**
* Returns a model with data from BBC_MUSIC SPARQL search
* @returns a Model
*/
public static Model BBCMusic(String artistName) throws Exception{
if(artistName.isEmpty()){
throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo");
}
else {
QueryEndPoint qep = new QueryEndPointImp();
String constructStr = "CONSTRUCT {} WHERE {}";
String queryStr = "DESCRIBE ?artist WHERE { " +
"?artist foaf:name \""+ artistName + "\". " +
" }";
qep.setQuery(prefix + queryStr);
qep.setEndPoint(QueryEndPoint.BBC_MUSIC);
Model model = qep.describeStatement();
LOGGER.debug("BBC search found " + model.size() + " statements" );
// FileOutputStream out = new FileOutputStream(new File("log/bbcout.ttl"));
// model.write(out, "TURTLE");
return model;
}
}
public static Model BBCMusic(String artistName, String artistUri) throws Exception{
if(artistName.isEmpty()){
throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo");
}
else {
QueryEndPoint qep = new QueryEndPointImp();
String artist = "<" + artistUri + ">";
String constructStr = "CONSTRUCT { "+artist+" " +
"mo:fanpage ?fanpage ; " +
"mo:imdb ?imdb ; " +
"mo:myspace ?myspace ; " +
"mo:homepage ?homepage ; " +
"rdfs:comment ?comment ; " +
"mo:image ?image ;" +
"owl:sameAs ?artist" +
"} " ;
String whereStr =" WHERE {?artist foaf:name \"" + artistName + "\" " + "." +
"OPTIONAL{?artist mo:fanpage ?fanpage}" +
"OPTIONAL{?artist mo:imdb ?imdb}" +
"OPTIONAL{?artist mo:myspace ?myspace}" +
"OPTIONAL{?artist foaf:homepage ?homepage}" +
"OPTIONAL{?artist rdfs:comment ?comment. FILTER (lang(?comment) = '')}" +
"OPTIONAL{?artist mo:image ?image}}";
LOGGER.debug("Sending Query: " + prefix + constructStr + whereStr );
qep.setQuery(prefix + constructStr + whereStr);
qep.setEndPoint(QueryEndPoint.BBC_MUSIC);
Model model = qep.describeStatement();
LOGGER.debug("BBC with URI search found " + model.size() + " statements" );
FileOutputStream out = new FileOutputStream(new File("log/bbcout.ttl"));
model.write(out, "TURTLE");
return model;
}
}
/**
* Returns a model with data from DB_PEDIA SPARQL search
* @returns a Model
*/
public static Model DBPedia(String artistName) throws Exception{
if(artistName.isEmpty()){
throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo");
}
else {
QueryEndPoint qep = new QueryEndPointImp();
// Fanger ikke opp Michael Jacksom siden han er oppfrt med foaf:name Michael Joseph Jackson
String queryStr = "DESCRIBE ?artist WHERE { " +
"?artist foaf:name \""+ artistName + "\"@en. " +
" }";
qep.setQuery(prefix + queryStr);
qep.setEndPoint(QueryEndPoint.DB_PEDIA);
Model model = qep.describeStatement();
LOGGER.debug("DBPedia search found " + model.size() + " statements" );
// FileOutputStream out = new FileOutputStream(new File("log/dbpediaout.ttl"));
// model.write(out, "TURTLE");
return model;
}
}
public static Model DBPedia(String artistName, String artistUri) throws Exception{
if(artistName.isEmpty()){
throw new NullPointerException("artistName cannot be empty string in GetArtistInfo.DbPediaArtistInfo");
}
else {
QueryEndPoint qep = new QueryEndPointImp();
// Fanger ikke opp Michael Jacksom siden han er oppfrt med foaf:name Michael Joseph Jackson
String artist = "<" + artistUri + ">";
String constructStr = "CONSTRUCT { "+artist +" " +
"rdfs:comment ?comment ; " +
"mo:biography ?bio ; " +
"dbont:birthname ?birthname ; " +
"dbont:hometown ?hometown ; " +
"mo:origin ?origin ; " +
"mo:activity_start ?start; " +
"mo:activity_end ?end ;" +
"dbont:birthDate ?birth ;" +
"dbont:deathDate ?death ;" +
"mo:wikipedia ?wikipedia ;" +
"owl:sameAs ?artist" ;
String whereStr ="} WHERE {?artist foaf:name \"" + artistName + "\"@en." +
"OPTIONAL{?artist dbpedia:shortDescription ?comment} . " +
"OPTIONAL{?artist dbont:abstract ?bio . FILTER(lang(?bio) = 'en')} . " +
"OPTIONAL{?artist dbont:birthname ?birthname} ." +
"OPTIONAL{?artist dbont:hometown ?hometown} ." +
"OPTIONAL{?artist dbpedia:origin ?origin} ." +
"OPTIONAL{?artist dbont:activeYearsEndYear ?end} ." +
"OPTIONAL{?artist dbont:activeYearsStartYear ?start} ." +
"OPTIONAL{?artist dbont:birthDate ?birth} ." +
"OPTIONAL{?artist dbont:deathDate ?death} ." +
"OPTIONAL{?artist foaf:page ?wikipedia}" +
"FILTER(rdf:type(?artist) = dbont:Artist)}";
qep.setQuery(prefix + constructStr + whereStr);
qep.setEndPoint(QueryEndPoint.DB_PEDIA);
Model model = qep.describeStatement();
LOGGER.debug("DBPedia search found " + model.size() + " statements" );
return model;
}
}
public static void main(String[] args) throws Exception{
LOGGER.debug("started query");
Model test = ModelFactory.createDefaultModel();
test.add(BBCMusic("Moby"));
test.add(DBPedia("Moby"));
LOGGER.debug("ended query");
FileOutputStream out = new FileOutputStream(new File("log/getartistinfoout.ttl"));
test.write(out, "TURTLE");
}
}
|
package fr.insee.stamina.cpc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDFS;
import org.apache.jena.vocabulary.SKOS;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.healthmarketscience.jackcess.Cursor;
import com.healthmarketscience.jackcess.CursorBuilder;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;
import fr.insee.stamina.utils.Names;
import fr.insee.stamina.utils.XKOS;
public class CPCModelMaker {
/** Files containing the Access databases */
public static Map<String, String> CPC_ACCESS_FILE = new HashMap<String, String>();
/** Name of the Access tables containing the data */
public static Map<String, String> CPC_ACCESS_TABLE = new HashMap<String, String>();
/** Labels for the concept schemes representing the classification versions */
public static Map<String, String> CPC_SCHEME_LABEL = new HashMap<String, String>();
/** Notations for the concept schemes representing the classification versions */
public static Map<String, String> CPC_SCHEME_NOTATION = new HashMap<String, String>();
// There are no French labels for the CPC on the UNSD web site
/** CSV files containing the additional Spanish labels */
public static Map<String, String> CPC_SPANISH_LABELS_FILE = new HashMap<String, String>();
// Initialization of the static properties
static {
CPC_ACCESS_FILE.put("1.1", "D:\\Temp\\unsd\\cpc_v11_english.mdb");
CPC_ACCESS_FILE.put("2", "D:\\Temp\\unsd\\CPCv2_english.mdb");
CPC_ACCESS_FILE.put("2.1", "D:\\Temp\\unsd\\CPC21_english.mdb");
CPC_ACCESS_TABLE.put("1.1", "tblTitles_English_CPCV11");
CPC_ACCESS_TABLE.put("2", "CPC2-structure");
CPC_ACCESS_TABLE.put("2.1", "CPC21-structure");
CPC_SCHEME_LABEL.put("1.1", "Central Product Classification - Ver.1.1");
CPC_SCHEME_LABEL.put("2", "Central Product Classification - Ver.2");
CPC_SCHEME_LABEL.put("2.1", "Central Product Classification - Ver.2.1");
CPC_SCHEME_NOTATION.put("1.1", "CPC Ver.1.1");
CPC_SCHEME_NOTATION.put("2", "CPC Ver.2");
CPC_SCHEME_NOTATION.put("2.1", "CPC Ver 2.1");
CPC_SPANISH_LABELS_FILE.put("1.1", null); // No Spanish labels for CPC Ver.1.1
CPC_SPANISH_LABELS_FILE.put("2", "CPCv2_Spanish_structure.txt");
CPC_SPANISH_LABELS_FILE.put("2.1", null); // No Spanish labels for CPC Ver.2.1
}
// TODO Add correspondence between CPC Ver.1.1 and CPC Ver.2
/** CSV file containing the correspondences between CPC Ver.2 and CPC Ver.2.1 */
public static String CPC2_TO_CPC21_FILE = "D:\\Temp\\unsd\\cpc2-cpc21.txt";
/** Base URIs for RDF resources in correspondences. */
public final static String CPC2_TO_CPC21_BASE_URI = "http://stamina-project.org/codes/cpc2-cpc21/";
/** File where the CPC Ver.2 to CPC Ver.2.1 correspondence information is saved as Turtle */
private static String CPC2_TO_CPC21_TTL = "src/main/resources/data/cpc2-cpc21.ttl";
/** Log4J2 logger */
private static final Logger logger = LogManager.getLogger(CPCModelMaker.class);
/** Names of the items for each level, singular and plural */
private static String[] levelNames = new String[]{"section", "division", "group", "class", "subclass", "sections", "divisions", "groups", "classes", "subclasses"};
/** Current Jena model */
private Model cpcModel = null;
/** Resource corresponding to the current concept scheme */
private Resource scheme = null;
/** List of resources corresponding to the current classification levels */
private List<Resource> levels = null;
/**
* Main method: basic launcher that produces all the models.
*
* @param args Not used.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
CPCModelMaker modelMaker = new CPCModelMaker();
logger.debug("New CPCModelMaker instance created");
modelMaker.createCPCModel("1.1", true);
modelMaker.createCPCModel("2", false);
modelMaker.createCPCModel("2.1", false);
modelMaker.createCorrespondenceModels();
logger.debug("Program terminated");
}
/**
* Creates an Jena model corresponding to a version of CPC and saves it to a Turtle file.
*
* @throws Exception In case of problem getting the data or creating the file.
*/
private void createCPCModel(String version, boolean withNotes) throws Exception {
logger.debug("Construction of the Jena model for CPC version " + version);
String baseURI = Names.getCSBaseURI("CPC", version);
// Init the Jena model for the given version of the classification
initModel(version);
// For CPC, the naming of the columns in the tables between different versions is not coherent
String codeColumnName = ("2.1".equals(version)) ? "CPC21code" : "Code";
String labelColumnName = ("2.1".equals(version)) ? "CPC21title" : "Description";
String noteColumnName = ("2.1".equals(version)) ? "CPC21ExplanatoryNote" : "ExplanatoryNote";
// Open a cursor on the main table and iterate through all the records
Table table = DatabaseBuilder.open(new File(CPC_ACCESS_FILE.get(version))).getTable(CPC_ACCESS_TABLE.get(version));
Cursor cursor = CursorBuilder.createCursor(table);
logger.debug("Cursor defined on table " + CPC_ACCESS_TABLE.get(version));
for (Row row : cursor.newIterable()) {
String itemCode = row.getString(codeColumnName);
Resource itemResource = cpcModel.createResource(getItemURI(itemCode, baseURI), SKOS.Concept);
itemResource.addProperty(SKOS.notation, cpcModel.createLiteral(itemCode));
itemResource.addProperty(SKOS.prefLabel, cpcModel.createLiteral(row.getString(labelColumnName), "en"));
// Add explanatory notes if requested
// TODO For CPC Ver.2 and CPC Ver.2.1, all notes together in one column. For now all is recorded as a skos:skosNote
if (withNotes) {
String note = row.getString(noteColumnName + "ExplanatoryNote");
if ((note != null) && (note.length() > 0)) itemResource.addProperty(SKOS.scopeNote, cpcModel.createLiteral(note, "en"));
}
// Create the SKOS hierarchical properties for the item
itemResource.addProperty(SKOS.inScheme, scheme);
String parentCode = getParentCode(itemCode);
if (parentCode == null) {
scheme.addProperty(SKOS.hasTopConcept, itemResource);
itemResource.addProperty(SKOS.topConceptOf, scheme);
} else {
Resource parentResource = cpcModel.createResource(getItemURI(parentCode, baseURI), SKOS.Concept);
parentResource.addProperty(SKOS.narrower, itemResource);
itemResource.addProperty(SKOS.broader, parentResource);
}
// Add the item as a member of its level
Resource level = levels.get(itemCode.length() - 1);
level.addProperty(SKOS.member, itemResource);
}
logger.debug("Preparing to create additional Spanish labels");
this.addLabels(CPC_SPANISH_LABELS_FILE.get(version), version, "es");
// Write the Turtle file and clear the model
String turtleFileName = "src/main/resources/data/" + Names.getCSContext("CPC", version) + ".ttl";
cpcModel.write(new FileOutputStream(turtleFileName), "TTL");
logger.debug("The Jena model for CPC Ver." + version + " has been written to " + turtleFileName);
cpcModel.close();
}
/**
* Initializes the Jena model with the namespaces and the top resources (concept scheme, levels, ...).
*
* @param version The CPC version corresponding to the model.
*/
private void initModel(String version) {
cpcModel = ModelFactory.createDefaultModel();
cpcModel.setNsPrefix("skos", SKOS.getURI());
cpcModel.setNsPrefix("xkos", XKOS.getURI());
// Create the classification, classification levels and their properties
String baseURI = Names.getCSBaseURI("CPC", version);
String schemeLabel = CPC_SCHEME_LABEL.get(version);
scheme = cpcModel.createResource(getSchemeURI(version), SKOS.ConceptScheme);
scheme.addProperty(SKOS.prefLabel, cpcModel.createLiteral(schemeLabel, "en"));
scheme.addProperty(SKOS.notation, CPC_SCHEME_NOTATION.get(version));
int numberOfLevels = levelNames.length / 2;
scheme.addProperty(XKOS.numberOfLevels, cpcModel.createTypedLiteral(numberOfLevels));
levels = new ArrayList<Resource>();
for (int levelIndex = 1; levelIndex <= numberOfLevels; levelIndex++) {
String levelName = levelNames[levelIndex + 3];
Resource level = cpcModel.createResource(baseURI + levelNames[levelIndex + 3], XKOS.ClassificationLevel);
level.addProperty(SKOS.prefLabel, cpcModel.createLiteral(schemeLabel + " - " + levelName.substring(0, 1).toUpperCase() + levelName.substring(1), "en"));
level.addProperty(XKOS.depth, cpcModel.createTypedLiteral(levelIndex));
levels.add(level);
}
scheme.addProperty(XKOS.levels, cpcModel.createList(levels.toArray(new Resource[levels.size()])));
}
/**
* Adds labels read in a CSV file to the Jena model.
*
* @param filePath The path of the CSV file.
* @param version The version of the CPC classification.
* @param language The tag representing the language of the labels ("fr", "es", etc.).
*/
private void addLabels(String filePath, String version, String language) {
if (filePath == null) return;
String baseURI = Names.getCSBaseURI("CPC", version);
try {
Reader reader = new InputStreamReader(new FileInputStream(filePath), "Cp1252");
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader());
for (CSVRecord record : parser) {
String itemCode = record.get(0);
Resource itemResource = cpcModel.createResource(getItemURI(itemCode, baseURI));
itemResource.addProperty(SKOS.prefLabel, cpcModel.createLiteral(record.get(1), language));
}
parser.close();
reader.close();
} catch (Exception e) {
logger.error("Error adding labels from " + filePath, e);
}
}
/**
* Creates the models for correspondences between CPC Ver.2 and CPC Ver.2.1.
*/
private void createCorrespondenceModels() {
// Create model for the correspondences between CPC Ver.2 and CPC Ver.2.1
cpcModel = ModelFactory.createDefaultModel();
cpcModel.setNsPrefix("rdfs", RDFS.getURI());
cpcModel.setNsPrefix("skos", SKOS.getURI());
cpcModel.setNsPrefix("xkos", XKOS.getURI());
// Creation of the correspondence table resource
Resource table = cpcModel.createResource(CPC2_TO_CPC21_BASE_URI + "correspondence", XKOS.Correspondence);
// TODO Add properties properly
table.addProperty(SKOS.definition, "CPC Ver.2 - CPC Ver.2.1 correspondence table");
// Comment extracted from the 'readme.txt' file (could be better in a skos:historyNote)
table.addProperty(RDFS.comment, cpcModel.createLiteral("The correspondence does not yet include divisions 61 and 62 of the CPC", "en"));
try {
Reader reader = new FileReader(CPC2_TO_CPC21_FILE);
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader());
for (CSVRecord record : parser) {
String cpc2Code = record.get("CPC2code");
String cpc21Code = record.get("CPC21code");
Resource association = cpcModel.createResource(CPC2_TO_CPC21_BASE_URI + cpc2Code + "-" + cpc21Code, XKOS.ConceptAssociation);
association.addProperty(XKOS.sourceConcept, getItemURI(cpc2Code, Names.getCSBaseURI("CPC", "2")));
association.addProperty(XKOS.targetConcept, getItemURI(cpc21Code, Names.getCSBaseURI("CPC", "2.1")));
// There are no descriptions of the correspondences for CPC2-CPC2.1
table.addProperty(XKOS.madeOf, association);
// TODO Add 'partial' information
}
parser.close();
reader.close();
} catch (Exception e) {
logger.error("Error reading correspondences from " + CPC2_TO_CPC21_FILE, e);
}
// Write the Turtle file and clear the model
try {
cpcModel.write(new FileOutputStream(CPC2_TO_CPC21_TTL), "TTL");
} catch (FileNotFoundException e) {
logger.error("Error saving the CPC2-CPC21 correspondences to " + CPC2_TO_CPC21_TTL, e);
}
cpcModel.close();
}
/**
* Returns the URI of the concept scheme corresponding to a major version of CPC.
*
* @param version The version of the CPC classification.
* @return The URI of the concept scheme.
*/
public static String getSchemeURI(String version) {
return Names.getCSBaseURI("CPC", version) + "cpc";
}
/**
* Computes the URI of an CPC item.
*
* @param code The item code.
* @param baseURI The base URI corresponding to the CPC version.
* @return The item URI, or a blank string if the code type was not recognized.
*/
public static String getItemURI(String code, String baseURI) {
String uri = "";
if ((code == null) || (code.length() == 0)) return uri;
if (code.length() < 6) uri = baseURI + levelNames[code.length() - 1] + "/" + code;
return uri;
}
/**
* Returns the code of the parent of the item whose code is provided.
*
* @param code The code of the item.
* @return The code of the parent of the item.
*/
public static String getParentCode(String code) {
if ((code == null) || (code.length() <= 1)) return null;
return code.substring(0, code.length() - 1);
}
}
|
package hex.deeplearning;
import com.amazonaws.services.cloudfront.model.InvalidArgumentException;
import hex.FrameTask.DataInfo;
import water.*;
import water.api.*;
import water.api.Request.API;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.D3Plot;
import water.util.Log;
import water.util.ModelUtils;
import water.util.Utils;
import java.util.Arrays;
import java.util.Random;
import static java.lang.Double.isNaN;
public class DeepLearningModel extends Model {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help="Model info", json = true)
private volatile DeepLearningModelInfo model_info;
void set_model_info(DeepLearningModelInfo mi) { model_info = mi; }
final public DeepLearningModelInfo model_info() { return model_info; }
@API(help="Job that built the model", json = true)
final private Key jobKey;
@API(help="Time to build the model", json = true)
private long run_time;
final private long start_time;
@API(help="Number of training epochs", json = true)
public double epoch_counter;
@API(help="Number of rows in training data", json = true)
public long training_rows;
@API(help = "Scoring during model building")
private Errors[] errors;
public Errors last_scored() { return errors[errors.length-1]; }
@Override public void delete() {
super.delete();
model_info.delete();
}
public static class Errors extends Iced {
static final int API_WEAVER = 1;
static public DocGen.FieldDoc[] DOC_FIELDS;
@API(help = "How many epochs the algorithm has processed")
public double epoch_counter;
@API(help = "How many rows the algorithm has processed")
public long training_samples;
@API(help = "How long the algorithm ran in ms")
public long training_time_ms;
//training/validation sets
@API(help = "Whether a validation set was provided")
boolean validation;
@API(help = "Number of training set samples for scoring")
public long score_training_samples;
@API(help = "Number of validation set samples for scoring")
public long score_validation_samples;
@API(help="Do classification or regression")
public boolean classification;
// classification
@API(help = "Confusion matrix on training data")
public water.api.ConfusionMatrix train_confusion_matrix;
@API(help = "Confusion matrix on validation data")
public water.api.ConfusionMatrix valid_confusion_matrix;
@API(help = "Classification error on training data")
public double train_err = 1;
@API(help = "Classification error on validation data")
public double valid_err = 1;
@API(help = "AUC on training data")
public AUC trainAUC;
@API(help = "AUC on validation data")
public AUC validAUC;
// regression
@API(help = "Training MSE")
public double train_mse = Double.POSITIVE_INFINITY;
@API(help = "Validation MSE")
public double valid_mse = Double.POSITIVE_INFINITY;
// @API(help = "Training MCE")
// public double train_mce = Double.POSITIVE_INFINITY;
// @API(help = "Validation MCE")
// public double valid_mce = Double.POSITIVE_INFINITY;
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (classification) {
sb.append("Error on training data (misclassification)"
+ (trainAUC != null ? " [using threshold for " + trainAUC.threshold_criterion.toString().replace("_"," ") +"]: ": ": ")
+ String.format("%.2f", 100*train_err) + "%");
if (trainAUC != null) sb.append(", AUC on training data: " + String.format("%.4f", 100*trainAUC.AUC) + "%");
if (validation) sb.append("\nError on validation data (misclassification)"
+ (validAUC != null ? " [using threshold for " + validAUC.threshold_criterion.toString().replace("_"," ") +"]: ": ": ")
+ String.format("%.2f", (100 * valid_err)) + "%");
if (validAUC != null) sb.append(", AUC on validation data: " + String.format("%.4f", 100*validAUC.AUC) + "%");
} else {
sb.append("Error on training data (MSE): " + train_mse);
if (validation) sb.append("\nError on validation data (MSE): " + valid_mse);
}
return sb.toString();
}
}
final private static class ConfMat extends hex.ConfusionMatrix {
final private double _err;
final private double _f1;
public ConfMat(double err, double f1) {
super(null);
_err=err;
_f1=f1;
}
@Override public double err() { return _err; }
@Override public double F1() { return _f1; }
@Override public double[] classErr() { return null; }
}
/** for grid search error reporting */
@Override
public hex.ConfusionMatrix cm() {
final Errors lasterror = last_scored();
if (errors == null) return null;
water.api.ConfusionMatrix cm = lasterror.validation ?
lasterror.valid_confusion_matrix :
lasterror.train_confusion_matrix;
if (cm == null || cm.cm == null) {
if (lasterror.validation) {
return new ConfMat(lasterror.valid_err, lasterror.validAUC != null ? lasterror.validAUC.F1() : 0);
} else {
return new ConfMat(lasterror.train_err, lasterror.trainAUC != null ? lasterror.trainAUC.F1() : 0);
}
}
return new hex.ConfusionMatrix(cm.cm);
}
@Override
public double mse() {
if (errors == null) return super.mse();
return last_scored().validation ? last_scored().valid_mse : last_scored().train_mse;
}
// This describes the model, together with the parameters
// This will be shared: one per node
public static class DeepLearningModelInfo extends Iced {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help="Input data info")
final private DataInfo data_info;
public DataInfo data_info() { return data_info; }
// model is described by parameters and the following 2 arrays
final private float[][] weights; //one 2D weight matrix per layer (stored as a 1D array each)
final private double[][] biases; //one 1D bias array per layer
// helpers for storing previous step deltas
// Note: These two arrays *could* be made transient and then initialized freshly in makeNeurons() and in DeepLearningTask.initLocal()
// But then, after each reduction, the weights would be lost and would have to restart afresh -> not *exactly* right, but close...
private float[][] weights_momenta;
private double[][] biases_momenta;
// helpers for AdaDelta
private float[][] E_dx2;
private float[][] E_g2;
// compute model size (number of model parameters required for making predictions)
// momenta are not counted here, but they are needed for model building
public long size() {
long siz = 0;
for (float[] w : weights) siz += w.length;
for (double[] b : biases) siz += b.length;
return siz;
}
// accessors to (shared) weights and biases - those will be updated racily (c.f. Hogwild!)
boolean has_momenta() { return parameters.momentum_start != 0 || parameters.momentum_stable != 0; }
boolean adaDelta() { return parameters.rho > 0 && parameters.epsilon > 0; }
public final float[] get_weights(int i) { return weights[i]; }
public final double[] get_biases(int i) { return biases[i]; }
public final float[] get_weights_momenta(int i) { return weights_momenta[i]; }
public final double[] get_biases_momenta(int i) { return biases_momenta[i]; }
public final float[] get_E_dx2(int i) { return E_dx2[i]; }
public final float[] get_E_g2(int i) { return E_g2[i]; }
@API(help = "Model parameters", json = true)
final private DeepLearning parameters;
public final DeepLearning get_params() { return parameters; }
public final DeepLearning job() { return get_params(); }
@API(help = "Mean rate", json = true)
private double[] mean_rate;
@API(help = "RMS rate", json = true)
private double[] rms_rate;
@API(help = "Mean bias", json = true)
private double[] mean_bias;
@API(help = "RMS bias", json = true)
private double[] rms_bias;
@API(help = "Mean weight", json = true)
private double[] mean_weight;
@API(help = "RMS weight", json = true)
public double[] rms_weight;
@API(help = "Unstable", json = true)
private volatile boolean unstable = false;
public boolean unstable() { return unstable; }
public void set_unstable() { unstable = true; computeStats(); }
@API(help = "Processed samples", json = true)
private long processed_global;
public synchronized long get_processed_global() { return processed_global; }
public synchronized void set_processed_global(long p) { processed_global = p; }
public synchronized void add_processed_global(long p) { processed_global += p; }
private long processed_local;
public synchronized long get_processed_local() { return processed_local; }
public synchronized void set_processed_local(long p) { processed_local = p; }
public synchronized void add_processed_local(long p) { processed_local += p; }
public synchronized long get_processed_total() { return processed_global + processed_local; }
// package local helpers
final int[] units; //number of neurons per layer, extracted from parameters and from datainfo
public DeepLearningModelInfo(final DeepLearning params, final DataInfo dinfo) {
data_info = dinfo;
final int num_input = dinfo.fullN();
final int num_output = params.classification ? dinfo._adaptedFrame.lastVec().domain().length : 1;
assert(num_input > 0);
assert(num_output > 0);
parameters = params;
if (has_momenta() && adaDelta()) throw new InvalidArgumentException("Cannot have non-zero momentum and non-zero AdaDelta parameters at the same time.");
final int layers=parameters.hidden.length;
// units (# neurons for each layer)
units = new int[layers+2];
units[0] = num_input;
System.arraycopy(parameters.hidden, 0, units, 1, layers);
units[layers+1] = num_output;
// weights (to connect layers)
weights = new float[layers+1][];
for (int i=0; i<=layers; ++i) weights[i] = new float[units[i]*units[i+1]];
// biases (only for hidden layers and output layer)
biases = new double[layers+1][];
for (int i=0; i<=layers; ++i) biases[i] = new double[units[i+1]];
fillHelpers();
// for diagnostics
mean_rate = new double[units.length];
rms_rate = new double[units.length];
mean_bias = new double[units.length];
rms_bias = new double[units.length];
mean_weight = new double[units.length];
rms_weight = new double[units.length];
}
void fillHelpers() {
if (has_momenta()) {
if (weights_momenta != null) return;
weights_momenta = new float[weights.length][];
for (int i=0; i<weights_momenta.length; ++i) weights_momenta[i] = new float[units[i]*units[i+1]];
biases_momenta = new double[biases.length][];
for (int i=0; i<biases_momenta.length; ++i) biases_momenta[i] = new double[units[i+1]];
}
else {
//AdaGrad
if (E_dx2 != null) return;
E_dx2 = new float[weights.length][];
for (int i=0; i<E_dx2.length; ++i) E_dx2[i] = new float[units[i]*units[i+1]];
E_g2 = new float[weights.length][];
for (int i=0; i<E_g2.length; ++i) E_g2[i] = new float[units[i]*units[i+1]];
}
}
public void delete() {
// ugly: whoever made data_info should also clean this up... but sometimes it was made by Weaver from UKV!
if (data_info()._adaptedFrame.lastVec()._key!=null) UKV.remove(data_info()._adaptedFrame.lastVec()._key);
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (parameters.diagnostics) {
computeStats();
if (!parameters.quiet_mode) {
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(this);
sb.append("Status of Neuron Layers:\n");
sb.append("# Units Type Dropout L1 L2 " + (parameters.adaptive_rate ? " Rate (Mean,RMS) " : " Rate Momentum") + " Weight (Mean, RMS) Bias (Mean,RMS)\n");
final String format = "%7g";
for (int i=0; i<neurons.length; ++i) {
sb.append((i+1) + " " + String.format("%6d", neurons[i].units)
+ " " + String.format("%16s", neurons[i].getClass().getSimpleName()));
if (i == 0) {
sb.append(" " + String.format("%.5g", neurons[i].params.input_dropout_ratio*100) + "%\n");
continue;
}
else if (i < neurons.length-1) {
sb.append( neurons[i] instanceof Neurons.TanhDropout
|| neurons[i] instanceof Neurons.RectifierDropout
|| neurons[i] instanceof Neurons.MaxoutDropout ? " 50% " : " 0% ");
} else {
sb.append(" ");
}
sb.append(
" " + String.format("%5f", neurons[i].params.l1)
+ " " + String.format("%5f", neurons[i].params.l2)
+ " " + (parameters.adaptive_rate ? (" (" + String.format(format, mean_rate[i]) + ", " + String.format(format, rms_rate[i]) + ")" )
: (String.format("%10g", neurons[i].rate(get_processed_total())) + " " + String.format("%5f", neurons[i].momentum(get_processed_total()))))
+ " (" + String.format(format, mean_weight[i])
+ ", " + String.format(format, rms_weight[i]) + ")"
+ " (" + String.format(format, mean_bias[i])
+ ", " + String.format(format, rms_bias[i]) + ")\n");
}
}
}
return sb.toString();
}
// DEBUGGING
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(toString());
for (int i=0; i<weights.length; ++i)
sb.append("\nweights["+i+"][]="+Arrays.toString(weights[i]));
for (int i=0; i<biases.length; ++i)
sb.append("\nbiases["+i+"][]="+Arrays.toString(biases[i]));
if (weights_momenta != null) {
for (int i=0; i<weights_momenta.length; ++i)
sb.append("\nweights_momenta["+i+"][]="+Arrays.toString(weights_momenta[i]));
}
if (biases_momenta != null) {
for (int i=0; i<biases_momenta.length; ++i)
sb.append("\nbiases_momenta["+i+"][]="+Arrays.toString(biases_momenta[i]));
}
sb.append("\nunits[]="+Arrays.toString(units));
sb.append("\nprocessed global: "+get_processed_global());
sb.append("\nprocessed local: "+get_processed_local());
sb.append("\nprocessed total: " + get_processed_total());
sb.append("\n");
return sb.toString();
}
void initializeMembers() {
randomizeWeights();
//TODO: determine good/optimal/best initialization scheme for biases
// hidden layers
for (int i=0; i<parameters.hidden.length; ++i) {
if (parameters.activation == DeepLearning.Activation.Rectifier
|| parameters.activation == DeepLearning.Activation.RectifierWithDropout
|| parameters.activation == DeepLearning.Activation.Maxout
|| parameters.activation == DeepLearning.Activation.MaxoutWithDropout
) {
// Arrays.fill(biases[i], 1.); //old behavior
Arrays.fill(biases[i], i == 0 ? 0.5 : 1.); //new behavior, might be slightly better
}
else if (parameters.activation == DeepLearning.Activation.Tanh || parameters.activation == DeepLearning.Activation.TanhWithDropout) {
Arrays.fill(biases[i], 0.0);
}
}
Arrays.fill(biases[biases.length-1], 0.0); //output layer
}
public void add(DeepLearningModelInfo other) {
Utils.add(weights, other.weights);
Utils.add(biases, other.biases);
if (has_momenta()) {
assert(other.has_momenta());
Utils.add(weights_momenta, other.weights_momenta);
Utils.add(biases_momenta, other.biases_momenta);
}
if (adaDelta()) {
assert(other.adaDelta());
Utils.add(E_dx2, other.E_dx2);
Utils.add(E_g2, other.E_g2);
}
add_processed_local(other.get_processed_local());
}
protected void div(double N) {
for (float[] weight : weights) Utils.div(weight, (float) N);
for (double[] bias : biases) Utils.div(bias, N);
if (has_momenta()) {
for (float[] weight_momenta : weights_momenta) Utils.div(weight_momenta, (float) N);
for (double[] bias_momenta : biases_momenta) Utils.div(bias_momenta, N);
}
if (adaDelta()) {
for (float[] dx2 : E_dx2) Utils.div(dx2, (float) N);
for (float[] g2 : E_g2) Utils.div(g2, (float) N);
}
}
double uniformDist(Random rand, double min, double max) {
return min + rand.nextFloat() * (max - min);
}
void randomizeWeights() {
for (int i=0; i<weights.length; ++i) {
final Random rng = water.util.Utils.getDeterRNG(get_params().seed + 0xBAD5EED + i+1); //to match NeuralNet behavior
for( int j = 0; j < weights[i].length; j++ ) {
if (parameters.initial_weight_distribution == DeepLearning.InitialWeightDistribution.UniformAdaptive) {
final double range = Math.sqrt(6. / (units[i] + units[i+1]));
weights[i][j] = (float)uniformDist(rng, -range, range);
if (i==weights.length-1 && parameters.classification) weights[i][j] *= 4; //Softmax might need an extra factor 4, since it's like a sigmoid
}
else if (parameters.initial_weight_distribution == DeepLearning.InitialWeightDistribution.Uniform) {
weights[i][j] = (float)uniformDist(rng, -parameters.initial_weight_scale, parameters.initial_weight_scale);
}
else if (parameters.initial_weight_distribution == DeepLearning.InitialWeightDistribution.Normal) {
weights[i][j] = (float)(rng.nextGaussian() * parameters.initial_weight_scale);
}
}
}
}
// TODO: Add "subset randomize" function
// int count = Math.min(15, _previous.units);
// double min = -.1f, max = +.1f;
// //double min = -1f, max = +1f;
// for( int o = 0; o < units; o++ ) {
// for( int n = 0; n < count; n++ ) {
// int i = rand.nextInt(_previous.units);
// int w = o * _previous.units + i;
// _w[w] = uniformDist(rand, min, max);
// compute stats on all nodes
public void computeStats() {
double[][] rate = parameters.adaptive_rate ? new double[units.length-1][] : null;
for( int y = 1; y < units.length; y++ ) {
mean_rate[y] = rms_rate[y] = 0;
mean_bias[y] = rms_bias[y] = 0;
mean_weight[y] = rms_weight[y] = 0;
for(int u = 0; u < biases[y-1].length; u++) {
mean_bias[y] += biases[y-1][u];
}
if (rate != null) rate[y-1] = new double[weights[y-1].length];
for(int u = 0; u < weights[y-1].length; u++) {
mean_weight[y] += weights[y-1][u];
if (rate != null) {
final double RMS_dx = Math.sqrt(E_dx2[y-1][u]+parameters.epsilon);
final double RMS_g = Math.sqrt(E_g2[y-1][u]+parameters.epsilon);
rate[y-1][u] = (RMS_dx/RMS_g); //not exactly right, RMS_dx should be from the previous time step -> but close enough for diagnostics.
mean_rate[y] += rate[y-1][u];
}
}
mean_bias[y] /= biases[y-1].length;
mean_weight[y] /= weights[y-1].length;
if (rate != null) mean_rate[y] /= rate[y-1].length;
for(int u = 0; u < biases[y-1].length; u++) {
final double db = biases[y-1][u] - mean_bias[y];
rms_bias[y] += db * db;
}
for(int u = 0; u < weights[y-1].length; u++) {
final double dw = weights[y-1][u] - mean_weight[y];
rms_weight[y] += dw * dw;
if (rate != null) {
final double drate = rate[y-1][u] - mean_rate[y];
rms_rate[y] += drate * drate;
}
}
rms_bias[y] = Math.sqrt(rms_bias[y]/biases[y-1].length);
rms_weight[y] = Math.sqrt(rms_weight[y]/weights[y-1].length);
if (rate != null) rms_rate[y] = Math.sqrt(rms_rate[y]/rate[y-1].length);
unstable |= isNaN(mean_bias[y]) || isNaN(rms_bias[y])
|| isNaN(mean_weight[y]) || isNaN(rms_weight[y]);
// Abort the run if weights or biases are unreasonably large (Note that all input values are normalized upfront)
// This can happen with Rectifier units when L1/L2/max_w2 are all set to 0, especially when using more than 1 hidden layer.
final double thresh = 1e10;
unstable |= mean_bias[y] > thresh || isNaN(mean_bias[y])
|| rms_bias[y] > thresh || isNaN(rms_bias[y])
|| mean_weight[y] > thresh || isNaN(mean_weight[y])
|| rms_weight[y] > thresh || isNaN(rms_weight[y]);
}
}
}
public DeepLearningModel(Key selfKey, Key jobKey, Key dataKey, DataInfo dinfo, DeepLearning params, float[] priorDist) {
super(selfKey, dataKey, dinfo._adaptedFrame, priorDist);
this.jobKey = jobKey;
run_time = 0;
start_time = System.currentTimeMillis();
model_info = new DeepLearningModelInfo(params, dinfo);
errors = new Errors[1];
errors[0] = new Errors();
errors[0].validation = (params.validation != null);
}
transient private long _timeLastScoreStart;
transient private long _timeLastScoreEnd;
transient private long _timeLastPrintStart;
/**
*
* @param train training data from which the model is built (for epoch counting only)
* @param ftrain potentially downsampled training data for scoring
* @param ftest potentially downsampled validation data for scoring
* @param timeStart start time in milliseconds, used to report training speed
* @param job_key key of the owning job
* @return true if model building is ongoing
*/
boolean doScoring(Frame train, Frame ftrain, Frame ftest, long timeStart, Key job_key) {
epoch_counter = (float)model_info().get_processed_total()/train.numRows();
run_time = (System.currentTimeMillis()-start_time);
boolean keep_running = (epoch_counter < model_info().get_params().epochs);
long now = System.currentTimeMillis();
final long sinceLastScore = now -_timeLastScoreStart;
final long sinceLastPrint = now -_timeLastPrintStart;
final long samples = model_info().get_processed_total();
if (sinceLastPrint > model_info().get_params().score_interval*1000) {
_timeLastPrintStart = now;
Log.info("Training time: " + PrettyPrint.msecs(now - start_time, true)
+ ". Processed " + String.format("%,d", samples) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)."
+ " Speed: " + String.format("%.3f", (double)samples/((now - start_time)/1000.)) + " samples/sec.");
}
// this is potentially slow - only do every so often
if( !keep_running ||
(sinceLastScore > model_info().get_params().score_interval*1000 //don't score too often
&&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < model_info().get_params().score_duty_cycle) ) { //duty cycle
final boolean printme = !model_info().get_params().quiet_mode;
if (printme) Log.info("Scoring the model.");
_timeLastScoreStart = now;
// compute errors
Errors err = new Errors();
err.classification = isClassifier();
assert(err.classification == model_info().get_params().classification);
err.training_time_ms = now - timeStart;
err.epoch_counter = epoch_counter;
err.validation = ftest != null;
err.training_samples = model_info().get_processed_total();
err.score_training_samples = ftrain.numRows();
err.train_confusion_matrix = new ConfusionMatrix();
if (err.classification && nclasses()==2) err.trainAUC = new AUC();
model_info().toString();
final Frame trainPredict = score(ftrain, false);
final double trainErr = calcError(ftrain, trainPredict, "training", printme, err.train_confusion_matrix, err.trainAUC);
if (isClassifier()) err.train_err = trainErr;
else err.train_mse = trainErr;
trainPredict.delete();
if (err.validation) {
assert ftest != null;
err.score_validation_samples = ftest.numRows();
err.valid_confusion_matrix = new ConfusionMatrix();
if (err.classification && nclasses()==2) err.validAUC = new AUC();
Job.ValidatedJob.Response2CMAdaptor vadaptor = model_info().job().getValidAdaptor();
Vec tmp = null;
if (isClassifier() && vadaptor.needsAdaptation2CM()) tmp = ftest.remove(ftest.vecs().length-1);
final Frame validPredict = score(ftest, false);
// Adapt output response domain, in case validation domain is different from training domain
// Note: doesn't change predictions, just the *possible* label domain
if (isClassifier() && vadaptor.needsAdaptation2CM()) {
ftest.add("adaptedValidationResponse", tmp);
final Vec CMadapted = vadaptor.adaptModelResponse2CM(validPredict.vecs()[0]);
validPredict.replace(0, CMadapted); //replace label
validPredict.add("to_be_deleted", CMadapted); //keep the Vec around to be deleted later (no leak)
}
final double validErr = calcError(ftest, validPredict, "validation", printme, err.valid_confusion_matrix, err.validAUC);
if (isClassifier()) err.valid_err = validErr;
else err.valid_mse = validErr;
validPredict.delete();
}
// keep output JSON small
if (errors.length > 1) {
if (last_scored().trainAUC != null) last_scored().trainAUC.clear();
if (last_scored().validAUC != null) last_scored().validAUC.clear();
}
// only keep confusion matrices for the last step if there are fewer than specified number of output classes
if (err.train_confusion_matrix.cm != null
&& err.train_confusion_matrix.cm.length >= model_info().get_params().max_confusion_matrix_size) {
err.train_confusion_matrix = null;
err.valid_confusion_matrix = null;
}
// enlarge the error array by one, push latest score back
if (errors == null) {
errors = new Errors[]{err};
} else {
Errors[] err2 = new Errors[errors.length+1];
System.arraycopy(errors, 0, err2, 0, errors.length);
err2[err2.length-1] = err;
errors = err2;
}
_timeLastScoreEnd = System.currentTimeMillis();
// print the freshly scored model to ASCII
for (String s : toString().split("\n")) Log.info(s);
if (printme) Log.info("Scoring time: " + PrettyPrint.msecs(System.currentTimeMillis() - now, true));
}
if (model_info().unstable()) {
Log.err("Canceling job since the model is unstable (exponential growth observed).");
Log.err("Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.");
keep_running = false;
} else if ( (isClassifier() && last_scored().train_err <= model_info().get_params().classification_stop)
|| (!isClassifier() && last_scored().train_mse <= model_info().get_params().regression_stop) ) {
Log.info("Achieved requested predictive accuracy on the training data. Model building completed.");
keep_running = false;
}
update(job_key);
// System.out.println(this);
return keep_running;
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toString());
sb.append(last_scored().toString());
return sb.toString();
}
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toStringAll());
sb.append(last_scored().toString());
return sb.toString();
}
/**
* Predict from raw double values representing
* @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs
* @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs
* @return preds, can contain NaNs
*/
@Override public float[] score0(double[] data, float[] preds) {
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
((Neurons.Input)neurons[0]).setInput(-1, data);
DeepLearningTask.step(-1, neurons, model_info, false, null);
double[] out = neurons[neurons.length - 1]._a;
if (isClassifier()) {
assert(preds.length == out.length+1);
for (int i=0; i<preds.length-1; ++i) {
preds[i+1] = (float)out[i];
if (Float.isNaN(preds[i+1])) throw new RuntimeException("Predicted class probability NaN!");
}
preds[0] = ModelUtils.getPrediction(preds, data);
} else {
assert(preds.length == 1 && out.length == 1);
if (model_info().data_info()._normRespMul != null)
preds[0] = (float)(out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]);
else
preds[0] = (float)out[0];
if (Float.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!");
}
return preds;
}
/**
* Compute the model error for a given test data set
* For multi-class classification, this is the classification error based on assigning labels for the highest predicted per-class probability.
* For binary classification, this is the classification error based on assigning labels using the optimal threshold for maximizing the F1 score.
* For regression, this is the mean squared error (MSE).
* @param ftest Frame containing test data
* @param fpreds Frame containing predicted data (classification: label + per-class probabilities, regression: target)
* @param label Name for the scored data set
* @param printCM Whether to print the confusion matrix to stdout
* @param cm Confusion Matrix object to populate for multi-class classification (also used for regression)
* @param auc AUC object to populate for binary classification
* @return model error, see description above
*/
public double calcError(Frame ftest, Frame fpreds, String label, boolean printCM, ConfusionMatrix cm, AUC auc) {
StringBuilder sb = new StringBuilder();
double error;
// populate AUC
if (auc != null) {
auc.actual = ftest;
auc.vactual = ftest.lastVec();
auc.predict = fpreds;
auc.vpredict = fpreds.vecs()[2]; //binary classifier (label, prob0, prob1 (THIS ONE), adaptedlabel)
auc.threshold_criterion = AUC.ThresholdCriterion.maximum_F1;
auc.serve();
auc.toASCII(sb);
error = auc.err(); //using optimal threshold for F1
}
// populate CM
else {
if (cm == null) cm = new ConfusionMatrix();
cm.actual = ftest;
cm.vactual = ftest.lastVec(); //original vector or adapted response (label) if CM adaptation was done
cm.predict = fpreds;
cm.vpredict = fpreds.vecs()[0]; //ditto
cm.serve();
cm.toASCII(sb);
error = isClassifier() ? new hex.ConfusionMatrix(cm.cm).err() : cm.mse;
}
if (printCM && (auc != null || cm.cm==null /*regression*/ || cm.cm.length <= model_info().get_params().max_confusion_matrix_size)) {
Log.info("Scoring on " + label + " data:");
for (String s : sb.toString().split("\n")) Log.info(s);
}
return error;
}
public boolean generateHTML(String title, StringBuilder sb) {
if (_key == null) {
DocGen.HTML.title(sb, "No model yet");
return true;
}
final String mse_format = "%g";
// final String cross_entropy_format = "%2.6f";
// stats for training and validation
final Errors error = last_scored();
DocGen.HTML.title(sb, title);
model_info.job().toHTML(sb);
Inspect2 is2 = new Inspect2();
sb.append("<div class='alert'>Actions: "
+ (Job.isRunning(jobKey) ? Cancel.link(jobKey, "Stop training") + ", " : "")
+ is2.link("Inspect training data (" + _dataKey + ")", _dataKey) + ", "
+ (model_info().parameters.validation != null ? (is2.link("Inspect validation data (" + model_info().parameters.validation._key + ")", model_info().parameters.validation._key) + ", ") : "")
+ water.api.Predict.link(_key, "Score on dataset") + ", " +
DeepLearning.link(_dataKey, "Compute new model") + "</div>");
DocGen.HTML.paragraph(sb, "Model Key: " + _key);
DocGen.HTML.paragraph(sb, "Job Key: " + jobKey);
DocGen.HTML.paragraph(sb, "Model type: " + (model_info().parameters.classification ? " Classification" : " Regression") + ", predicting: " + responseName());
DocGen.HTML.paragraph(sb, "Number of model parameters (weights/biases): " + String.format("%,d", model_info().size()));
if (model_info.unstable()) {
final String msg = "Job was aborted due to observed numerical instability (exponential growth)."
+ " Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.";
DocGen.HTML.section(sb, "=======================================================================================");
DocGen.HTML.section(sb, msg);
DocGen.HTML.section(sb, "=======================================================================================");
}
DocGen.HTML.title(sb, "Progress");
// update epoch counter every time the website is displayed
epoch_counter = training_rows > 0 ? (float)model_info().get_processed_total()/training_rows : 0;
final double progress = model_info.get_params().progress();
if (model_info.parameters != null && model_info.parameters.diagnostics) {
DocGen.HTML.section(sb, "Status of Neuron Layers");
sb.append("<table class='table table-striped table-bordered table-condensed'>");
sb.append("<tr>");
sb.append("<th>").append("#").append("</th>");
sb.append("<th>").append("Units").append("</th>");
sb.append("<th>").append("Type").append("</th>");
sb.append("<th>").append("Dropout").append("</th>");
sb.append("<th>").append("L1").append("</th>");
sb.append("<th>").append("L2").append("</th>");
if (model_info.get_params().adaptive_rate) {
sb.append("<th>").append("Rate (Mean, RMS)").append("</th>");
} else {
sb.append("<th>").append("Rate").append("</th>");
sb.append("<th>").append("Momentum").append("</th>");
}
sb.append("<th>").append("Weight (Mean, RMS)").append("</th>");
sb.append("<th>").append("Bias (Mean, RMS)").append("</th>");
sb.append("</tr>");
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info()); //link the weights to the neurons, for easy access
for (int i=0; i<neurons.length; ++i) {
sb.append("<tr>");
sb.append("<td>").append("<b>").append(i+1).append("</b>").append("</td>");
sb.append("<td>").append("<b>").append(neurons[i].units).append("</b>").append("</td>");
sb.append("<td>").append(neurons[i].getClass().getSimpleName()).append("</td>");
if (i == 0) {
sb.append("<td>");
sb.append(formatPct(neurons[i].params.input_dropout_ratio));
sb.append("</td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
continue;
}
else if (i < neurons.length-1) {
sb.append("<td>");
sb.append( neurons[i] instanceof Neurons.TanhDropout
|| neurons[i] instanceof Neurons.RectifierDropout
|| neurons[i] instanceof Neurons.MaxoutDropout ? "50%" : "0%");
sb.append("</td>");
} else {
sb.append("<td></td>");
}
final String format = "%g";
sb.append("<td>").append(neurons[i].params.l1).append("</td>");
sb.append("<td>").append(neurons[i].params.l2).append("</td>");
if (model_info.get_params().adaptive_rate) {
sb.append("<td>(").append(String.format(format, model_info.mean_rate[i])).
append(", ").append(String.format(format, model_info.rms_rate[i])).append(")</td>");
} else {
sb.append("<td>").append(String.format("%.5g", neurons[i].rate(error.training_samples))).append("</td>");
sb.append("<td>").append(String.format("%.5f", neurons[i].momentum(error.training_samples))).append("</td>");
}
sb.append("<td>(").append(String.format(format, model_info.mean_weight[i])).
append(", ").append(String.format(format, model_info.rms_weight[i])).append(")</td>");
sb.append("<td>(").append(String.format(format, model_info.mean_bias[i])).
append(", ").append(String.format(format, model_info.rms_bias[i])).append(")</td>");
sb.append("</tr>");
}
sb.append("</table>");
}
if (isClassifier()) {
DocGen.HTML.section(sb, "Classification error on training data: " + formatPct(error.train_err));
// DocGen.HTML.section(sb, "Training cross entropy: " + String.format(cross_entropy_format, error.train_mce));
if(error.validation) {
DocGen.HTML.section(sb, "Classification error on validation data: " + formatPct(error.valid_err));
// DocGen.HTML.section(sb, "Validation mean cross entropy: " + String.format(cross_entropy_format, error.valid_mce));
}
} else {
DocGen.HTML.section(sb, "MSE on training data: " + String.format(mse_format, error.train_mse));
if(error.validation) {
DocGen.HTML.section(sb, "MSE on validation data: " + String.format(mse_format, error.valid_mse));
}
}
DocGen.HTML.paragraph(sb, "Epochs: " + String.format("%.3f", epoch_counter) + " / " + model_info.parameters.epochs);
final boolean isEnded = Job.isEnded(model_info().job().self());
long time_so_far = isEnded ? error.training_time_ms : System.currentTimeMillis() - model_info.parameters.start_time;
if (time_so_far > 0) {
DocGen.HTML.paragraph(sb, "Training speed: " + String.format("%,d", model_info().get_processed_total() * 1000 / time_so_far) + " samples/s");
}
DocGen.HTML.paragraph(sb, "Training time: " + PrettyPrint.msecs(time_so_far, true));
if (progress > 0 && !isEnded)
DocGen.HTML.paragraph(sb, "Estimated time left: " +PrettyPrint.msecs((long)(time_so_far*(1-progress)/progress), true));
long score_train = error.score_training_samples;
long score_valid = error.score_validation_samples;
final boolean fulltrain = score_train==0 || score_train == model_info().data_info()._adaptedFrame.numRows();
final boolean fullvalid = score_valid==0 || score_valid == model_info().get_params().validation.numRows();
final String toolarge = " Not shown here - too large: number of classes (" + model_info.units[model_info.units.length-1]
+ ") is greater than the specified limit of " + model_info().get_params().max_confusion_matrix_size + ".";
boolean smallenough = model_info.units[model_info.units.length-1] <= model_info().get_params().max_confusion_matrix_size;
if (isClassifier()) {
// print AUC
if (error.validAUC != null) {
error.validAUC.toHTML(sb);
}
else if (error.trainAUC != null) {
error.trainAUC.toHTML(sb);
}
else {
if (error.validation) {
String cmTitle = "Confusion matrix reported on validation data" + (fullvalid ? "" : " (" + score_valid + " samples)") + ":";
sb.append("<h5>" + cmTitle);
if (error.valid_confusion_matrix != null && smallenough) {
sb.append("</h5>");
error.valid_confusion_matrix.toHTML(sb);
} else if (smallenough) sb.append(" Not yet computed.</h5>");
else sb.append(" Too large." + "</h5>");
} else {
String cmTitle = "Confusion matrix reported on training data" + (fulltrain ? "" : " (" + score_train + " samples)") + ":";
sb.append("<h5>" + cmTitle);
if (error.train_confusion_matrix != null && smallenough) {
sb.append("</h5>");
error.train_confusion_matrix.toHTML(sb);
} else if (smallenough) sb.append(" Not yet computed.</h5>");
else sb.append(toolarge + "</h5>");
}
}
}
DocGen.HTML.title(sb, "Scoring history");
if (errors.length > 1) {
// training
{
final long pts = fulltrain ? model_info().data_info()._adaptedFrame.numRows() : score_train;
String training = "Number of training data samples for scoring: " + (fulltrain ? "all " : "") + pts;
if (pts < 1000 && model_info().data_info()._adaptedFrame.numRows() >= 1000) training += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)";
if (pts > 100000) training += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)";
DocGen.HTML.paragraph(sb, training);
}
// validation
if (error.validation) {
final long ptsv = fullvalid ? model_info().get_params().validation.numRows() : score_valid;
String validation = "Number of validation data samples for scoring: " + (fullvalid ? "all " : "") + ptsv;
if (ptsv < 1000 && model_info().get_params().validation.numRows() >= 1000) validation += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)";
if (ptsv > 100000) validation += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)";
DocGen.HTML.paragraph(sb, validation);
}
if (isClassifier() && nclasses() != 2 /*binary classifier has its own conflicting D3 object (AUC)*/) {
// Plot training error
float[] err = new float[errors.length];
float[] samples = new float[errors.length];
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i].train_err;
samples[i] = errors[i].training_samples;
}
new D3Plot(samples, err, "training samples", "classification error",
"classification error on training data").generate(sb);
// Plot validation error
if (model_info.parameters.validation != null) {
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i].valid_err;
}
new D3Plot(samples, err, "training samples", "classification error",
"classification error on validation set").generate(sb);
}
}
// regression
else if (!isClassifier()) {
// Plot training MSE
float[] err = new float[errors.length-1];
float[] samples = new float[errors.length-1];
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i+1].train_mse;
samples[i] = errors[i+1].training_samples;
}
new D3Plot(samples, err, "training samples", "MSE",
"regression error on training data").generate(sb);
// Plot validation MSE
if (model_info.parameters.validation != null) {
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i+1].valid_mse;
}
new D3Plot(samples, err, "training samples", "MSE",
"regression error on validation data").generate(sb);
}
}
}
// String training = "Number of training set samples for scoring: " + error.score_training;
if (error.validation) {
// String validation = "Number of validation set samples for scoring: " + error.score_validation;
}
sb.append("<table class='table table-striped table-bordered table-condensed'>");
sb.append("<tr>");
sb.append("<th>Training Time</th>");
sb.append("<th>Training Epochs</th>");
sb.append("<th>Training Samples</th>");
if (isClassifier()) {
// sb.append("<th>Training MCE</th>");
sb.append("<th>Training Error</th>");
if (nclasses()==2) sb.append("<th>Training AUC</th>");
} else {
sb.append("<th>Training MSE</th>");
}
if (error.validation) {
if (isClassifier()) {
// sb.append("<th>Validation MCE</th>");
sb.append("<th>Validation Error</th>");
if (nclasses()==2) sb.append("<th>Validation AUC</th>");
} else {
sb.append("<th>Validation MSE</th>");
}
}
sb.append("</tr>");
for( int i = errors.length - 1; i >= 0; i
final Errors e = errors[i];
sb.append("<tr>");
sb.append("<td>" + PrettyPrint.msecs(e.training_time_ms, true) + "</td>");
sb.append("<td>" + String.format("%g", e.epoch_counter) + "</td>");
sb.append("<td>" + String.format("%,d", e.training_samples) + "</td>");
if (isClassifier()) {
// sb.append("<td>" + String.format(cross_entropy_format, e.train_mce) + "</td>");
sb.append("<td>" + formatPct(e.train_err) + "</td>");
if (nclasses()==2) {
if (e.trainAUC != null) sb.append("<td>" + formatPct(e.trainAUC.AUC()) + "</td>");
else sb.append("<td>" + "N/A" + "</td>");
}
} else {
sb.append("<td>" + String.format(mse_format, e.train_mse) + "</td>");
}
if(e.validation) {
if (isClassifier()) {
// sb.append("<td>" + String.format(cross_entropy_format, e.valid_mce) + "</td>");
sb.append("<td>" + formatPct(e.valid_err) + "</td>");
if (nclasses()==2) {
if (e.validAUC != null) sb.append("<td>" + formatPct(e.validAUC.AUC()) + "</td>");
else sb.append("<td>" + "N/A" + "</td>");
}
} else {
sb.append("<td>" + String.format(mse_format, e.valid_mse) + "</td>");
}
}
sb.append("</tr>");
}
sb.append("</table>");
return true;
}
private static String formatPct(double pct) {
String s = "N/A";
if( !isNaN(pct) )
s = String.format("%5.2f %%", 100 * pct);
return s;
}
public boolean toJavaHtml(StringBuilder sb) { return false; }
@Override public String toJava() { return "Not yet implemented."; }
}
|
package info.danidiaz.xanela.driver;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JRootPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.msgpack.MessagePackable;
import org.msgpack.packer.Packer;
import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
import com.sun.org.apache.xpath.internal.operations.Bool;
public class Xanela {
private ImageBin imageBin;
private List<Window> windowArray = new ArrayList<Window>();
private Map<Window,BufferedImage> windowImageMap = new HashMap<Window,BufferedImage>();
private List<Component> componentArray = new ArrayList<Component>();
boolean dirty = false;
public Xanela(Xanela xanela) {
this.imageBin = xanela==null?new ImageBin():xanela.obtainImageBin();
}
public void buildAndWrite(final int xanelaid, final Packer packer) throws IOException {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
try {
Window warray[] = Window.getOwnerlessWindows();
writeWindowArray(xanelaid, packer, warray);
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
this.imageBin.flush();
}
}
private static int countShowing(Component[] warray) {
int visibleCount = 0;
for (int i=0;i<warray.length;i++) {
if (warray[i].isShowing()) {
visibleCount++;
}
}
return visibleCount;
}
private void writeWindowArray(int xanelaid, Packer packer, Window warray[]) throws IOException {
packer.writeArrayBegin(countShowing(warray));
for (int i=0;i<warray.length;i++) {
Window w = warray[i];
if (w.isShowing()) {
writeWindow(xanelaid, packer,w);
}
}
packer.writeArrayEnd();
}
private void writeWindow(int xanelaid, Packer packer, Window w) throws IOException {
int windowId = windowArray.size();
windowArray.add(w);
BufferedImage image = imageBin.obtainImage(w.getSize());
w.paint(image.getGraphics());
windowImageMap.put(w, image);
packer.write((int)xanelaid);
packer.write((int)windowId);
String title = "";
if (w instanceof JFrame) {
title = ((JFrame)w).getTitle();
} else if (w instanceof JDialog) {
title = ((JDialog)w).getTitle();
}
packer.write(title);
packer.writeArrayBegin(2);
{
packer.write((int)w.getHeight());
packer.write((int)w.getWidth());
}
packer.writeArrayEnd();
writeMenuBar(xanelaid, packer, w);
writePopupLayer(xanelaid,packer,w);
RootPaneContainer rpc = (RootPaneContainer)w;
writeComponent(xanelaid, packer, (JComponent) rpc.getContentPane(),w);
writeWindowArray(xanelaid, packer, w.getOwnedWindows());
}
private void writeMenuBar(int xanelaid, Packer packer, Window w) throws IOException {
JMenuBar menubar = null;
if (w instanceof JFrame) {
menubar = ((JFrame)w).getJMenuBar();
} else if (w instanceof JDialog) {
menubar = ((JDialog)w).getJMenuBar();
}
if (menubar==null) {
packer.writeArrayBegin(0);
packer.writeArrayEnd();
} else {
packer.writeArrayBegin(menubar.getMenuCount());
for (int i=0; i<menubar.getMenuCount();i++) {
writeComponent(xanelaid, packer,menubar.getMenu(i),w);
}
packer.writeArrayEnd();
}
}
private void writePopupLayer(int xanelaid, Packer packer, Window w) throws IOException {
Component[] popupLayerArray = new Component[] {};
if (w instanceof JFrame) {
popupLayerArray = ((JFrame)w).getLayeredPane().getComponentsInLayer(JLayeredPane.POPUP_LAYER);
} else if (w instanceof JDialog) {
popupLayerArray = ((JDialog)w).getLayeredPane().getComponentsInLayer(JLayeredPane.POPUP_LAYER);
}
packer.writeArrayBegin(countShowing(popupLayerArray));
for (int i=0;i<popupLayerArray.length;i++) {
JComponent c = (JComponent) popupLayerArray[i];
if (c.isShowing()) {
writeComponent(xanelaid, packer, c, w);
}
}
packer.writeArrayEnd();
}
private void writeComponent(int xanelaid, Packer packer, JComponent c, Component coordBase) throws IOException {
int componentId = componentArray.size();
componentArray.add(c);
packer.write((int)xanelaid);
packer.write((int)componentId);
packer.writeArrayBegin(2);
{
Point posInWindow = SwingUtilities.convertPoint(c, c.getX(), c.getY(), coordBase);
packer.write((int)posInWindow.getX());
packer.write((int)posInWindow.getY());
}
packer.writeArrayEnd();
packer.writeArrayBegin(2);
{
packer.write((int)c.getHeight());
packer.write((int)c.getWidth());
}
packer.writeArrayEnd();
writePotentiallyNullString(packer,c.getName());
writePotentiallyNullString(packer,c.getToolTipText());
if (c instanceof AbstractButton) {
writePotentiallyNullString(packer,((AbstractButton)c).getText());
} else if (c instanceof JLabel) {
writePotentiallyNullString(packer,((JLabel)c).getText());
} else if (c instanceof JTextComponent) {
writePotentiallyNullString(packer,((JTextComponent)c).getText());
} else {
packer.writeNil();
}
packer.write(c.isEnabled());
writeComponentType(xanelaid, packer, componentId, c, coordBase);
Component children[] = c.getComponents();
packer.writeArrayBegin(countShowing(children));
for (int i=0;i<children.length;i++) {
if (children[i].isShowing()) {
writeComponent(xanelaid, packer, (JComponent)children[i],coordBase);
}
}
packer.writeArrayEnd();
}
private void writeComponentType( int xanelaid, Packer packer,
int componentId,
JComponent c,
Component coordBase
) throws IOException
{
packer.write((int)xanelaid);
if (c instanceof JPanel) {
packer.write((int)1);
} else if (c instanceof JToggleButton || c instanceof JCheckBoxMenuItem || c instanceof JRadioButtonMenuItem) {
packer.write((int)2);
packer.write((int)componentId);
packer.write(((AbstractButton)c).isSelected());
} else if (c instanceof AbstractButton) { // normal button, not toggle button
packer.write((int)3);
packer.write((int)componentId);
} else if (c instanceof JTextField ) {
packer.write((int)4);
JTextField textField = (JTextField) c;
if (textField.isEditable()) {
packer.write((int)componentId);
} else {
packer.writeNil();
}
} else if (c instanceof JLabel) {
packer.write((int)5);
} else if (c instanceof JComboBox) {
packer.write((int)6);
packer.write((int)componentId);
JComboBox comboBox = (JComboBox)c;
ListCellRenderer renderer = comboBox.getRenderer();
JList dummyJList = new JList();
if (comboBox.getSelectedIndex()==-1) {
packer.writeNil();
} else {
JComponent cell = (JComponent)renderer.getListCellRendererComponent(dummyJList,
comboBox.getModel().getElementAt(comboBox.getSelectedIndex()),
comboBox.getSelectedIndex(),
false,
false
);
writeComponent(xanelaid, packer, cell, coordBase);
}
} else if (c instanceof JList) {
packer.write((int)7);
JList list = (JList) c;
ListCellRenderer renderer = list.getCellRenderer();
packer.writeArrayBegin((int)list.getModel().getSize());
for (int rowid=0; rowid<list.getModel().getSize(); rowid++) {
writeCell( xanelaid,
packer,
componentId,
rowid, 0,
(JComponent)renderer.getListCellRendererComponent(list,
list.getModel().getElementAt(rowid),
rowid,
false,
false
),
coordBase );
}
packer.writeArrayEnd();
} else if (c instanceof JTable) {
packer.write((int)8);
JTable table = (JTable) c;
TableModel model = table.getModel();
int rowcount = model.getRowCount();
int columncount = model.getColumnCount();
packer.writeArrayBegin(rowcount);
for (int i=0;i<rowcount;i++) {
packer.writeArrayBegin(columncount);
for (int j=0;j<columncount;j++) {
TableCellRenderer renderer = table.getCellRenderer(i, j);
writeCell(
xanelaid,
packer,
componentId,
i, j,
(JComponent)renderer.getTableCellRendererComponent(table,
model.getValueAt(i, j),
false,
false,
i,
j
),
coordBase );
}
packer.writeArrayEnd();
}
packer.writeArrayEnd();
} else if (c instanceof JTree) {
packer.write((int)9);
JTree tree = (JTree) c;
TreeModel model = tree.getModel();
TreeCellRenderer renderer = tree.getCellRenderer();
packer.writeArrayBegin(tree.isRootVisible()?1:model.getChildCount(model.getRoot()));
int basepathcount = tree.isRootVisible()?1:2;
int expectedpathcount = basepathcount;
for (int rowid=0;rowid<tree.getRowCount();rowid++) {
TreePath path = tree.getPathForRow(rowid);
if (path.getPathCount()<expectedpathcount) {
for (int i=0; i < expectedpathcount - path.getPathCount();i++) {
packer.writeArrayEnd();
}
expectedpathcount = path.getPathCount();
}
writeCell(
xanelaid,
packer,
componentId,
rowid, 0,
(JComponent)renderer.getTreeCellRendererComponent(
tree,
path.getLastPathComponent(),
tree.isRowSelected(rowid),
tree.isExpanded(rowid),
model.isLeaf(path.getLastPathComponent()),
rowid,
true
),
coordBase );
if (tree.isExpanded(rowid)) {
packer.writeArrayBegin(model.getChildCount(path.getLastPathComponent()));
expectedpathcount++;
} else {
packer.writeArrayBegin(0);
packer.writeArrayEnd();
}
}
for (int i=0; i < expectedpathcount - basepathcount;i++) {
packer.writeArrayEnd();
}
packer.writeArrayEnd();
} else if (c instanceof JPopupMenu) {
packer.write((int)50);
} else if (c instanceof JTabbedPane) {
packer.write((int)70);
JTabbedPane tpane = (JTabbedPane)c;
packer.writeArrayBegin(tpane.getTabCount());
for (int i=0; i<tpane.getTabCount();i++) {
packer.write((int)xanelaid);
packer.write((int)componentId);
packer.write((int)i);
packer.write(tpane.getTitleAt(i));
writePotentiallyNullString(packer,tpane.getToolTipTextAt(i));
packer.write(i==tpane.getSelectedIndex());
}
packer.writeArrayEnd();
} else {
packer.write((int)77);
packer.write(c.getClass().getName());
}
}
private void writeCell(int xanelaid,
Packer packer,
int componentid,
int rowid,
int colid,
JComponent rendererc,
Component coordBase) throws IOException
{
packer.write((int)xanelaid);
packer.write((int)componentid);
packer.write((int)rowid);
packer.write((int)colid);
writeComponent(xanelaid, packer, rendererc, coordBase);
}
private static void writePotentiallyNullString(Packer packer, String s) throws IOException {
if (s==null) {
packer.writeNil();
} else {
packer.write(s);
}
}
public void toggle(final int buttonId, final boolean targetState) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final AbstractButton button = (AbstractButton)componentArray.get(buttonId);
if (button.isSelected() != targetState) {
click(buttonId);
}
}
});
}
public void click(int buttonId) {
final AbstractButton button = (AbstractButton)componentArray.get(buttonId);
Point point = new Point(button.getWidth()/2,button.getHeight()/2);
postMouseEvent(button, MouseEvent.MOUSE_ENTERED, 0, point, 0, false);
pressedReleasedClicked1(button, new Rectangle(0, 0, button.getWidth(), button.getHeight()), 1);
}
public void clickCombo(int buttonId) {
final JComboBox button = (JComboBox)componentArray.get(buttonId);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
button.showPopup();
}
});
}
public void setTextField(int componentid, final String text) {
final JTextField textField = (JTextField)componentArray.get(componentid);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
textField.setText(text);
}
});
}
public void clickCell(final int componentid, final int rowid, final int columnid) {
final Component component = componentArray.get(componentid);
Rectangle bounds = new Rectangle(0,0,0,0);
if (component instanceof JList) {
JList list = (JList) component;
bounds = list.getCellBounds(rowid, rowid);
list.ensureIndexIsVisible(rowid);
} else if (component instanceof JTable) {
JTable table = (JTable) component;
bounds = table.getCellRect(rowid, columnid, false);
table.scrollRectToVisible(bounds);
} else if (component instanceof JTree) {
JTree tree = (JTree) component;
bounds = tree.getRowBounds(rowid);
tree.scrollRowToVisible(rowid);
} else {
throw new RuntimeException("can't handle component");
}
pressedReleasedClicked1(component, bounds, 1);
}
public void doubleClickCell(final int componentid, final int rowid, final int columnid) {
final Component component = componentArray.get(componentid);
Rectangle bounds = new Rectangle(0,0,0,0);
if (component instanceof JList) {
JList list = (JList) component;
bounds = list.getCellBounds(rowid, rowid);
list.ensureIndexIsVisible(rowid);
} else if (component instanceof JTable) {
JTable table = (JTable) component;
bounds = table.getCellRect(rowid, columnid, false);
table.scrollRectToVisible(bounds);
} else if (component instanceof JTree) {
JTree tree = (JTree) component;
bounds = tree.getRowBounds(rowid);
tree.scrollRowToVisible(rowid);
} else {
throw new RuntimeException("can't handle component");
}
pressedReleasedClicked1(component, bounds, 1);
pressedReleasedClicked1(component, bounds, 2);
}
public void selectTab(final int componentid, final int tabid) {
final JTabbedPane tpane = (JTabbedPane) componentArray.get(componentid);
tpane.setSelectedIndex(tabid);
}
public void rightClick(final int componentid) {
final JComponent button = (JComponent)componentArray.get(componentid);
Point point = new Point(button.getWidth()/2,button.getHeight()/2);
postMouseEvent(button, MouseEvent.MOUSE_ENTERED, 0, point, 0, false);
postMouseEvent(button, MouseEvent.MOUSE_PRESSED, MouseEvent.BUTTON3_MASK, point, 1, false);
postMouseEvent(button, MouseEvent.MOUSE_RELEASED, MouseEvent.BUTTON3_MASK, point, 1, false);
postMouseEvent(button, MouseEvent.MOUSE_CLICKED, MouseEvent.BUTTON3_MASK, point, 1, true);
}
public BufferedImage getWindowImage(final int windowId) {
Window window = windowArray.get(windowId);
return windowImageMap.get(window);
}
public void closeWindow(final int windowId) {
Window window = windowArray.get(windowId);
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new WindowEvent(window, WindowEvent.WINDOW_CLOSING)
);
}
public void escape(final int windowid) {
Window window = windowArray.get(windowid);
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new KeyEvent( window,
KeyEvent.KEY_PRESSED,
System.currentTimeMillis(),
0,
KeyEvent.VK_ESCAPE,
(char)KeyEvent.VK_ESCAPE
));
}
private void setDirty() {
this.dirty = true;
}
private ImageBin obtainImageBin() {
setDirty();
return new ImageBin(windowImageMap.values());
}
private static void postMouseEvent(Component component,
int type,
int mask,
Point point,
int clickCount,
boolean popupTrigger)
{
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new MouseEvent( component,
type, // event type
0,
mask, // modifiers
point.x,
point.y,
clickCount,
popupTrigger
));
}
private static void pressedReleasedClicked1(Component component, Rectangle bounds, int clickCount) {
Point point = new Point(bounds.x + bounds.width/2,bounds.y + bounds.height/2);
postMouseEvent(component, MouseEvent.MOUSE_PRESSED, MouseEvent.BUTTON1_MASK, point, clickCount, false);
postMouseEvent(component, MouseEvent.MOUSE_RELEASED, MouseEvent.BUTTON1_MASK, point, clickCount, false);
postMouseEvent(component, MouseEvent.MOUSE_CLICKED, MouseEvent.BUTTON1_MASK, point, clickCount, false);
}
}
|
package info.jayharris.klondike;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.googlecode.blacken.colors.ColorNames;
import com.googlecode.blacken.colors.ColorPalette;
import com.googlecode.blacken.swing.SwingTerminal;
import com.googlecode.blacken.terminal.BlackenKeys;
import com.googlecode.blacken.terminal.CursesLikeAPI;
import com.googlecode.blacken.terminal.TerminalInterface;
import info.jayharris.cardgames.Deck;
import org.apache.commons.collections4.iterators.LoopingListIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class TerminalUI implements KlondikeUI {
private Klondike klondike;
private boolean quit;
private ColorPalette palette;
private CursesLikeAPI term = null;
private TerminalUIComponent<?> pointingTo, movingFrom = null;
private List<TerminalUIComponent<?>> components;
private LoopingListIterator<TerminalUIComponent<?>> componentOrder;
private boolean lastDirectionRight = true; // direction of last move --
// if componentOrder.next() => X, then an immediate call to
// componentOrder.previous() will also => X.
public final int START_ROW = 0,
LEFT_COL = 5,
SPACE_BETWEEN = 5,
TABLEAU_ROW = 2,
WASTE_CARDS_SHOWN = 6,
WASTE_START_COL = LEFT_COL + "[24 cards]".length() + SPACE_BETWEEN,
WASTE_MAX_WIDTH = "... XX XX XX XX XX XX".length(),
FOUNDATION_START_COL = WASTE_START_COL + WASTE_MAX_WIDTH + SPACE_BETWEEN;
final Logger logger = LoggerFactory.getLogger(TerminalUI.class);
public TerminalUI(Klondike klondike) {
this.klondike = klondike;
}
protected boolean loop() {
int key = BlackenKeys.NO_KEY;
if (palette.containsKey("White")) {
term.setCurBackground("White");
}
if (palette.containsKey("Black")) {
term.setCurForeground("Black");
}
term.clear();
while (!this.quit) {
for (TerminalUIComponent<?> component : components) {
component.writeToTerminal();
}
pointingTo.drawPointer(false);
key = term.getch();
// getch automatically does a refresh
onKeyPress(key);
}
term.refresh();
return this.quit;
}
public void init(TerminalInterface term, ColorPalette palette) {
if (term == null) {
this.term = new CursesLikeAPI(new SwingTerminal());
this.term.init("Klondike", 25, 80);
} else {
this.term = new CursesLikeAPI(term);
}
if (palette == null) {
palette = new ColorPalette();
palette.addAll(ColorNames.XTERM_256_COLORS, false);
palette.putMapping(ColorNames.SVG_COLORS);
}
this.palette = palette;
this.term.setPalette(palette);
// set up all of the deck, waste, foundation, tableau visual components
components = new ArrayList<TerminalUIComponent<?>>() {{
int col;
this.add(new TerminalUIComponent<Deck>(klondike.getDeck(), START_ROW, LEFT_COL) {
@Override
public void writeToTerminal() {
super.writeToTerminal("[" +
Strings.padStart(Integer.toString(klondike.getDeck().size()), 2, ' ') + " cards]");
}
@Override
public void doAction() {
klondike.deal();
}
});
this.add(new TerminalUIComponent<Klondike.Waste>(klondike.getWaste(), START_ROW, WASTE_START_COL) {
@Override
public void doAction() {
// pick up the next card in the waste
if (movingFrom == null && !payload.isEmpty()) {
movingFrom = this;
}
// return the card to whence it came
else {
movingFrom = null;
}
}
@Override
public void writeToTerminal() {
int sz = payload.size();
int index = Math.max(0, sz - WASTE_CARDS_SHOWN), strlen = 0;
if (sz > WASTE_CARDS_SHOWN) {
writeToTerminal("... ");
strlen += "... ".length();
}
while (index < sz) {
if (index == sz - 1) {
if (movingFrom == this) {
setCurBackground("Yellow");
}
writeToTerminal(0, strlen, payload.get(index).toString());
strlen += 2;
}
else {
writeToTerminal(0, strlen, payload.get(index).toString() + " ");
strlen += 3;
}
setCurBackground("White");
++index;
}
while (strlen < WASTE_MAX_WIDTH) {
writeToTerminal(0, strlen, " ");
++strlen;
}
}
});
col = LEFT_COL;
for (int i = 0; i < 7; ++i) {
this.add(new TableauUIComponent(klondike.getTableau(i), col));
col += "XX".length() + SPACE_BETWEEN;
}
col = FOUNDATION_START_COL;
this.add(new TerminalUIComponent<Collection<Klondike.Foundation>>(
klondike.getFoundations(), START_ROW, col) {
Joiner joiner = Joiner.on(Strings.repeat(" ", SPACE_BETWEEN));
@Override
public void writeToTerminal() {
writeToTerminal(joiner.join(payload));
}
@Override
public void doAction() {
boolean legal = false;
if (movingFrom != null) {
if (movingFrom.getClass() == TableauUIComponent.class) {
legal = klondike.moveFromTableauToFoundation((Klondike.Tableau) movingFrom.payload);
}
else {
legal = klondike.moveFromWasteToFoundation();
}
}
if (legal) {
movingFrom.writeToTerminal();
this.writeToTerminal();
movingFrom = null;
}
}
});
}};
componentOrder = new LoopingListIterator(components);
pointingTo = componentOrder.next();
start();
}
private void onKeyPress(int codepoint) {
switch (codepoint) {
case 'z':
case 'Z':
pointingTo.doAction();
break;
case 'a':
case 'A':
movePointerAndRedraw(true);
break;
case 'd':
case 'D':
movePointerAndRedraw(false);
break;
default:
break;
}
pointingTo.receiveKeyPress(codepoint);
}
public void update(Observable observable, Object object) {
}
private void setCurBackground(String c) {
term.setCurBackground(c);
}
private void movePointerAndRedraw(boolean left) {
pointingTo.drawPointer(true);
if (left) {
movePointerLeft();
}
else {
movePointerRight();
}
pointingTo.receiveFocus();
pointingTo.drawPointer(false);
}
private void movePointerRight() {
pointingTo = componentOrder.next();
if (!lastDirectionRight) {
pointingTo = componentOrder.next();
lastDirectionRight = true;
}
}
private void movePointerLeft() {
pointingTo = componentOrder.previous();
if (lastDirectionRight) {
pointingTo = componentOrder.previous();
lastDirectionRight = false;
}
}
private void start() {
klondike.init();
}
public void quit() {
this.quit = true;
term.quit();
}
public abstract class TerminalUIComponent<T> {
T payload;
int startRow, startColumn;
public TerminalUIComponent(T payload, int startRow, int startColumn) {
this.payload = payload;
this.startRow = startRow;
this.startColumn = startColumn;
}
public abstract void doAction();
public void receiveFocus() {}
public void receiveKeyPress(int codepoint) {}
public void writeToTerminal() {
this.writeToTerminal(payload.toString());
}
public void writeToTerminal(String str) {
term.mvputs(startRow, startColumn, str);
}
public void writeToTerminal(int rowOffset, int columnOffset, String str) {
term.mvputs(startRow + rowOffset, startColumn + columnOffset, str);
}
/**
* Draw or undraw the pointer indicating the current element.
*
* @param remove if {@code true} then remove the pointer, otherwise draw it
*/
public void drawPointer(boolean remove) {
term.mvputs(startRow, startColumn - 3, remove ? " " : "-> ");
}
}
public class TableauUIComponent extends TerminalUIComponent<Klondike.Tableau> {
int pointerIndex;
int lengthToClean;
static final String blank = " ";
public TableauUIComponent(Klondike.Tableau payload, int column) {
super(payload, TABLEAU_ROW, column);
pointerIndex = payload.size() - 1;
lengthToClean = payload.size();
}
public void writeToTerminal() {
for (int i = 0; i < Math.max(payload.size(), lengthToClean); ++i) {
if (movingFrom == this && pointerIndex == i) {
setCurBackground("Yellow");
}
if (i == payload.size()) {
setCurBackground("White");
}
term.mvputs(startRow + i, startColumn, i < payload.size() ? payload.get(i).toString() : " ");
}
setCurBackground("White");
lengthToClean = payload.size();
}
public void doAction() {
boolean legal = false;
if (movingFrom == null && !payload.isEmpty()) {
movingFrom = this;
}
else if (movingFrom.getClass() == TableauUIComponent.class) {
TableauUIComponent _movingFrom = (TableauUIComponent) movingFrom;
int numCards = _movingFrom.payload.size() - _movingFrom.pointerIndex;
legal = klondike.moveFromTableauToTableau(_movingFrom.payload, this.payload, numCards);
}
else {
legal = klondike.moveFromWasteToTableau(this.payload);
}
if (legal) {
movingFrom.writeToTerminal();
writeToTerminal();
drawPointer(true);
this.pointerIndex = payload.size() - 1;
drawPointer(false);
movingFrom = null;
}
}
public void receiveFocus() {
if (movingFrom != this) {
pointerIndex = payload.size() - 1;
}
}
public void receiveKeyPress(int codepoint) {
switch (codepoint) {
case 'w':
case 'W':
movePointerUp();
break;
case 's':
case 'S':
movePointerDown();
break;
default:
break;
}
}
public void movePointerUp() {
if (pointerIndex > payload.size() - payload.countFaceup()) {
drawPointer(true);
--pointerIndex;
drawPointer(false);
}
}
public void movePointerDown() {
if (pointerIndex < payload.size() - 1) {
drawPointer(true);
++pointerIndex;
drawPointer(false);
}
}
public void drawPointer(boolean remove) {
term.mvputs(startRow + pointerIndex, startColumn - 3, remove ? " " : "-> ");
}
}
public static void main(String[] args) {
TerminalUI ui = new TerminalUI(new Klondike());
ui.init(null, null);
ui.loop();
ui.quit();
}
}
|
package com.eegeo.compass;
import com.eegeo.entrypointinfrastructure.MainActivity;
import com.eegeo.helpers.IRuntimePermissionResultHandler;
import com.eegeo.mobileexampleapp.R;
import com.eegeo.runtimepermissions.RuntimePermissionDispatcher;
import com.wrld.widgets.navigation.widget.WrldNavWidget;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class CompassView implements View.OnClickListener, IRuntimePermissionResultHandler {
private MainActivity m_activity = null;
private long m_nativeCallerPointer;
private View m_view = null;
private View m_compassPoint = null;
private ImageView m_compassInner = null;
private View m_compassDefault = null;
private View m_compassLocked = null;
private View m_compassUnlocked = null;
private boolean m_unauthorizedGpsAlertShown = false;
private float m_defaultYPosActive;
private float m_yPosActive;
private float m_yPosInactive;
private float m_screenHeight;
private final long m_stateChangeAnimationTimeMilliseconds = 200;
private final long RotationHighlightAnimationMilliseconds = 200;
private final long NeedleLockRotationAnimationMilliseconds = 200;
private final float CompassOuterShapeInactiveAlpha = 0.5f;
private final float CompassOuterShapeActiveAlpha = 1.0f;
private int m_navWidgetModeOffset = 0;
private enum CompassState {
Default(0), Navigation(1);
private final int state;
CompassState(int state){
this.state = state;
}
public final int getState(){
return this.state;
}
};
public CompassView(MainActivity activity, long nativeCallerPointer)
{
m_activity = activity;
m_nativeCallerPointer = nativeCallerPointer;
createView();
}
public void destroy()
{
final RelativeLayout uiRoot = (RelativeLayout) m_activity.findViewById(R.id.ui_container);
uiRoot.removeView(m_view);
m_view = null;
m_activity.getRuntimePermissionDispatcher().removeIRuntimePermissionResultHandler(this);
}
private void createView()
{
final RelativeLayout uiRoot = (RelativeLayout) m_activity.findViewById(R.id.ui_container);
m_view = m_activity.getLayoutInflater().inflate(R.layout.compass_layout, uiRoot, false);
m_view.setOnClickListener(this);
m_screenHeight = uiRoot.getMeasuredHeight();
m_compassPoint = m_view.findViewById(R.id.compass_arrow_shape);
m_compassInner = (ImageView) m_view.findViewById(R.id.compass_inner_shape);
m_compassInner.setVisibility(View.GONE);
m_compassDefault = m_view.findViewById(R.id.compass_outer_shape);
m_compassLocked = m_view.findViewById(R.id.compass_new_locked);
m_compassUnlocked = m_view.findViewById(R.id.compass_new_unlocked);
m_activity.getRuntimePermissionDispatcher().addRuntimePermissionResultHandler(this);
m_view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
final float screenWidth = uiRoot.getWidth();
final float screenHeight = uiRoot.getHeight();
final float viewWidth = m_view.getWidth();
final float viewHeight = m_view.getHeight();
m_defaultYPosActive = (screenHeight - viewWidth) - m_activity.dipAsPx(8.f);
m_yPosActive = m_defaultYPosActive;
m_yPosInactive = screenHeight + viewHeight;
m_view.setX((screenWidth * 0.5f) - (viewWidth * 0.5f));
m_view.setY(m_yPosInactive);
m_view.removeOnLayoutChangeListener(this);
}
});
m_compassPoint.setAlpha(CompassOuterShapeInactiveAlpha);
uiRoot.addView(m_view);
showGpsDisabledView();
}
public void updateHeading(float headingAngleRadians)
{
final float rotationDegrees = (float) -Math.toDegrees(headingAngleRadians);
m_compassPoint.setRotation(rotationDegrees);
m_compassLocked.setRotation(rotationDegrees);
}
public void showGpsDisabledView()
{
m_compassInner.setVisibility(View.GONE);
m_compassDefault.setVisibility(View.VISIBLE);
m_compassLocked.setVisibility(View.INVISIBLE);
m_compassUnlocked.setVisibility(View.INVISIBLE);
}
public void showGpsFollowView()
{
m_compassLocked.setRotation(m_compassPoint.getRotation());
m_compassInner.setVisibility(View.VISIBLE);
m_compassDefault.setVisibility(View.INVISIBLE);
m_compassLocked.setVisibility(View.VISIBLE);
m_compassUnlocked.setVisibility(View.INVISIBLE);
}
public void showGpsCompassModeView()
{
final float NeedleLockeRotationDegrees = 0.0f;
m_compassUnlocked.setRotation(m_compassLocked.getRotation());
m_compassInner.setVisibility(View.VISIBLE);
m_compassLocked.setVisibility(View.INVISIBLE);
m_compassUnlocked.setVisibility(View.VISIBLE);
m_compassDefault.setVisibility(View.INVISIBLE);
m_compassUnlocked.animate()
.rotation(NeedleLockeRotationDegrees)
.setDuration(NeedleLockRotationAnimationMilliseconds);
}
public void notifyGpsUnauthorized()
{
if (m_unauthorizedGpsAlertShown == false) {
m_unauthorizedGpsAlertShown = true;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(m_activity);
alertDialogBuilder.setTitle("Location Services disabled")
.setMessage("GPS Compass inaccessible: Location Services are not enabled for this application. You can change this in your device settings.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_unauthorizedGpsAlertShown = false;
dialog.dismiss();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
@Override
public void onClick(View view)
{
if (m_activity.getRuntimePermissionDispatcher().hasLocationPermissions()) {
CompassViewJniMethods.HandleClick(m_nativeCallerPointer);
}
}
public void animateToActive()
{
animateViewToY((int) m_yPosActive);
}
public void animateToInactive()
{
animateViewToY((int) m_yPosInactive);
}
protected void animateViewToY(final int yAsPx)
{
m_view.animate()
.y(yAsPx)
.setDuration(m_stateChangeAnimationTimeMilliseconds);
}
public void animateToIntermediateOnScreenState(final float onScreenState)
{
int viewYPx = (int) m_view.getY();
int newYPx = (int) (m_yPosInactive + (int) (((m_yPosActive - m_yPosInactive) * onScreenState) + 0.5f));
if (viewYPx != newYPx)
{
m_view.setY(newYPx);
}
}
public void setState(final int state)
{
CompassState compassState = rawStateToCompassState(state);
int offset = (compassState == CompassState.Default) ? 0 : m_navWidgetModeOffset;
m_yPosActive = m_defaultYPosActive - offset;
animateToActive();
}
private CompassState rawStateToCompassState(final int state)
{
if(CompassState.Navigation.getState() == state) {
return CompassState.Navigation;
}
if(CompassState.Default.getState() == state) {
return CompassState.Default;
}
throw new ClassCastException(state + " is not a valid CompassState");
}
public void setNavigationModeOffset(final int offset)
{
if(offset < m_screenHeight * 0.25f) {
m_navWidgetModeOffset = offset;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode != RuntimePermissionDispatcher.GPS_PERMISSION_REQUEST_CODE)
return;
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
CompassViewJniMethods.HandleClick(m_nativeCallerPointer);
}
else
{
// properly, so we will show the dialog with agree or cancel dialog
showPermissionRequiredDialog(m_activity);
}
return;
}
public void setRotationHighlight(boolean shouldShowRotationHighlight)
{
m_compassPoint.animate()
.alpha(shouldShowRotationHighlight ? CompassOuterShapeActiveAlpha : CompassOuterShapeInactiveAlpha)
.setDuration(RotationHighlightAnimationMilliseconds);
}
private void showPermissionRequiredDialog(final Activity context)
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
if(ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.ACCESS_FINE_LOCATION))
{
m_activity.getRuntimePermissionDispatcher().hasLocationPermissions();
}
else
{
m_activity.getRuntimePermissionDispatcher().startAppSettings(context);
}
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(context.getResources().getString(R.string.required_location_permission_text))
.setPositiveButton(context.getResources().getString(R.string.ok_text), dialogClickListener)
.setNegativeButton(context.getResources().getString(R.string.cancel_text), dialogClickListener).show();
}
}
|
package io.mikekennedy.camel;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.client.HttpClient;
public class SlackEndpoint extends DefaultEndpoint {
private static final transient Logger LOG = LoggerFactory.getLogger(SlackEndpoint.class);
private String webhookUrl;
private String username;
private String channel;
private String iconUrl;
private String iconEmoji;
/**
* Constructor for SlackEndpoint
*
* @param uri the full component url
* @param channelName the channel or username the message is directed at
* @param component the component that was created
*/
public SlackEndpoint(String uri, String channelName, SlackComponent component) {
super(uri, component);
this.webhookUrl = component.getWebhookUrl();
this.channel = channelName;
}
/**
* Creates a SlackProducer
*
* @return SlackProducer
* @throws Exception
*/
@Override
public Producer createProducer() throws Exception {
SlackProducer producer = new SlackProducer(this);
return producer;
}
/**
* Unsupported operation
*
* @param processor
* @return
* @throws java.lang.UnsupportedOperationException
*/
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("You cannot consume slack messages from this endpoint: " + getEndpointUri());
}
@Override
public boolean isSingleton() {
return true;
}
public String getWebhookUrl() {
return webhookUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getChannel() {
return channel;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getIconEmoji() {
return iconEmoji;
}
public void setIconEmoji(String iconEmoji) {
this.iconEmoji = iconEmoji;
}
}
|
package com.react;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import android.os.Bundle;
import android.widget.Toast;
import android.app.LoaderManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ContentResolver;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SmsModule extends ReactContextBaseJavaModule /*implements LoaderManager.LoaderCallbacks<Cursor>*/ {
// private LoaderManager mManager;
private Cursor smsCursor;
private Map<Long, String> smsList;
private Map<Long, Object> smsListBody;
Activity mActivity = null;
private static Context context;
private ReactContext mReactContext;
private Callback cb_autoSend_succ = null;
private Callback cb_autoSend_err = null;
public SmsModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
smsList = new HashMap<Long, String>();
context = reactContext.getApplicationContext();
}
@Override
public String getName() {
return "Sms";
}
@ReactMethod
public void list(String filter, final Callback errorCallback, final Callback successCallback) {
try {
JSONObject filterJ = new JSONObject(filter);
String uri_filter = filterJ.has("box") ? filterJ.optString("box") : "inbox";
int fread = filterJ.has("read") ? filterJ.optInt("read") : -1;
int fid = filterJ.has("_id") ? filterJ.optInt("_id") : -1;
String faddress = filterJ.optString("address");
String fcontent = filterJ.optString("body");
int indexFrom = filterJ.has("indexFrom") ? filterJ.optInt("indexFrom") : 0;
int maxCount = filterJ.has("maxCount") ? filterJ.optInt("maxCount") : -1;
Cursor cursor = context.getContentResolver().query(Uri.parse("content://sms/" + uri_filter), null, "", null,
null);
int c = 0;
JSONArray jsons = new JSONArray();
while (cursor.moveToNext()) {
boolean matchFilter = false;
if (fid > -1)
matchFilter = fid == cursor.getInt(cursor.getColumnIndex("_id"));
else if (fread > -1)
matchFilter = fread == cursor.getInt(cursor.getColumnIndex("read"));
else if (faddress.length() > 0)
matchFilter = faddress.equals(cursor.getString(cursor.getColumnIndex("address")).trim());
else if (fcontent.length() > 0)
matchFilter = fcontent.equals(cursor.getString(cursor.getColumnIndex("body")).trim());
else {
matchFilter = true;
}
if (matchFilter) {
if (c >= indexFrom) {
if (maxCount > 0 && c >= indexFrom + maxCount)
break;
c++;
// Long dateTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("date")));
// String message = cursor.getString(cursor.getColumnIndex("body"));
JSONObject json;
json = getJsonFromCursor(cursor);
jsons.put(json);
}
}
}
cursor.close();
try {
successCallback.invoke(c, jsons.toString());
} catch (Exception e) {
errorCallback.invoke(e.getMessage());
}
} catch (JSONException e) {
errorCallback.invoke(e.getMessage());
return;
}
}
private JSONObject getJsonFromCursor(Cursor cur) {
JSONObject json = new JSONObject();
int nCol = cur.getColumnCount();
String[] keys = cur.getColumnNames();
try {
for (int j = 0; j < nCol; j++)
switch (cur.getType(j)) {
case 0:
json.put(keys[j], null);
break;
case 1:
json.put(keys[j], cur.getLong(j));
break;
case 2:
json.put(keys[j], cur.getFloat(j));
break;
case 3:
json.put(keys[j], cur.getString(j));
break;
case 4:
json.put(keys[j], cur.getBlob(j));
}
} catch (Exception e) {
return null;
}
return json;
}
@ReactMethod
public void send(String addresses, String text, final Callback errorCallback, final Callback successCallback) {
mActivity = getCurrentActivity();
try {
JSONObject jsonObject = new JSONObject(addresses);
JSONArray addressList = jsonObject.getJSONArray("addressList");
int n;
if ((n = addressList.length()) > 0) {
PendingIntent sentIntent = PendingIntent.getBroadcast(mActivity, 0, new Intent("SENDING_SMS"), 0);
SmsManager sms = SmsManager.getDefault();
for (int i = 0; i < n; i++) {
String address;
if ((address = addressList.optString(i)).length() > 0)
sms.sendTextMessage(address, null, text, sentIntent, null);
}
} else {
PendingIntent sentIntent = PendingIntent.getActivity(mActivity, 0, new Intent("android.intent.action.VIEW"), 0);
Intent intent = new Intent("android.intent.action.VIEW");
intent.putExtra("sms_body", text);
intent.setData(Uri.parse("sms:"));
try {
sentIntent.send(mActivity.getApplicationContext(), 0, intent);
successCallback.invoke("OK");
} catch (PendingIntent.CanceledException e) {
errorCallback.invoke(e.getMessage());
return;
}
}
return;
} catch (JSONException e) {
errorCallback.invoke(e.getMessage());
return;
}
}
@ReactMethod
public void delete(Integer id, final Callback errorCallback, final Callback successCallback) {
try {
int res = context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
if (res > 0) {
successCallback.invoke("OK");
} else {
errorCallback.invoke("SMS not found");
}
return;
} catch (Exception e) {
errorCallback.invoke(e.getMessage());
return;
}
}
private void sendEvent(ReactContext reactContext, String eventName, String params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
private void sendCallback(String message, boolean success) {
if (success && cb_autoSend_succ != null) {
cb_autoSend_succ.invoke(message);
cb_autoSend_succ = null;
} else if (!success && cb_autoSend_err != null) {
cb_autoSend_err.invoke(message);
cb_autoSend_err = null;
}
}
@ReactMethod
public void autoSend(String phoneNumber, String message, final Callback errorCallback,
final Callback successCallback) {
cb_autoSend_succ = successCallback;
cb_autoSend_err = errorCallback;
try {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
sendCallback("SMS sent", true);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
sendCallback("Generic failure", false);
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
sendCallback("No service", false);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
sendCallback("Null PDU", false);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
sendCallback("Radio off", false);
break;
}
}
}, new IntentFilter(SENT));
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
sendEvent(mReactContext, "sms_onDelivery", "SMS delivered");
break;
case Activity.RESULT_CANCELED:
sendEvent(mReactContext, "sms_onDelivery", "SMS not delivered");
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
} catch (Exception e) {
sendCallback(e.getMessage(), false);
}
}
}
|
package javax.time.calendar;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
/**
* A set of date-time fields.
* <p>
* Instances of this class store a map of field-value pairs.
* Together these specify constraints on the dates and times that match.
* For example, if an instance stores 'DayOfMonth=13' and 'DayOfWeek=Friday'
* then it represents and matches only dates of Friday the Thirteenth.
* <p>
* All the values will be within the valid range for the field.
* However, there is no cross validation between fields.
* Thus, it is possible for the date-time represented to never exist.
* For example, if an instance stores 'DayOfMonth=31' and 'MonthOfYear=February'
* then there will never be a matching date.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public final class DateTimeFields
implements CalendricalProvider,
DateMatcher, TimeMatcher, Iterable<DateTimeFieldRule>, Serializable {
/** Serialization version. */
private static final long serialVersionUID = 1L;
/** A singleton empty field set, placing no restrictions on the date-time. */
private static final DateTimeFields EMPTY = new DateTimeFields(createMap());
/**
* The date time map, never null, may be empty.
*/
private final TreeMap<DateTimeFieldRule, Integer> fieldValueMap;
/**
* Obtains an empty instance of <code>DateTimeFields</code>.
*
* @return a DateTimeFields object, never null
*/
public static DateTimeFields fields() {
return EMPTY;
}
public static DateTimeFields fields(DateTimeFieldRule fieldRule, int value) {
checkNotNull(fieldRule, "The field rule must not be null");
fieldRule.checkValue(value);
TreeMap<DateTimeFieldRule, Integer> map = createMap();
map.put(fieldRule, value);
return new DateTimeFields(map);
}
public static DateTimeFields fields(DateTimeFieldRule fieldRule1, int value1, DateTimeFieldRule fieldRule2, int value2) {
checkNotNull(fieldRule1, "The first field rule must not be null");
checkNotNull(fieldRule2, "The second field rule must not be null");
fieldRule1.checkValue(value1);
fieldRule2.checkValue(value2);
TreeMap<DateTimeFieldRule, Integer> map = createMap();
map.put(fieldRule1, value1);
map.put(fieldRule2, value2);
return new DateTimeFields(map);
}
public static DateTimeFields fields(Map<DateTimeFieldRule, Integer> fieldValueMap) {
checkNotNull(fieldValueMap, "The field-value map must not be null");
if (fieldValueMap.isEmpty()) {
return EMPTY;
}
// don't use contains() as tree map and others can throw NPE
TreeMap<DateTimeFieldRule, Integer> map = createMap();
for (Entry<DateTimeFieldRule, Integer> entry : fieldValueMap.entrySet()) {
DateTimeFieldRule fieldRule = entry.getKey();
Integer value = entry.getValue();
checkNotNull(fieldRule, "Null keys are not permitted in field-value map");
checkNotNull(value, "Null values are not permitted in field-value map");
fieldRule.checkValue(value);
map.put(fieldRule, value);
}
return new DateTimeFields(map);
}
/**
* Creates a new empty map.
*
* @return ordered representation of internal map
*/
private static TreeMap<DateTimeFieldRule, Integer> createMap() {
return new TreeMap<DateTimeFieldRule, Integer>(Collections.reverseOrder());
}
/**
* Validates that the input value is not null.
*
* @param object the object to check
* @param errorMessage the error to throw
* @throws NullPointerException if the object is null
*/
private static void checkNotNull(Object object, String errorMessage) {
if (object == null) {
throw new NullPointerException(errorMessage);
}
}
/**
* Constructor.
* @param assignedMap the map of fields, which is assigned, not null
*/
private DateTimeFields(TreeMap<DateTimeFieldRule, Integer> assignedMap) {
fieldValueMap = assignedMap;
}
/**
* Ensure EMPTY singleton.
*
* @return the resolved instance
* @throws ObjectStreamException if an error occurs
*/
private Object readResolve() throws ObjectStreamException {
return fieldValueMap.isEmpty() ? EMPTY : this;
}
/**
* The size of the map of fields to values.
*
* @return number of field-value pairs
*/
public int size() {
return fieldValueMap.size();
}
/**
* Iterates through all the fields.
* <p>
* This method fulfils the {@link Iterable} interface and allows looping
* around the fields using the for-each loop. The values can be obtained using
* {@link #getValueInt(DateTimeFieldRule)}.
*
* @return an iterator over the fields in this object, never null
*/
public Iterator<DateTimeFieldRule> iterator() {
return fieldValueMap.keySet().iterator();
}
/**
* Checks if a value can be obtained for the specified field.
*
* @param fieldRule the field to query, null returns false
* @return true if the field is supported, false otherwise
*/
public boolean isSupported(DateTimeFieldRule fieldRule) {
if (fieldRule == null) {
return false;
}
return fieldValueMap.containsKey(fieldRule);
}
/**
* Gets the value for the specified field returning null if the field is
* not in the field-value map.
* <p>
* The value will be within the valid range for the field.
* No cross-validation between fields is performed.
*
* @param fieldRule the rule to query from the map, null returns null
* @return the value mapped to the specified field, null if not present
*/
public Integer getValue(DateTimeFieldRule fieldRule) {
if (fieldRule == null) {
return null;
}
return fieldValueMap.get(fieldRule);
}
/**
* Gets the value for the specified field throwing an exception if the
* field is not in the field-value map.
* <p>
* The value will be within the valid range for the field.
* No cross-validation between fields is performed.
*
* @param fieldRule the rule to query from the map, not null
* @return the value mapped to the specified field
* @throws UnsupportedCalendarFieldException if the field is not in the map
*/
public int getValueInt(DateTimeFieldRule fieldRule) {
checkNotNull(fieldRule, "The field rule must not be null");
Integer value = fieldValueMap.get(fieldRule);
if (value == null) {
throw new UnsupportedCalendarFieldException(fieldRule, "DateTimeFields");
}
return value;
}
public DateTimeFields withFieldValue(DateTimeFieldRule fieldRule, int value) {
checkNotNull(fieldRule, "The field rule must not be null");
fieldRule.checkValue(value);
TreeMap<DateTimeFieldRule, Integer> clonedMap = clonedMap();
clonedMap.put(fieldRule, value);
return new DateTimeFields(clonedMap);
}
public DateTimeFields withFields(Map<DateTimeFieldRule, Integer> fieldValueMap) {
checkNotNull(fieldValueMap, "The field-value map must not be null");
if (fieldValueMap.isEmpty()) {
return this;
}
// don't use contains() as tree map and others can throw NPE
TreeMap<DateTimeFieldRule, Integer> clonedMap = clonedMap();
for (Entry<DateTimeFieldRule, Integer> entry : fieldValueMap.entrySet()) {
DateTimeFieldRule fieldRule = entry.getKey();
Integer value = entry.getValue();
checkNotNull(fieldRule, "Null keys are not permitted in field-value map");
checkNotNull(value, "Null values are not permitted in field-value map");
fieldRule.checkValue(value);
clonedMap.put(fieldRule, value);
}
return new DateTimeFields(clonedMap);
}
/**
* Returns a copy of this DateTimeFields with the fields from the specified set added.
* <p>
* If this instance already has a value for the field then the value is replaced.
* Otherwise the value is added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param fields the field set to add to the returned instance, not null
* @return a new, updated DateTimeFields, never null
*/
public DateTimeFields withFields(DateTimeFields fields) {
checkNotNull(fields, "The field-set must not be null");
if (fields.size() == 0 || fields == this) {
return this;
}
TreeMap<DateTimeFieldRule, Integer> clonedMap = clonedMap();
clonedMap.putAll(fields.fieldValueMap);
return new DateTimeFields(clonedMap);
}
/**
* Returns a copy of this DateTimeFields with the specified field removed.
* <p>
* If this instance does not contain the field then the returned instance
* is the same as this one.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param fieldRule the field to set in the returned set of fields, not null
* @return a new, updated DateTimeFields, never null
*/
public DateTimeFields withFieldRemoved(DateTimeFieldRule fieldRule) {
checkNotNull(fieldRule, "The field rule must not be null");
TreeMap<DateTimeFieldRule, Integer> clonedMap = clonedMap();
if (clonedMap.remove(fieldRule) == null) {
return this;
}
return clonedMap.isEmpty() ? EMPTY : new DateTimeFields(clonedMap);
}
// /**
// * Merges the fields in this map to form a calendrical.
// * <p>
// * The merge process aims to extract the maximum amount of information
// * possible from this set of fields. Ideally the outcome will be a date, time
// * or both, however there may be insufficient information to achieve this.
// * <p>
// * The process repeatedly calls the field rule {@link DateTimeFieldRule#merge merge}
// * method to perform the merge on each individual field. Sometimes two or
// * more fields will combine to form a more significant field. Sometimes they
// * will combine to form a date or time. The process stops when there no more
// * merges can occur.
// * <p>
// * The process is based around hierarchies that can be combined.
// * For example, QuarterOfYear and MonthOfQuarter can be combined to form MonthOfYear.
// * Then, MonthOfYear can be combined with DayOfMonth and Year to form a date.
// * Any fields which take part in a merge will be removed from the result as their
// * values can be derived from the merged field.
// * <p>
// * The exact definition of which fields combine with which is chronology dependent.
// * For example, see {@link ISOChronology}.
// * <p>
// * The details of the process are controlled by the merge context.
// * This includes strict/lenient behaviour.
// * <p>
// * The merge must result in consistent values for each field, date and time.
// * If two different values are produced an exception is thrown.
// * For example, both Year/MonthOfYear/DayOfMonth and Year/DayOfYear will merge to form a date.
// * If both sets of fields do not produce the same date then an exception will be thrown.
// *
// * @return the new instance, with merged fields, never null
// * @throws CalendricalException if the fields cannot be merged
// */
// public Calendrical mergeStrict() {
// if (fieldValueMap.size() == 0) {
// return new Calendrical();
// CalendricalMerger merger = new CalendricalMerger(this, new CalendricalContext(true, true));
// merger.merge();
// return merger.toCalendrical();
/**
* Checks if the date fields in this set of fields match the specified date.
* <p>
* This implementation checks that all date fields in this field set match the input date.
*
* @param date the date to match, not null
* @return true if the date fields match, false otherwise
*/
public boolean matchesDate(LocalDate date) {
checkNotNull(date, "The date to match against must not be null");
for (Entry<DateTimeFieldRule, Integer> entry : fieldValueMap.entrySet()) {
Integer dateValue = entry.getKey().getValueQuiet(date, null);
if (dateValue != null && dateValue.equals(entry.getValue()) == false) {
return false;
}
}
return true;
}
/**
* Checks if the time fields in this set of fields match the specified time.
* <p>
* This implementation checks that all time fields in this field set match the input time.
*
* @param time the time to match, not null
* @return true if the time fields match, false otherwise
*/
public boolean matchesTime(LocalTime time) {
checkNotNull(time, "The time to match against must not be null");
for (Entry<DateTimeFieldRule, Integer> entry : fieldValueMap.entrySet()) {
Integer timeValue = entry.getKey().getValueQuiet(null, time);
if (timeValue != null && timeValue.equals(entry.getValue()) == false) {
return false;
}
}
return true;
}
/**
* Converts this field set to a map of fields to values.
* <p>
* The map will never be null, however it may be empty.
* The values contained in the map might be out of range for the rule.
* <p>
* For example, the day of month might be set to 75, or the hour to 1000.
* The purpose of this class is simply to store the values, not to provide
* any guarantees as to their validity.
*
* @return a modifiable copy of the field-value map, never null
*/
public Map<DateTimeFieldRule, Integer> toFieldValueMap() {
return new HashMap<DateTimeFieldRule, Integer>(fieldValueMap);
}
/**
* Clones the field-value map.
*
* @return a clone of the field-value map, never null
*/
private TreeMap<DateTimeFieldRule, Integer> clonedMap() {
TreeMap<DateTimeFieldRule, Integer> cloned = createMap();
cloned.putAll(fieldValueMap);
return cloned;
}
/**
* Copies the field-value map into the specified map.
*
* @param map the map to copy into, not null
*/
void copyInto(Map<DateTimeFieldRule, Integer> map) {
map.putAll(fieldValueMap);
}
// public LocalDate toLocalDate() {
// LocalDate date = mergeToDate(true, true);
// if (date == null) {
// throw new CalendarConversionException(
// "Cannot convert DateTimeFields to LocalDate, insufficient infomation to create a date");
// return date;
// public LocalTime toLocalTime() {
// LocalTime time = mergeToTime(true, true);
// if (time == null) {
// throw new CalendarConversionException(
// "Cannot convert DateTimeFields to LocalTime, insufficient infomation to create a time");
// return time;
// /**
// * Converts this object to a LocalDateTime.
// * <p>
// * This method will validate and merge the fields to create a date-time.
// * This merge process is strict as defined by {@link #mergeToDateTime}.
// *
// * @return the LocalDateTime, never null
// * @throws InvalidCalendarFieldException if any field is invalid
// * @throws CalendarConversionException if the date or time cannot be converted
// */
// public LocalDateTime toLocalDateTime() {
// LocalDateTime dateTime = mergeToDateTime(true, true);
// if (dateTime == null) {
// throw new CalendarConversionException(
// "Cannot convert DateTimeFields to LocalTime, insufficient infomation to create a date-time");
// return dateTime;
/**
* Converts this object to a calendrical with the same set of fields.
*
* @return the calendrical with the same set of fields, never null
*/
public Calendrical toCalendrical() {
return new Calendrical(this);
}
/**
* Is this set of fields equal to the specified set.
*
* @param obj the other field set to compare to, null returns false
* @return true if this instance is equal to the specified field set
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof DateTimeFields) {
DateTimeFields other = (DateTimeFields) obj;
return fieldValueMap.equals(other.fieldValueMap);
}
return false;
}
/**
* A hash code for this set of fields.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return fieldValueMap.hashCode();
}
/**
* Outputs the set of fields as a <code>String</code>.
* <p>
* The output will consist of the field-value map in standard map format.
*
* @return the formatted date-time string, never null
*/
@Override
public String toString() {
return fieldValueMap.toString();
}
}
|
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.File;
import java.util.*;
public class CacheTest {
public static class ArrayCache {
final Object[] storage;
public ArrayCache(int[] keys, Object[] values) {
storage = new Object[keys[keys.length - 1] + 1];
for (int i = 0; i < keys.length; i++) storage[keys[i]] = values[i];
}
public Object get(int key) {
return key < storage.length ? storage[key] : null;
}
}
public static class BinarySearchCache {
final int[] keys;
final Object[] values;
public BinarySearchCache(int[] keys, Object[] values) {
this.keys = keys.clone();
this.values = values;
}
public Object get(int key) {
int pos = Arrays.binarySearch(keys, key);
return pos >= 0 ? values[pos] : null;
}
}
public static class SortedBucketsCache {
final int[] cnt;
final int[] a;
final Object[] storage;
final int mask;
public SortedBucketsCache(int[] keys, Object[] values) {
int n = 1;
while (n < keys.length)
n *= 2;
mask = n - 1;
cnt = new int[n + 1];
for (int id : keys)
++cnt[id & mask];
for (int i = 1; i < cnt.length; i++)
cnt[i] += cnt[i - 1];
a = new int[keys.length];
storage = new Object[values.length];
for (int i = keys.length - 1; i >= 0; i
int id = keys[i];
a[--cnt[id & mask]] = id;
storage[cnt[id & mask]] = values[i];
}
}
public Object get(int key) {
int bucket = key & mask;
int pos = Arrays.binarySearch(a, cnt[bucket], cnt[bucket + 1], key);
return pos >= 0 ? storage[pos] : null;
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("D:/Dropbox/map/b.txt"));
List<Integer> list = new ArrayList<>();
while (sc.hasNext()) {
list.add(sc.nextInt());
}
for (int i = 0; i + 1 < list.size(); i++) if (list.get(i) >= list.get(i + 1)) throw new RuntimeException();
final int steps = 1000;
Random rnd = new Random(1);
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < 200000; i++) {
set.add(rnd.nextInt(1000000));
}
list.clear();
list.addAll(set);
Collections.sort(list);
List<Integer> list2 = new ArrayList<>(list);
Collections.shuffle(list2);
int[] access = new int[list2.size()];
for (int i = 0; i < access.length; i++) {
access[i] = list2.get(i);
}
int[] ids = new int[list.size()];
Object[] objects = new Object[ids.length];
for (int i = 0; i < ids.length; i++) {
ids[i] = list.get(i);
objects[i] = list.get(i);
}
Map<Integer, Object> map1 = new HashMap<>();
Int2ObjectMap map2 = new Int2ObjectOpenHashMap();
ArrayCache arrayCache = new ArrayCache(ids, objects);
BinarySearchCache binarySearchCache = new BinarySearchCache(ids, objects);
SortedBucketsCache sortedBucketsCache = new SortedBucketsCache(ids, objects);
for (int i = 0; i < ids.length; i++) {
map1.put(ids[i], objects[i]);
map2.put(ids[i], objects[i]);
}
for (int i = 0; i < 1000000; i++) {
Object o1 = arrayCache.get(i);
Object o2 = binarySearchCache.get(i);
Object o3 = sortedBucketsCache.get(i);
Object o4 = map1.get(i);
Object o5 = map2.get(i);
if (o1 != o2 || o1 != o3 || o1 != o4 || o1 != o5)
throw new RuntimeException();
}
long time = System.currentTimeMillis();
Object[] objects2 = new Object[1000000];
for (int i = 0; i < objects2.length; i++) objects2[i] = i;
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = objects2[access[i]];
// int o = access[i];
}
}
System.out.println("array = " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = arrayCache.get(access[i]);
}
}
System.out.println("arrayCache = " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = sortedBucketsCache.get(access[i]);
}
}
System.out.println("sortedBucketsCache = " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = map2.get(access[i]);
}
}
System.out.println("Int2ObjectOpenHashMap = " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = binarySearchCache.get(access[i]);
}
}
System.out.println("binarySearchCache = " + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
for (int step = 0; step < steps; step++) {
for (int i = 0; i < ids.length; i++) {
Object o = map1.get(access[i]);
}
}
System.out.println("HashMap = " + (System.currentTimeMillis() - time));
}
}
|
package logbook.internal.gui;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.controlsfx.control.ToggleSwitch;
import org.controlsfx.control.textfield.TextFields;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.Labeled;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.TitledPane;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.converter.IntegerStringConverter;
import logbook.bean.AppConfig;
import logbook.bean.AppShipTableConfig;
import logbook.bean.AppShipTableConfig.AppShipTableTabConfig;
import logbook.bean.DeckPort;
import logbook.bean.DeckPortCollection;
import logbook.bean.Ship;
import logbook.bean.ShipCollection;
import logbook.bean.ShipLabelCollection;
import logbook.bean.ShipMst;
import logbook.bean.ShipMstCollection;
import logbook.bean.SlotItem;
import logbook.bean.SlotItemCollection;
import logbook.internal.Items;
import logbook.internal.LoggerHolder;
import logbook.internal.Operator;
import logbook.internal.ShipFilter;
import logbook.internal.Ships;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.val;
public class ShipTablePane extends VBox {
@FXML
private TitledPane filter;
@FXML
private ToggleSwitch textFilter;
@FXML
private TextField textValue;
@FXML
private ToggleSwitch typeFilter;
@FXML
private CheckBox escort;
@FXML
private CheckBox destroyer;
@FXML
private CheckBox lightCruiser;
@FXML
private CheckBox torpedoCruiser;
@FXML
private CheckBox heavyCruiser;
@FXML
private CheckBox flyingDeckCruiser;
@FXML
private CheckBox seaplaneTender;
@FXML
private CheckBox escortCarrier;
@FXML
private CheckBox carrier;
@FXML
private CheckBox armoredcarrier;
@FXML
private CheckBox battleship;
@FXML
private CheckBox flyingDeckBattleship;
@FXML
private CheckBox submarine;
@FXML
private CheckBox carrierSubmarine;
@FXML
private CheckBox landingship;
@FXML
private CheckBox repairship;
@FXML
private CheckBox submarineTender;
@FXML
private CheckBox trainingShip;
@FXML
private CheckBox supply;
@FXML
private CheckBox allTypes;
@FXML
private ToggleSwitch condFilter;
@FXML
private TextField conditionValue;
@FXML
private ChoiceBox<Operator> conditionType;
@FXML
private ToggleSwitch levelFilter;
@FXML
private TextField levelValue;
@FXML
private ChoiceBox<Operator> levelType;
@FXML
private ToggleSwitch labelFilter;
@FXML
private ChoiceBox<String> labelValue;
@FXML
private ToggleSwitch slotExFilter;
@FXML
private CheckBox slotExValue;
@FXML
private ToggleSwitch missionFilter;
@FXML
private CheckBox missionValue;
@FXML
private TableView<ShipItem> table;
@FXML
private TableColumn<ShipItem, Integer> row;
@FXML
private TableColumn<ShipItem, Integer> id;
@FXML
private TableColumn<ShipItem, Ship> ship;
@FXML
private TableColumn<ShipItem, String> type;
@FXML
private TableColumn<ShipItem, Integer> lv;
@FXML
private TableColumn<ShipItem, Integer> exp;
/** Next */
@FXML
private TableColumn<ShipItem, Integer> next;
/** cond */
@FXML
private TableColumn<ShipItem, Integer> cond;
@FXML
private TableColumn<ShipItem, Set<String>> label;
@FXML
private TableColumn<ShipItem, Integer> seiku;
@FXML
private TableColumn<ShipItem, Integer> hPower;
@FXML
private TableColumn<ShipItem, Integer> rPower;
@FXML
private TableColumn<ShipItem, Integer> yPower;
@FXML
private TableColumn<ShipItem, Integer> tPower;
@FXML
private TableColumn<ShipItem, Integer> karyoku;
@FXML
private TableColumn<ShipItem, Integer> raisou;
@FXML
private TableColumn<ShipItem, Integer> taiku;
@FXML
private TableColumn<ShipItem, Integer> tais;
@FXML
private TableColumn<ShipItem, Integer> sakuteki;
@FXML
private TableColumn<ShipItem, Integer> lucky;
@FXML
private TableColumn<ShipItem, Integer> maxhp;
@FXML
private TableColumn<ShipItem, Integer> soukou;
@FXML
private TableColumn<ShipItem, Integer> kaihi;
@FXML
private TableColumn<ShipItem, Integer> soku;
@FXML
private TableColumn<ShipItem, Integer> leng;
@FXML
private TableColumn<ShipItem, Integer> slot1;
@FXML
private TableColumn<ShipItem, Integer> slot2;
@FXML
private TableColumn<ShipItem, Integer> slot3;
@FXML
private TableColumn<ShipItem, Integer> slot4;
@FXML
private TableColumn<ShipItem, Integer> slot5;
@FXML
private TableColumn<ShipItem, Integer> slotEx;
private final Supplier<List<Ship>> shipSupplier;
private final ObservableList<ShipItem> shipItems = FXCollections.observableArrayList();
private final FilteredList<ShipItem> filteredShipItems = new FilteredList<>(this.shipItems);
private boolean enable;
private boolean disableFilterUpdate;
private int shipsHashCode;
private String fleetName;
/**
*
*
* @param port
*/
public ShipTablePane(DeckPort port) {
this(() -> {
Map<Integer, Ship> shipMap = ShipCollection.get()
.getShipMap();
DeckPort newPort = DeckPortCollection.get()
.getDeckPortMap()
.get(port.getId());
if (newPort != null) {
return newPort.getShip().stream()
.map(shipMap::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
return Collections.emptyList();
}, port.getName());
}
/**
*
*
* @param shipSupplier
*/
public ShipTablePane(Supplier<List<Ship>> shipSupplier, String fleetName) {
this.shipSupplier = shipSupplier;
this.fleetName = fleetName;
try {
FXMLLoader loader = InternalFXMLLoader.load("logbook/gui/ship_table.fxml");
loader.setRoot(this);
loader.setController(this);
loader.load();
} catch (IOException e) {
LoggerHolder.get().error("FXML", e);
}
}
@FXML
void initialize() {
try {
TableTool.setVisible(this.table, this.getClass().toString() + "#" + "table");
this.disableFilterUpdate = true;
this.filter.expandedProperty().addListener((ob, ov, nv) -> {
this.saveConfig();
});
this.conditionType.setItems(FXCollections.observableArrayList(Operator.values()));
this.conditionType.getSelectionModel().select(Operator.GE);
this.levelType.setItems(FXCollections.observableArrayList(Operator.values()));
this.levelType.getSelectionModel().select(Operator.GE);
this.textFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.textValue.setDisable(!nv);
});
this.typeFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.typeCheckBox().forEach(c -> c.setDisable(!nv));
this.allTypes.setDisable(!nv);
});
this.condFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.conditionValue.setDisable(!nv);
this.conditionType.setDisable(!nv);
});
this.levelFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.levelValue.setDisable(!nv);
this.levelType.setDisable(!nv);
});
this.labelFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.labelValue.setDisable(!nv);
});
this.slotExFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.slotExValue.setDisable(!nv);
});
this.missionFilter.selectedProperty().addListener((ob, ov, nv) -> {
this.missionValue.setDisable(!nv);
});
this.textFilter.selectedProperty().addListener(this::filterAction);
this.textValue.textProperty().addListener(this::filterAction);
this.typeFilter.selectedProperty().addListener(this::filterAction);
this.typeCheckBox().forEach(c -> c.selectedProperty().addListener(this::filterAction));
this.condFilter.selectedProperty().addListener(this::filterAction);
this.conditionValue.textProperty().addListener(this::filterAction);
this.conditionType.getSelectionModel().selectedItemProperty().addListener(this::filterAction);
this.levelFilter.selectedProperty().addListener(this::filterAction);
this.levelValue.textProperty().addListener(this::filterAction);
this.levelType.getSelectionModel().selectedItemProperty().addListener(this::filterAction);
this.labelFilter.selectedProperty().addListener(this::filterAction);
this.labelValue.getSelectionModel().selectedItemProperty().addListener(this::filterAction);
this.slotExFilter.selectedProperty().addListener(this::filterAction);
this.slotExValue.selectedProperty().addListener(this::filterAction);
this.missionFilter.selectedProperty().addListener(this::filterAction);
this.missionValue.selectedProperty().addListener(this::filterAction);
this.conditionValue.setTextFormatter(new TextFormatter<>(new IntegerStringConverter()));
TextFields.bindAutoCompletion(this.conditionValue, new SuggestSupport("53", "50", "49", "33", "30", "20"));
this.conditionValue.setText("53");
this.levelValue.setTextFormatter(new TextFormatter<>(new IntegerStringConverter()));
TextFields.bindAutoCompletion(this.levelValue,
new SuggestSupport("100", "99", "90", "80", "75", "70", "65", "60", "55", "50", "40", "30", "20"));
this.levelValue.setText("98");
this.row.setCellFactory(e -> {
TableCell<ShipItem, Integer> cell = new TableCell<ShipItem, Integer>() {
@Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
TableRow<?> currentRow = this.getTableRow();
this.setText(Integer.toString(currentRow.getIndex() + 1));
} else {
this.setText(null);
}
}
};
return cell;
});
this.id.setCellValueFactory(new PropertyValueFactory<>("id"));
this.ship.setCellValueFactory(new PropertyValueFactory<>("ship"));
this.ship.setCellFactory(p -> new ShipImageCell());
this.type.setCellValueFactory(new PropertyValueFactory<>("type"));
this.lv.setCellValueFactory(new PropertyValueFactory<>("lv"));
this.exp.setCellValueFactory(new PropertyValueFactory<>("exp"));
this.next.setCellValueFactory(new PropertyValueFactory<>("next"));
this.cond.setCellFactory(p -> new CondCell());
this.cond.setCellValueFactory(new PropertyValueFactory<>("cond"));
this.label.setCellValueFactory(new PropertyValueFactory<>("label"));
this.label.setCellFactory(p -> new LabelCell());
this.seiku.setCellValueFactory(new PropertyValueFactory<>("seiku"));
this.hPower.setCellValueFactory(new PropertyValueFactory<>("hPower"));
this.rPower.setCellValueFactory(new PropertyValueFactory<>("rPower"));
this.yPower.setCellValueFactory(new PropertyValueFactory<>("yPower"));
this.tPower.setCellValueFactory(new PropertyValueFactory<>("tPower"));
this.karyoku.setCellValueFactory(new PropertyValueFactory<>("karyoku"));
this.raisou.setCellValueFactory(new PropertyValueFactory<>("raisou"));
this.taiku.setCellValueFactory(new PropertyValueFactory<>("taiku"));
this.tais.setCellValueFactory(new PropertyValueFactory<>("tais"));
this.sakuteki.setCellValueFactory(new PropertyValueFactory<>("sakuteki"));
this.lucky.setCellValueFactory(new PropertyValueFactory<>("lucky"));
this.maxhp.setCellValueFactory(new PropertyValueFactory<>("maxhp"));
this.soukou.setCellValueFactory(new PropertyValueFactory<>("soukou"));
this.kaihi.setCellValueFactory(new PropertyValueFactory<>("kaihi"));
this.soku.setCellValueFactory(new PropertyValueFactory<>("soku"));
this.soku.setCellFactory(p -> new TableCell<ShipItem, Integer>() {
@Override
protected void updateItem(Integer i, boolean empty) {
super.updateItem(i, empty);
this.setText(Ships.sokuText(i));
}
});
this.leng.setCellValueFactory(new PropertyValueFactory<>("leng"));
this.leng.setCellFactory(p -> new TableCell<ShipItem, Integer>() {
@Override
protected void updateItem(Integer i, boolean empty) {
super.updateItem(i, empty);
this.setText(Ships.lengText(i));
}
});
this.slot1.setCellValueFactory(new PropertyValueFactory<>("slot1"));
this.slot1.setCellFactory(p -> new ItemImageCell());
this.slot2.setCellValueFactory(new PropertyValueFactory<>("slot2"));
this.slot2.setCellFactory(p -> new ItemImageCell());
this.slot3.setCellValueFactory(new PropertyValueFactory<>("slot3"));
this.slot3.setCellFactory(p -> new ItemImageCell());
this.slot4.setCellValueFactory(new PropertyValueFactory<>("slot4"));
this.slot4.setCellFactory(p -> new ItemImageCell());
this.slot5.setCellValueFactory(new PropertyValueFactory<>("slot5"));
this.slot5.setCellFactory(p -> new ItemImageCell());
this.slotEx.setCellValueFactory(new PropertyValueFactory<>("slotEx"));
this.slotEx.setCellFactory(p -> new ItemImageCell());
this.table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
SortedList<ShipItem> sortedList = new SortedList<>(this.filteredShipItems);
this.table.setItems(sortedList);
sortedList.comparatorProperty().bind(this.table.comparatorProperty());
this.table.setOnKeyPressed(TableTool::defaultOnKeyPressedHandler);
this.table.setStyle("-fx-cell-size: 16px;");
this.disableFilterUpdate = false;
this.loadConfig();
} catch (Exception e) {
LoggerHolder.get().error("FXML", e);
}
}
public void enable() {
this.enable = true;
}
public void disable() {
this.enable = false;
}
public void update() {
try {
if (!this.enable) {
return;
}
List<Ship> ships = this.shipSupplier.get();
if (this.shipsHashCode != ships.hashCode()) {
this.shipsHashCode = ships.hashCode();
this.shipItems.clear();
this.shipItems.addAll(ships.stream()
.map(ShipItem::toShipItem)
.collect(Collectors.toList()));
this.updateLabel();
}
} catch (Exception e) {
LoggerHolder.get().error("", e);
}
}
private void updateLabel() {
Set<String> labels = new TreeSet<>();
this.shipItems.forEach(ship -> {
labels.addAll(ship.getLabel());
});
Set<String> beforeLabels = new HashSet<>(this.labelValue.getItems());
this.labelValue.getItems().removeIf(l -> !labels.contains(l));
for (String label : labels) {
if (!beforeLabels.contains(label)) {
this.labelValue.getItems().add(label);
}
}
}
@FXML
void allTypeAction() {
this.disableFilterUpdate = true;
boolean selected = this.allTypes.isSelected();
this.typeCheckBox().forEach(c -> c.setSelected(selected));
this.disableFilterUpdate = false;
this.updateFilter();
}
@FXML
void copy() {
TableTool.selectionCopy(this.table);
}
@FXML
void selectAll() {
TableTool.selectAll(this.table);
}
/**
* CSV
*/
@FXML
void store() {
try {
TableTool.store(this.table, "(" + this.fleetName + ")", this.getScene().getWindow());
} catch (IOException e) {
LoggerHolder.get().error("CSV", e);
}
}
@FXML
void addLabel() {
if (this.table.getSelectionModel()
.getSelectedItems()
.isEmpty()) {
Tools.Conrtols.alert(AlertType.INFORMATION,
"",
"",
this.getScene().getWindow());
return;
}
String shipNames = this.table.getSelectionModel()
.getSelectedItems()
.stream()
.map(ship -> Ships.shipMst(ship.getShip()).map(ShipMst::getName).orElse(""))
.collect(Collectors.joining(","));
if (shipNames.length() > 50) {
shipNames = shipNames.substring(0, 50) + "...";
}
TextInputDialog dialog = new TextInputDialog("");
dialog.initOwner(this.getScene().getWindow());
dialog.setTitle("");
dialog.setHeaderText(shipNames + "");
TextFields.bindAutoCompletion(dialog.getEditor(), new SuggestSupport(this.labelValue.getItems()));
val result = dialog.showAndWait();
if (result.isPresent()) {
String label = result.get();
if (!label.isEmpty()) {
val labelMap = ShipLabelCollection.get()
.getLabels();
val selections = this.table.getSelectionModel()
.getSelectedItems();
for (ShipItem ship : selections) {
ship.labelProperty().get()
.add(label);
val labels = labelMap.computeIfAbsent(ship.getId(), k -> new LinkedHashSet<>());
labels.add(label);
}
this.updateLabel();
this.table.refresh();
}
}
}
@FXML
void removeLabel() {
if (this.table.getSelectionModel()
.getSelectedItems()
.isEmpty()) {
Tools.Conrtols.alert(AlertType.INFORMATION,
"",
"",
this.getScene().getWindow());
return;
}
String shipNames = this.table.getSelectionModel()
.getSelectedItems()
.stream()
.map(ship -> Ships.shipMst(ship.getShip()).map(ShipMst::getName).orElse(""))
.collect(Collectors.joining(","));
if (shipNames.length() > 50) {
shipNames = shipNames.substring(0, 50) + "...";
}
Set<String> labels = new TreeSet<>();
val selections = this.table.getSelectionModel()
.getSelectedItems();
for (ShipItem ship : selections) {
labels.addAll(ship.getLabel());
}
ChoiceDialog<String> dialog = new ChoiceDialog<>();
dialog.initOwner(this.getScene().getWindow());
dialog.getItems().addAll(labels);
dialog.setTitle("");
dialog.setHeaderText(shipNames + "");
val result = dialog.showAndWait();
if (result.isPresent()) {
String label = result.get();
if (!label.isEmpty()) {
val labelMap = ShipLabelCollection.get()
.getLabels();
for (ShipItem ship : selections) {
ship.labelProperty().get()
.remove(label);
labelMap.computeIfPresent(ship.getId(), (k, v) -> {
v.remove(label);
if (v.isEmpty())
return null;
return v;
});
}
this.updateLabel();
this.table.refresh();
}
}
}
@FXML
void kanmusuListCopyAll() {
KanmusuList.copyAll();
}
@FXML
void kanmusuListDisplayCopy() {
KanmusuList.displayCopy(this.table);
}
@FXML
void kanmusuListSelectionCopy() {
KanmusuList.selectionCopy(this.table);
}
@FXML
void columnVisible() {
try {
TableTool.showVisibleSetting(this.table, this.getClass().toString() + "#" + "table",
(Stage) this.getScene().getWindow());
} catch (Exception e) {
LoggerHolder.get().error("FXML", e);
}
}
/**
*
* @return
*/
private List<CheckBox> typeCheckBox() {
return Arrays.asList(
this.escort,
this.destroyer,
this.lightCruiser,
this.torpedoCruiser,
this.heavyCruiser,
this.flyingDeckCruiser,
this.seaplaneTender,
this.escortCarrier,
this.carrier,
this.armoredcarrier,
this.battleship,
this.flyingDeckBattleship,
this.submarine,
this.carrierSubmarine,
this.landingship,
this.repairship,
this.submarineTender,
this.trainingShip,
this.supply);
}
private void filterAction(ObservableValue<?> observable, Object oldValue, Object newValue) {
this.updateFilter();
}
private void updateFilter() {
if (!this.disableFilterUpdate) {
Predicate<ShipItem> filter = this.createFilter();
this.filteredShipItems.setPredicate(filter);
this.saveConfig();
}
}
/**
*
* @return
*/
private Predicate<ShipItem> createFilter() {
Predicate<ShipItem> filter = null;
if (this.textFilter.isSelected()) {
filter = ShipFilter.TextFilter.builder()
.text(this.textValue.getText())
.build();
}
if (this.typeFilter.isSelected()) {
Set<String> types = this.typeCheckBox().stream()
.filter(CheckBox::isSelected)
.map(CheckBox::getText)
.collect(Collectors.toSet());
filter = this.filterAnd(filter, ShipFilter.TypeFilter.builder()
.types(types)
.build());
}
if (this.condFilter.isSelected()) {
int condition = Integer.parseInt(this.conditionValue.getText().isEmpty() ? "0"
: this.conditionValue.getText());
filter = this.filterAnd(filter, ShipFilter.CondFilter.builder()
.conditionValue(condition)
.conditionType(this.conditionType.getValue())
.build());
}
if (this.levelFilter.isSelected()) {
int level = Integer.parseInt(this.levelValue.getText().isEmpty() ? "0"
: this.levelValue.getText());
filter = this.filterAnd(filter, ShipFilter.LevelFilter.builder()
.levelValue(level)
.levelType(this.levelType.getValue())
.build());
}
if (this.labelFilter.isSelected()) {
filter = this.filterAnd(filter, ShipFilter.LabelFilter.builder()
.labelValue(this.labelValue.getValue() == null ? "" : this.labelValue.getValue())
.build());
}
if (this.slotExFilter.isSelected()) {
filter = this.filterAnd(filter, ShipFilter.SlotExFilter.builder()
.slotEx(this.slotExValue.isSelected())
.build());
}
if (this.missionFilter.isSelected()) {
filter = this.filterAnd(filter, ShipFilter.MissionFilter.builder()
.mission(this.missionValue.isSelected())
.build());
}
return filter;
}
private Predicate<ShipItem> filterAnd(Predicate<ShipItem> base, Predicate<ShipItem> add) {
if (base != null) {
return base.and(add);
}
return add;
}
private void loadConfig() {
AppShipTableTabConfig config = AppShipTableConfig.get()
.getTabConfig()
.get(this.fleetName);
if (config == null) {
return;
}
this.disableFilterUpdate = true;
this.filter.setExpanded(config.isExpanded());
this.textFilter.setSelected(config.isTextEnabled());
this.textValue.setText(config.getTextValue());
this.typeFilter.setSelected(config.isTypeEnabled());
this.typeCheckBox().forEach(c -> c.setSelected(config.getTypeValue().contains(c.getText())));
this.condFilter.setSelected(config.isConditionEnabled());
this.conditionValue.setText(config.getConditionValue());
this.conditionType.setValue(config.getConditionType());
this.levelFilter.setSelected(config.isLevelEnabled());
this.levelValue.setText(config.getLevelValue());
this.levelType.setValue(config.getLevelType());
this.labelFilter.setSelected(config.isLabelEnabled());
this.labelValue.setValue(config.getLabelValue());
this.slotExFilter.setSelected(config.isSlotExEnabled());
this.slotExValue.setSelected(config.isSlotExValue());
this.missionFilter.setSelected(config.isMissionEnabled());
this.missionValue.setSelected(config.isMissionValue());
this.disableFilterUpdate = false;
this.updateFilter();
}
private void saveConfig() {
AppShipTableTabConfig config = AppShipTableConfig.get()
.getTabConfig()
.getOrDefault(this.fleetName, new AppShipTableTabConfig());
if (this.disableFilterUpdate) {
return;
}
config.setExpanded(this.filter.isExpanded());
config.setTextEnabled(this.textFilter.isSelected());
config.setTextValue(this.textValue.getText());
config.setTypeEnabled(this.typeFilter.isSelected());
config.setTypeValue(this.typeCheckBox().stream()
.filter(CheckBox::isSelected)
.map(CheckBox::getText)
.collect(Collectors.toList()));
config.setConditionEnabled(this.condFilter.isSelected());
config.setConditionValue(this.conditionValue.getText());
config.setConditionType(this.conditionType.getValue());
config.setLevelEnabled(this.levelFilter.isSelected());
config.setLevelValue(this.levelValue.getText());
config.setLevelType(this.levelType.getValue());
config.setLabelEnabled(this.labelFilter.isSelected());
config.setLabelValue(this.labelValue.getValue());
config.setSlotExEnabled(this.slotExFilter.isSelected());
config.setSlotExValue(this.slotExValue.isSelected());
config.setMissionEnabled(this.missionFilter.isSelected());
config.setMissionValue(this.missionValue.isSelected());
AppShipTableConfig.get()
.getTabConfig()
.put(this.fleetName, config);
}
private static class ShipImageCell extends TableCell<ShipItem, Ship> {
@Override
protected void updateItem(Ship ship, boolean empty) {
super.updateItem(ship, empty);
if (!empty) {
this.setGraphic(Tools.Conrtols.zoomImage(new ImageView(Ships.shipWithItemImage(ship))));
this.setText(Ships.shipMst(ship)
.map(ShipMst::getName)
.orElse(""));
} else {
this.setGraphic(null);
this.setText(null);
}
}
}
private static class ItemImageCell extends TableCell<ShipItem, Integer> {
private Map<Integer, SlotItem> itemMap = SlotItemCollection.get()
.getSlotitemMap();
@Override
protected void updateItem(Integer itemId, boolean empty) {
super.updateItem(itemId, empty);
if (!empty) {
if (itemId == 0) {
this.getStyleClass().add("none");
} else {
this.getStyleClass().removeAll("none");
}
SlotItem item = this.itemMap.get(itemId);
if (item != null) {
ImageView img = new ImageView(Items.itemImage(item));
int percent = AppConfig.get().getImageZoomRate();
int size = 32;
if (percent > 0) {
size = (int) Math.min(size, 60 * ((double) percent / 100));
}
img.setFitWidth(size);
img.setFitHeight(size);
this.setGraphic(img);
this.setText(Items.name(item));
} else {
this.setGraphic(null);
this.setText(null);
}
} else {
this.setGraphic(null);
this.setText(null);
this.getStyleClass().removeAll("none");
}
}
}
private static class CondCell extends TableCell<ShipItem, Integer> {
@Override
protected void updateItem(Integer cond, boolean empty) {
super.updateItem(cond, empty);
if (!empty) {
ObservableList<String> styleClass = this.getStyleClass();
styleClass.removeAll("deepgreen", "green", "orange", "red");
if (cond >= Ships.DARK_GREEN && cond < Ships.GREEN) {
styleClass.add("deepgreen");
} else if (cond >= Ships.GREEN) {
styleClass.add("green");
} else if (cond <= Ships.ORANGE && cond > Ships.RED) {
styleClass.add("orange");
} else if (cond <= Ships.RED) {
styleClass.add("red");
}
this.setText(cond.toString());
} else {
this.setText(null);
}
}
}
class LabelCell extends TableCell<ShipItem, Set<String>> {
@Override
protected void updateItem(Set<String> labels, boolean empty) {
super.updateItem(labels, empty);
if (!empty) {
FlowPane pane = new FlowPane();
for (String label : labels) {
Button button = new Button(label);
button.setStyle("-fx-color: " + this.colorCode(label.hashCode()));
button.setOnAction(this::handle);
pane.getChildren().add(button);
}
this.setGraphic(pane);
this.setText(null);
} else {
this.setGraphic(null);
this.setText(null);
}
}
private void handle(ActionEvent e) {
Object src = e.getSource();
if (src instanceof Labeled) {
Labeled label = (Labeled) src;
ShipTablePane.this.labelValue.getSelectionModel().select(label.getText());
ShipTablePane.this.labelFilter.setSelected(true);
}
}
/**
* seed#rrggbb<br>
*
*
* @param seed
* @return
*/
private String colorCode(int seed) {
long n = 123456789L;
n ^= seed * 2685821657736338717L;
for (int i = 0; i < 3; i++) {
n ^= n >>> 13;
n ^= n << 17;
n ^= n >>> 15;
}
String hex = Long.toString(n & 0xFFFFFF, 16);
return "#" + ("000000" + hex).substring(hex.length());
}
}
public static class KanmusuList {
public static void copyAll() {
ClipboardContent content = new ClipboardContent();
content.putString(text(ShipCollection.get()
.getShipMap()
.values()));
Clipboard.getSystemClipboard().setContent(content);
}
/**
*
*
* @param table
*/
public static void displayCopy(TableView<ShipItem> table) {
ClipboardContent content = new ClipboardContent();
content.putString(text(table.getItems()
.stream()
.map(ShipItem::getShip)
.collect(Collectors.toList())));
Clipboard.getSystemClipboard().setContent(content);
}
/**
*
*
* @param table
*/
public static void selectionCopy(TableView<ShipItem> table) {
ClipboardContent content = new ClipboardContent();
content.putString(text(table.getSelectionModel()
.getSelectedItems()
.stream()
.map(ShipItem::getShip)
.collect(Collectors.toList())));
Clipboard.getSystemClipboard().setContent(content);
}
private static String text(Collection<Ship> ships) {
// ID => ID
Map<Integer, Kanmusu> map = new HashMap<>();
Map<Integer, ShipMst> shipMstMap = ShipMstCollection.get().getShipMap();
Map<Integer, Set<Integer>> groupMap = new HashMap<>();
for (ShipMst shipMst : shipMstMap.values()) {
Integer id = shipMst.getId();
Integer afterid = shipMst.getAftershipid();
if (afterid == null || afterid == 0) {
continue;
}
Set<Integer> list = new HashSet<>();
if (groupMap.containsKey(id))
list.addAll(groupMap.get(id));
if (groupMap.containsKey(afterid))
list.addAll(groupMap.get(afterid));
list.add(id);
list.add(afterid);
list.forEach(v -> groupMap.put(v, list));
}
for (Set<Integer> list : new HashSet<>(groupMap.values())) {
ShipMst root = list.stream()
.map(shipMstMap::get)
.filter(m -> m.getAftershipid() != 0)
.sorted(Comparator.comparing(ShipMst::getAfterlv))
.findFirst()
.get();
ShipMst after = root;
// aftershipid
int index = 0;
while (after != null && !map.containsKey(after.getId())) {
int afterlv = Optional.ofNullable(after.getAfterlv())
.filter(v -> v > 0)
.orElse(Integer.MAX_VALUE);
map.put(after.getId(), new Kanmusu(root.getId(), ++index, afterlv));
after = shipMstMap.get(after.getAftershipid());
}
}
return ".2|" + ships.stream()
.filter(s -> map.containsKey(s.getShipId()))
.map(s -> new Value(map.get(s.getShipId()), s.getLv()))
.sorted(Comparator.comparing(v -> v.ship.id))
.collect(Collectors.groupingBy(v -> v.ship.id, LinkedHashMap::new, Collectors.toList()))
.entrySet().stream()
.map(e -> e.getKey() + ":" + e.getValue().stream()
.sorted(Comparator.comparing(Value::getLv, Comparator.reverseOrder()))
.map(Value::toString)
.collect(Collectors.joining(",")))
.collect(Collectors.joining("|"));
}
@Data
@AllArgsConstructor
private static class Kanmusu {
private int id;
private int kai;
private int afterlv;
}
@Data
@AllArgsConstructor
private static class Value {
private Kanmusu ship;
private int lv;
@Override
public String toString() {
return this.ship.kai == 1 && this.ship.afterlv > this.lv
? Integer.toString(this.lv)
: this.lv + "." + this.ship.kai;
}
}
}
}
|
package looly.github.hutool;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
/**
*
*
* @author xiaoleilu
*
*/
public class CollectionUtil {
/**
* conjunction
*
* @param <T>
* @param collection
* @param conjunction
* @return
*/
public static <T> String join(Iterable<T> collection, String conjunction) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (T item : collection) {
if (isFirst) {
isFirst = false;
} else {
sb.append(conjunction);
}
sb.append(item);
}
return sb.toString();
}
/**
* conjunction
*
* @param <T>
* @param array
* @param conjunction
* @return
*/
public static <T> String join(T[] array, String conjunction) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (T item : array) {
if (isFirst) {
isFirst = false;
} else {
sb.append(conjunction);
}
sb.append(item);
}
return sb.toString();
}
/**
*
* @param pageNo
* @param numPerPage
* @param comparator
* @param colls
* @return
*/
public static <T> List<T> sortPageAll(int pageNo, int numPerPage, Comparator<T> comparator, Collection<T>... colls) {
final List<T> result = new ArrayList<T>();
for (Collection<T> coll : colls) {
result.addAll(coll);
}
Collections.sort(result, comparator);
if(pageNo <=1 && result.size() <= numPerPage) {
return result;
}
final int[] startEnd = PageUtil.transToStartEnd(pageNo, numPerPage);
return result.subList(startEnd[0], startEnd[1]);
}
/**
*
* @param pageNo
* @param numPerPage
* @param comparator
* @param colls
* @return
*/
public static <T> List<T> sortPageAll2(int pageNo, int numPerPage, Comparator<T> comparator, Collection<T>... colls) {
BoundedPriorityQueue<T> queue = new BoundedPriorityQueue<T>(pageNo * numPerPage);
for (Collection<T> coll : colls) {
queue.addAll(coll);
}
if(pageNo <=1 && queue.size() <= numPerPage) {
return queue.toList();
}
final int[] startEnd = PageUtil.transToStartEnd(pageNo, numPerPage);
return queue.toList().subList(startEnd[0], startEnd[1]);
}
/**
* SetEntry
*
* @param set Set
* @return Set
*/
public static List<Entry<Long, Long>> sortEntrySetToList(Set<Entry<Long, Long>> set) {
List<Entry<Long, Long>> list = new LinkedList<Map.Entry<Long, Long>>(set);
Collections.sort(list, new Comparator<Entry<Long, Long>>(){
@Override
public int compare(Entry<Long, Long> o1, Entry<Long, Long> o2) {
if (o1.getValue() > o2.getValue()) return 1;
if (o1.getValue() < o2.getValue()) return -1;
return 0;
}
});
return list;
}
/**
*
*
* @param <T>
* @param surplusAlaDatas
* @param partSize
* @return null
*/
public static <T> List<T> popPart(Stack<T> surplusAlaDatas, int partSize) {
if (surplusAlaDatas == null || surplusAlaDatas.size() <= 0) return null;
List<T> currentAlaDatas = new ArrayList<T>();
int size = surplusAlaDatas.size();
if (size > partSize) {
for (int i = 0; i < partSize; i++) {
currentAlaDatas.add(surplusAlaDatas.pop());
}
} else {
for (int i = 0; i < size; i++) {
currentAlaDatas.add(surplusAlaDatas.pop());
}
}
return currentAlaDatas;
}
/**
* HashMap
*
* @return HashMap
*/
public static <T, K> HashMap<T, K> newHashMap() {
return new HashMap<T, K>();
}
/**
* HashMap
* @param size 0.75sizesize / 0.75
* @return HashMap
*/
public static <T, K> HashMap<T, K> newHashMap(int size) {
return new HashMap<T, K>((int)(size / 0.75));
}
/**
* HashSet
*
* @return HashSet
*/
public static <T> HashSet<T> newHashSet() {
return new HashSet<T>();
}
/**
* ArrayList
*
* @return ArrayList
*/
public static <T> ArrayList<T> newArrayList() {
return new ArrayList<T>();
}
/**
* <br/>
*
*
* @param buffer
* @param newElement
* @return
*/
public static <T> T[] append(T[] buffer, T newElement) {
T[] t = resize(buffer, buffer.length + 1, newElement.getClass());
t[buffer.length] = newElement;
return t;
}
/**
*
*
* @param buffer
* @param newSize
* @param componentType
* @return
*/
public static <T> T[] resize(T[] buffer, int newSize, Class<?> componentType) {
T[] newArray = newArray(componentType, newSize);
System.arraycopy(buffer, 0, newArray, 0, buffer.length >= newSize ? newSize : buffer.length);
return newArray;
}
/**
*
* @param componentType
* @param newSize
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T[] newArray(Class<?> componentType, int newSize) {
return (T[]) Array.newInstance(componentType, newSize);
}
/**
* <br/>
*
*
* @param buffer
* @param newSize
* @return
*/
public static <T> T[] resize(T[] buffer, int newSize) {
return resize(buffer, newSize, buffer.getClass().getComponentType());
}
/**
* <br>
* null
*
* @param array1 1
* @param array2 2
* @return
*/
public static <T> T[] addAll(T[]... arrays) {
if (arrays.length == 1) {
return arrays[0];
}
int length = 0;
for (T[] array : arrays) {
if(array == null) {
continue;
}
length += array.length;
}
T[] result = newArray(arrays.getClass().getComponentType().getComponentType(), length);
length = 0;
for (T[] array : arrays) {
if(array == null) {
continue;
}
System.arraycopy(array, 0, result, length, array.length);
length += array.length;
}
return result;
}
/**
*
* @param array
* @return
*/
public static <T> T[] clone(T[] array) {
if (array == null) {
return null;
}
return array.clone();
}
/**
* <br>
*
* @param excludedEnd
* @return
*/
public static int[] range(int excludedEnd) {
return range(0, excludedEnd, 1);
}
/**
* <br>
*
* @param includedStart
* @param excludedEnd
* @return
*/
public static int[] range(int includedStart, int excludedEnd) {
return range(includedStart, excludedEnd, 1);
}
/**
* <br>
*
* @param includedStart
* @param excludedEnd
* @param step
* @return
*/
public static int[] range(int includedStart, int excludedEnd, int step) {
if(includedStart > excludedEnd) {
int tmp = includedStart;
includedStart = excludedEnd;
excludedEnd = tmp;
}
if(step <=0) {
step = 1;
}
int length = (excludedEnd - includedStart) / step;
int[] range = new int[length];
for(int i = 0; i < length; i++) {
range[i] = includedStart;
includedStart += step;
}
return range;
}
/**
*
* @param list
* @param start
* @param end
* @return null
*/
public static <T> List<T> sub(List<T> list, int start, int end) {
if(list == null || list.isEmpty()) {
return null;
}
if(start < 0) {
start = 0;
}
if(end < 0) {
end = 0;
}
if(start > end) {
int tmp = start;
start = end;
end = tmp;
}
final int size = list.size();
if(end > size) {
if(start >= size) {
return null;
}
end = size;
}
return list.subList(start, end);
}
/**
*
* @param list
* @param start
* @param end
* @return null
*/
public static <T> List<T> sub(Collection<T> list, int start, int end) {
if(list == null || list.isEmpty()) {
return null;
}
return sub(new ArrayList<T>(list), start, end);
}
/**
*
* @param array
* @return
*/
public static <T> boolean isEmpty(T[] array) {
return array == null || array.length == 0;
}
/**
*
* @param array
* @return
*/
public static <T> boolean isNotEmpty(T[] array) {
return false == isEmpty(array);
}
/**
*
* @param collection
* @return
*/
public static <T> boolean isEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
/**
*
* @param collection
* @return
*/
public static <T> boolean isNotEmpty(Collection<T> collection) {
return false == isEmpty(collection);
}
/**
* Pythonzip()<br>
* <br>
* keys = [a,b,c,d]<br>
* values = [1,2,3,4]<br>
* Map {a=1, b=2, c=3, d=4}<br>
*
* @param keys
* @param values
* @return Map
*/
public static <T, K> Map<T, K> zip(T[] keys, K[] values) {
if(isEmpty(keys) || isEmpty(values)) {
return null;
}
final int size = Math.min(keys.length, values.length);
final Map<T, K> map = new HashMap<T, K>((int)(size / 0.75));
for(int i = 0; i < size; i++) {
map.put(keys[i], values[i]);
}
return map;
}
/**
* Pythonzip()<br>
* <br>
* keys = a,b,c,d<br>
* values = 1,2,3,4<br>
* delimiter = ,
* Map {a=1, b=2, c=3, d=4}<br>
*
* @param keys
* @param values
* @return Map
*/
public static Map<String, String> zip(String keys, String values, String delimiter) {
return zip(StrUtil.split(keys, delimiter), StrUtil.split(values, delimiter));
}
/**
* Pythonzip()<br>
* <br>
* keys = [a,b,c,d]<br>
* values = [1,2,3,4]<br>
* Map {a=1, b=2, c=3, d=4}<br>
*
* @param keys
* @param values
* @return Map
*/
public static <T, K> Map<T, K> zip(Collection<T> keys, Collection<K> values) {
if(isEmpty(keys) || isEmpty(values)) {
return null;
}
final List<T> keyList = new ArrayList<T>(keys);
final List<K> valueList = new ArrayList<K>(values);
final int size = Math.min(keys.size(), values.size());
final Map<T, K> map = new HashMap<T, K>((int)(size / 0.75));
for(int i = 0; i < size; i++) {
map.put(keyList.get(i), valueList.get(i));
}
return map;
}
}
|
package mingzuozhibi.action;
import mingzuozhibi.persist.disc.Disc;
import mingzuozhibi.persist.disc.Disc.DiscType;
import mingzuozhibi.service.amazon.AmazonTaskService;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static mingzuozhibi.action.SakuraController.DISC_COLUMNS_ADMIN_SET;
import static mingzuozhibi.persist.disc.Disc.UpdateType.Amazon;
import static mingzuozhibi.service.amazon.DocumentReader.getNode;
import static mingzuozhibi.service.amazon.DocumentReader.getText;
@RestController
public class DiscController extends BaseController {
@Autowired
private AmazonTaskService service;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Transactional
@PreAuthorize("hasRole('BASIC')")
@GetMapping(value = "/api/discs/search/{asin}", produces = MEDIA_TYPE)
public String search(@PathVariable String asin) {
AtomicReference<Disc> disc = new AtomicReference<>(dao.lookup(Disc.class, "asin", asin));
StringBuilder error = new StringBuilder();
if (disc.get() == null) {
service.createDiscTask(asin, task -> {
if (task.isDone()) {
Node node = getNode(task.getDocument(), "Items", "Item", "ItemAttributes");
String rankText = getText(task.getDocument(), "Items", "Item", "SalesRank");
if (node != null) {
Document itemAttributes = node.getOwnerDocument();
String title = getText(itemAttributes, "Title");
String group = getText(itemAttributes, "ProductGroup");
String release = getText(itemAttributes, "ReleaseDate");
Objects.requireNonNull(title);
Objects.requireNonNull(group);
DiscType type = getType(group, title);
boolean amazon = title.startsWith("Amazon.co.jp");
LocalDate releaseDate;
if (release != null) {
releaseDate = LocalDate.parse(release, formatter);
} else {
releaseDate = LocalDate.now();
}
Disc newDisc = new Disc(asin, title, type, Amazon, amazon, releaseDate);
if (rankText != null) {
newDisc.setThisRank(new Integer(rankText));
}
dao.save(newDisc);
disc.set(newDisc);
} else {
error.append(task.getErrorMessage());
}
}
synchronized (disc) {
disc.notify();
}
});
try {
synchronized (disc) {
TimeUnit.SECONDS.timedWait(disc, 20);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (disc.get() == null) {
if (error.length() == 0) {
return errorMessage("");
} else {
return errorMessage(error.toString());
}
}
JSONArray result = new JSONArray();
result.put(disc.get().toJSON(DISC_COLUMNS_ADMIN_SET));
return objectResult(result);
}
private DiscType getType(String group, String title) {
switch (group) {
case "Music":
return DiscType.Cd;
case "DVD":
if (title.contains("Blu-ray")) {
return DiscType.Bluray;
} else {
return DiscType.Dvd;
}
default:
return DiscType.Other;
}
}
}
|
package mingzuozhibi.action;
import mingzuozhibi.persist.core.AutoLogin;
import mingzuozhibi.persist.core.User;
import mingzuozhibi.support.JsonArg;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController extends BaseController {
@Transactional
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/api/users", produces = MEDIA_TYPE)
public String findAll() {
JSONArray result = new JSONArray();
dao.findAll(User.class).forEach(user -> {
result.put(user.toJSON());
});
return objectResult(result);
}
@Transactional
@PreAuthorize("hasRole('ADMIN')")
@PostMapping(value = "/api/users", produces = MEDIA_TYPE)
public String addOne(
@JsonArg String username,
@JsonArg String password,
@JsonArg(defaults = "true") boolean enabled) {
if (dao.lookup(User.class, "username", username) != null) {
return errorMessage("");
}
User user = new User(username, password, enabled);
dao.save(user);
JSONObject result = user.toJSON();
if (LOGGER.isInfoEnabled()) {
infoRequest("[][={}]", result);
}
return objectResult(result);
}
@Transactional
@PreAuthorize("hasRole('ADMIN')")
@GetMapping(value = "/api/users/{id}", produces = MEDIA_TYPE)
public String getOne(@PathVariable Long id) {
User user = dao.get(User.class, id);
if (user == null) {
if (LOGGER.isWarnEnabled()) {
warnRequest("[][Id][Id={}]", id);
}
return errorMessage("Id");
}
return objectResult(user.toJSON());
}
@Transactional
@PreAuthorize("hasRole('ADMIN')")
@PutMapping(value = "/api/users/{id}", produces = MEDIA_TYPE)
public String setOne(
@PathVariable Long id,
@JsonArg String username,
@JsonArg String password,
@JsonArg boolean enabled) {
User user = dao.get(User.class, id);
if (user == null) {
if (LOGGER.isWarnEnabled()) {
warnRequest("[][Id][Id={}]", id);
}
return errorMessage("Id");
}
if (LOGGER.isInfoEnabled()) {
JSONObject before = user.toJSON();
infoRequest("[][={}]", before);
}
user.setUsername(username);
user.setEnabled(enabled);
if (StringUtils.isNotEmpty(password)) {
user.setPassword(password);
cleanAutoLogin(user);
}
JSONObject result = user.toJSON();
if (LOGGER.isInfoEnabled()) {
infoRequest("[][={}]", result);
}
return objectResult(result);
}
private void cleanAutoLogin(User user) {
List<AutoLogin> autoLogins = dao.findBy(AutoLogin.class, "user", user);
autoLogins.forEach(autoLogin -> {
if (LOGGER.isDebugEnabled()) {
debugRequest("[][][Id={}]", autoLogin.getId());
}
dao.delete(autoLogin);
});
}
}
|
package net.imagej.updater;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.GZIPOutputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import net.imagej.updater.Conflicts.Conflict;
import net.imagej.updater.FileObject.Action;
import net.imagej.updater.FileObject.Status;
import net.imagej.updater.action.InstallOrUpdate;
import net.imagej.updater.action.KeepAsIs;
import net.imagej.updater.action.Remove;
import net.imagej.updater.action.Uninstall;
import net.imagej.updater.action.Upload;
import net.imagej.updater.util.DependencyAnalyzer;
import net.imagej.updater.util.Progress;
import net.imagej.updater.util.UpdateCanceledException;
import net.imagej.updater.util.UpdaterUtil;
import org.scijava.log.LogService;
import org.xml.sax.SAXException;
/**
* This class represents the database of available {@link FileObject}s.
*
* @author Johannes Schindelin
*/
@SuppressWarnings("serial")
public class FilesCollection extends LinkedHashMap<String, FileObject>
implements Iterable<FileObject>
{
public final static String DEFAULT_UPDATE_SITE = "ImageJ";
private File imagejRoot;
public final LogService log;
protected Set<FileObject> ignoredConflicts = new HashSet<FileObject>();
protected List<Conflict> conflicts = new ArrayList<Conflict>();
private Map<String, UpdateSite> updateSites;
private boolean updateSitesChanged = false;
private DependencyAnalyzer dependencyAnalyzer;
public final UpdaterUtil util;
/**
* This constructor takes the imagejRoot primarily for testing purposes.
*
* @param imagejRoot the ImageJ directory
*/
public FilesCollection(final File imagejRoot) {
this(UpdaterUtil.getLogService(), imagejRoot);
}
/**
* This constructor takes the imagejRoot primarily for testing purposes.
*
* @param log the log service
* @param imagejRoot the ImageJ directory
*/
public FilesCollection(final LogService log, final File imagejRoot) {
this.log = log;
this.imagejRoot = imagejRoot;
util = new UpdaterUtil(imagejRoot);
updateSites = new LinkedHashMap<String, UpdateSite>();
addUpdateSite(DEFAULT_UPDATE_SITE, UpdaterUtil.MAIN_URL, null, null,
imagejRoot == null ? 0 : UpdaterUtil.getTimestamp(prefix(UpdaterUtil.XML_COMPRESSED)));
}
public UpdateSite addUpdateSite(final String name, final String url,
final String sshHost, final String uploadDirectory, final long timestamp)
{
final UpdateSite site = new UpdateSite(name, url, sshHost, uploadDirectory,
null, null, timestamp);
site.setActive(true);
return addUpdateSite(site);
}
public UpdateSite addUpdateSite(UpdateSite site) {
addUpdateSite(site.getName(), site);
setUpdateSitesChanged(true);
return site;
}
protected void addUpdateSite(final String name, final UpdateSite updateSite) {
UpdateSite already = updateSites.get(name);
updateSite.rank = already != null ? already.rank : updateSites.size();
updateSites.put(name, updateSite);
}
public void renameUpdateSite(final String oldName, final String newName) {
if (getUpdateSite(newName, true) != null) throw new RuntimeException(
"Update site " + newName + " exists already!");
if (getUpdateSite(oldName, true) == null) throw new RuntimeException(
"Update site " + oldName + " does not exist!");
// handle all files
for (final FileObject file : this)
if (oldName.equals(file.updateSite)) file.updateSite = newName;
// preserve order
final Map<String, UpdateSite> oldMap = updateSites;
updateSites = new LinkedHashMap<String, UpdateSite>();
for (final String name : oldMap.keySet()) {
final UpdateSite site = oldMap.get(name);
if (name.equals(oldName)) site.setName(newName);
addUpdateSite(site.getName(), site);
}
}
public void removeUpdateSite(final String name) {
for (final FileObject file : forUpdateSite(name)) {
file.removeFromUpdateSite(name, this);
}
updateSites.remove(name);
setUpdateSitesChanged(true);
// update rank
int counter = 1;
for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) {
entry.getValue().rank = counter++;
}
}
/** @deprecated use {@link #getUpdateSite(String, boolean)} instead */
@Deprecated
public UpdateSite getUpdateSite(final String name) {
return getUpdateSite(name, false);
}
public UpdateSite getUpdateSite(final String name, final boolean evenDisabled) {
if (name == null) return null;
final UpdateSite site = updateSites.get(name);
return evenDisabled || site == null || site.isActive() ? site : null;
}
/** @deprecated use {@link #getUpdateSiteNames(boolean)} instead */
@Deprecated
public Collection<String> getUpdateSiteNames() {
return getUpdateSiteNames(false);
}
/** Gets the names of known update sites. */
public Collection<String> getUpdateSiteNames(final boolean evenDisabled) {
if (evenDisabled) return updateSites.keySet();
final List<String> result = new ArrayList<String>();
final Iterator<java.util.Map.Entry<String, UpdateSite>> it = updateSites.entrySet().iterator();
while (it.hasNext()) {
java.util.Map.Entry<String, UpdateSite> entry = it.next();
if (entry.getValue().isActive()) result.add(entry.getKey());
}
return result;
}
/** Gets the list of known update sites. */
public Collection<UpdateSite> getUpdateSites(final boolean evenDisabled) {
if (evenDisabled) return updateSites.values();
final List<UpdateSite> result = new ArrayList<UpdateSite>();
for (final UpdateSite site : updateSites.values()) {
if (site.isActive()) result.add(site);
}
return result;
}
public Collection<String> getSiteNamesToUpload() {
final Collection<String> set = new HashSet<String>();
for (final FileObject file : toUpload(true))
set.add(file.updateSite);
for (final FileObject file : toRemove())
set.add(file.updateSite);
// keep the update sites' order
final List<String> result = new ArrayList<String>();
for (final String name : getUpdateSiteNames(false))
if (set.contains(name)) result.add(name);
if (result.size() != set.size()) throw new RuntimeException(
"Unknown update site in " + set.toString() + " (known: " +
result.toString() + ")");
return result;
}
public boolean hasUploadableSites() {
for (final UpdateSite site : updateSites.values())
if (site.isActive() && site.isUploadable()) return true;
return false;
}
public boolean hasUpdateSitesChanges() {
return updateSitesChanged;
}
public void setUpdateSitesChanged(boolean updateSitesChanged) {
this.updateSitesChanged = updateSitesChanged;
}
/**
* Deactivates the given update site.
*
* @param site the site to deactivate
* @return the number of files marked for update/install/uninstall
*/
public int deactivateUpdateSite(final UpdateSite site) {
if (!site.isActive()) return 0;
final List<FileObject> list = new ArrayList<FileObject>();
final String updateSite = site.getName();
for (final FileObject file : forUpdateSite(updateSite)) {
list.add(file);
}
for (final FileObject file : list) {
file.removeFromUpdateSite(updateSite, this);
}
site.setActive(false);
return list.size();
}
/**
* Activate the given update site.
*
* @param updateSite the update site to activate
* @param progress the object to display the progress
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public void activateUpdateSite(final UpdateSite updateSite, final Progress progress)
throws ParserConfigurationException, IOException, SAXException {
if (updateSite.isActive()) return;
updateSite.setActive(true);
reReadUpdateSite(updateSite.getName(), progress);
markForUpdate(updateSite.getName(), false);
}
private void markForUpdate(final String updateSite, final boolean evenForcedUpdates) {
for (final FileObject file : forUpdateSite(updateSite)) {
if ((file.isUpdateable(evenForcedUpdates) || file.getStatus()
.isValid(Action.INSTALL))
&& file.isUpdateablePlatform(this)) {
file.setFirstValidAction(this, Action.UPDATE,
Action.UNINSTALL, Action.INSTALL);
}
}
}
public void reReadUpdateSite(final String name, final Progress progress) throws ParserConfigurationException, IOException, SAXException {
new XMLFileReader(this).read(name);
final List<String> filesFromSite = new ArrayList<String>();
for (final FileObject file : forUpdateSite(name))
filesFromSite.add(file.localFilename != null ? file.localFilename : file.filename);
final Checksummer checksummer =
new Checksummer(this, progress);
checksummer.updateFromLocal(filesFromSite);
}
public String protocolsMissingUploaders(final UploaderService uploaderService, final Progress progress) {
final Map<String, Set<String>> map = new LinkedHashMap<String, Set<String>>();
for (final Map.Entry<String, UpdateSite> entry : updateSites.entrySet()) {
final UpdateSite site = entry.getValue();
if (!site.isUploadable()) continue;
final String protocol = site.getUploadProtocol();
try {
uploaderService.installUploader(protocol, this, progress);
} catch (IllegalArgumentException e) {
Set<String> set = map.get(protocol);
if (set == null) {
set = new LinkedHashSet<String>();
map.put(protocol, set);
}
set.add(entry.getKey());
}
}
if (map.size() == 0) return null;
final StringBuilder builder = new StringBuilder();
builder.append(prefixUpdate("").isDirectory() ? "Uploads via these protocols require a restart" : "Missing uploaders:\n");
for (final Map.Entry<String, Set<String>> entry : map.entrySet()) {
final String list = Arrays.toString(entry.getValue().toArray());
builder.append("'").append(entry.getKey()).append("': ").append(list).append("\n");
}
return builder.toString();
}
public Set<GroupAction> getValidActions() {
final Set<GroupAction> actions = new LinkedHashSet<GroupAction>();
actions.add(new KeepAsIs());
boolean hasChanges = hasChanges(), hasUploadOrRemove = hasUploadOrRemove();
if (!hasUploadOrRemove) {
actions.add(new InstallOrUpdate());
}
if (hasUploadOrRemove || !hasChanges) {
final Collection<String> siteNames = getSiteNamesToUpload();
final Map<String, UpdateSite> updateSites;
if (siteNames.size() == 0) updateSites = this.updateSites;
else {
updateSites = new LinkedHashMap<String, UpdateSite>();
for (final String name : siteNames) {
updateSites.put(name, getUpdateSite(name, true));
}
}
for (final UpdateSite updateSite : getUpdateSites(false)) {
if (updateSite.isUploadable()) {
final String name = updateSite.getName();
actions.add(new Upload(name));
actions.add(new Remove(name));
}
}
}
if (!hasUploadOrRemove) {
actions.add(new Uninstall());
}
return actions;
}
public Set<GroupAction> getValidActions(final Iterable<FileObject> selected) {
final Set<GroupAction> actions = getValidActions();
for (final Iterator<GroupAction> iter = actions.iterator(); iter.hasNext(); ) {
final GroupAction action = iter.next();
for (final FileObject file : selected) {
if (!action.isValid(this, file)) {
iter.remove();
break;
}
}
}
return actions;
}
@Deprecated
public Action[] getActions(final FileObject file) {
return file.isUploadable(this, false) ? file.getStatus().getDeveloperActions()
: file.getStatus().getActions();
}
@Deprecated
public Action[] getActions(final Iterable<FileObject> files) {
List<Action> result = null;
for (final FileObject file : files) {
final Action[] actions = getActions(file);
if (result == null) {
result = new ArrayList<Action>();
for (final Action action : actions)
result.add(action);
}
else {
final Set<Action> set = new TreeSet<Action>();
for (final Action action : actions)
set.add(action);
final Iterator<Action> iter = result.iterator();
while (iter.hasNext())
if (!set.contains(iter.next())) iter.remove();
}
}
if (result == null) {
return new Action[0];
}
return result.toArray(new Action[result.size()]);
}
public void read() throws IOException, ParserConfigurationException,
SAXException
{
read(prefix(UpdaterUtil.XML_COMPRESSED));
}
public void read(final File file) throws IOException,
ParserConfigurationException, SAXException
{
read(new FileInputStream(file));
}
public void read(final FileInputStream in) throws IOException,
ParserConfigurationException, SAXException
{
new XMLFileReader(this).read(in);
in.close();
}
public void write() throws IOException, SAXException,
TransformerConfigurationException
{
final File out = prefix(UpdaterUtil.XML_COMPRESSED);
final File tmp = prefix(UpdaterUtil.XML_COMPRESSED + ".tmp");
new XMLFileWriter(this).write(new GZIPOutputStream(
new FileOutputStream(tmp)), true);
if (out.exists() && !out.delete())
out.renameTo(prefix(UpdaterUtil.XML_COMPRESSED + ".backup"));
tmp.renameTo(out);
setUpdateSitesChanged(false);
}
public interface Filter {
boolean matches(FileObject file);
}
public FilesCollection clone(final Iterable<FileObject> iterable) {
final FilesCollection result = new FilesCollection(imagejRoot);
for (final FileObject file : iterable)
result.add(file);
for (final String name : updateSites.keySet())
result.updateSites.put(name, (UpdateSite) updateSites.get(name).clone());
return result;
}
public Iterable<FileObject> toUploadOrRemove() {
return filter(or(is(Action.UPLOAD), is(Action.REMOVE)));
}
public Iterable<FileObject> toUpload() {
return toUpload(false);
}
public Iterable<FileObject> toUpload(final boolean includeMetadataChanges) {
if (!includeMetadataChanges) return filter(is(Action.UPLOAD));
return filter(or(is(Action.UPLOAD), new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.metadataChanged;
}
}));
}
public Iterable<FileObject> toUpload(final String updateSite) {
return filter(and(is(Action.UPLOAD), isUpdateSite(updateSite)));
}
public Iterable<FileObject> toUninstall() {
return filter(is(Action.UNINSTALL));
}
public Iterable<FileObject> toRemove() {
return filter(is(Action.REMOVE));
}
public Iterable<FileObject> toUpdate() {
return filter(is(Action.UPDATE));
}
public Iterable<FileObject> upToDate() {
return filter(is(Action.INSTALLED));
}
public Iterable<FileObject> toInstall() {
return filter(is(Action.INSTALL));
}
public Iterable<FileObject> toInstallOrUpdate() {
return filter(oneOf(Action.INSTALL, Action.UPDATE));
}
public Iterable<FileObject> notHidden() {
return filter(and(not(is(Status.OBSOLETE_UNINSTALLED)), doesPlatformMatch()));
}
public Iterable<FileObject> uninstalled() {
return filter(is(Status.NOT_INSTALLED));
}
public Iterable<FileObject> installed() {
return filter(not(oneOf(Status.LOCAL_ONLY,
Status.NOT_INSTALLED)));
}
public Iterable<FileObject> locallyModified() {
return filter(oneOf(Status.MODIFIED,
Status.OBSOLETE_MODIFIED));
}
public Iterable<FileObject> forUpdateSite(final String name) {
return forUpdateSite(name, false);
}
public Iterable<FileObject> forUpdateSite(final String name, boolean includeObsoletes) {
Filter filter = and(doesPlatformMatch(), isUpdateSite(name));
if (!includeObsoletes) {
filter = and(not(is(Status.OBSOLETE_UNINSTALLED)), filter);
return filter(filter);
}
// make sure that overridden records are kept
List<FileObject> result = new ArrayList<FileObject>();
for (FileObject file : this) {
if (filter.matches(file))
result.add(file);
else {
FileObject overridden = file.overriddenUpdateSites.get(name);
if (overridden != null)
result.add(overridden);
}
}
return result;
}
public Iterable<FileObject> managedFiles() {
return filter(not(is(Status.LOCAL_ONLY)));
}
public Iterable<FileObject> localOnly() {
return filter(is(Status.LOCAL_ONLY));
}
public Iterable<FileObject> shownByDefault() {
/*
* Let's not show the NOT_INSTALLED ones, as the user chose not
* to have them.
*/
final Status[] oneOf =
{ Status.UPDATEABLE, Status.NEW, Status.OBSOLETE,
Status.OBSOLETE_MODIFIED };
return filter(or(oneOf(oneOf), oneOf(Action.INSTALL, Action.UPDATE, Action.UNINSTALL)));
}
public Iterable<FileObject> uploadable() {
return uploadable(false);
}
/**
* Gets the list of uploadable files.
*
* @param assumeModified true if we want the potentially uploadable files if
* they (or their metadata) were to be changed.
* @return the list of uploadable files
*/
public Iterable<FileObject> uploadable(final boolean assumeModified) {
return filter(new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.isUploadable(FilesCollection.this, assumeModified);
}
});
}
public Iterable<FileObject> changes() {
return filter(new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.getAction() != file.getStatus().getNoAction();
}
});
}
public static class FilteredIterator implements Iterator<FileObject> {
Filter filter;
boolean opposite;
Iterator<FileObject> iterator;
FileObject next;
FilteredIterator(final Filter filter, final Iterable<FileObject> files) {
this.filter = filter;
iterator = files.iterator();
findNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public FileObject next() {
final FileObject file = next;
findNext();
return file;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
protected void findNext() {
while (iterator.hasNext()) {
next = iterator.next();
if (filter.matches(next)) return;
}
next = null;
}
}
public static Iterable<FileObject> filter(final Filter filter,
final Iterable<FileObject> files)
{
return new Iterable<FileObject>() {
@Override
public Iterator<FileObject> iterator() {
return new FilteredIterator(filter, files);
}
};
}
public static Iterable<FileObject> filter(final String search,
final Iterable<FileObject> files)
{
final String keyword = search.trim().toLowerCase();
return filter(new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.getFilename().trim().toLowerCase().indexOf(keyword) >= 0;
}
}, files);
}
public Filter yes() {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return true;
}
};
}
public Filter doesPlatformMatch() {
// If we're a developer or no platform was specified, return yes
if (hasUploadableSites()) return yes();
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.isUpdateablePlatform(FilesCollection.this);
}
};
}
public Filter is(final Action action) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.getAction() == action;
}
};
}
public Filter isNoAction() {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.getAction() == file.getStatus().getNoAction();
}
};
}
public Filter oneOf(final Action... actions) {
final Set<Action> oneOf = new HashSet<Action>();
for (final Action action : actions)
oneOf.add(action);
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return oneOf.contains(file.getAction());
}
};
}
public Filter is(final Status status) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.getStatus() == status;
}
};
}
public Filter hasMetadataChanges() {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.metadataChanged;
}
};
}
public Filter isUpdateSite(final String updateSite) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.updateSite != null && // is null for local-only files
file.updateSite.equals(updateSite);
}
};
}
public Filter oneOf(final Status... states) {
final Set<Status> oneOf = new HashSet<Status>();
for (final Status status : states)
oneOf.add(status);
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return oneOf.contains(file.getStatus());
}
};
}
public Filter startsWith(final String prefix) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.filename.startsWith(prefix);
}
};
}
public Filter startsWith(final String... prefixes) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
for (final String prefix : prefixes)
if (file.filename.startsWith(prefix)) return true;
return false;
}
};
}
public Filter endsWith(final String suffix) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.filename.endsWith(suffix);
}
};
}
public Filter not(final Filter filter) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return !filter.matches(file);
}
};
}
public Filter or(final Filter a, final Filter b) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return a.matches(file) || b.matches(file);
}
};
}
public Filter and(final Filter a, final Filter b) {
return new Filter() {
@Override
public boolean matches(final FileObject file) {
return a.matches(file) && b.matches(file);
}
};
}
public Iterable<FileObject> filter(final Filter filter) {
return filter(filter, this);
}
public FileObject
getFileFromDigest(final String filename, final String digest)
{
for (final FileObject file : this)
if (file.getFilename().equals(filename) &&
file.getChecksum().equals(digest)) return file;
return null;
}
public Iterable<String> analyzeDependencies(final FileObject file) {
try {
if (dependencyAnalyzer == null) dependencyAnalyzer =
new DependencyAnalyzer(imagejRoot);
return dependencyAnalyzer.getDependencies(imagejRoot, file);
}
catch (final IOException e) {
log.error(e);
return null;
}
}
public void updateDependencies(final FileObject file) {
final Iterable<String> dependencies = analyzeDependencies(file);
if (dependencies == null) return;
for (final String dependency : dependencies)
file.addDependency(dependency, prefix(dependency));
}
public boolean has(final Filter filter) {
for (final FileObject file : this)
if (filter.matches(file)) return true;
return false;
}
public boolean hasChanges() {
return changes().iterator().hasNext();
}
public boolean hasUploadOrRemove() {
return has(oneOf(Action.UPLOAD, Action.REMOVE));
}
public boolean hasForcableUpdates() {
for (final FileObject file : updateable(true))
if (!file.isUpdateable(false)) return true;
return false;
}
public Iterable<FileObject> updateable(final boolean evenForcedOnes) {
return filter(new Filter() {
@Override
public boolean matches(final FileObject file) {
return file.isUpdateable(evenForcedOnes) && file.isUpdateablePlatform(FilesCollection.this);
}
});
}
public void markForUpdate(final boolean evenForcedUpdates) {
for (final FileObject file : updateable(evenForcedUpdates)) {
file.setFirstValidAction(this, Action.UPDATE,
Action.UNINSTALL, Action.INSTALL);
}
}
public String getURL(final FileObject file) {
final String siteName = file.updateSite;
assert (siteName != null && !siteName.equals(""));
final UpdateSite site = getUpdateSite(siteName, false);
if (site == null) return null;
return site.getURL() + file.filename.replace(" ", "%20") + "-" +
file.getTimestamp();
}
public static class DependencyMap extends
HashMap<FileObject, FilesCollection>
{
// returns true when the map did not have the dependency before
public boolean
add(final FileObject dependency, final FileObject dependencee)
{
if (containsKey(dependency)) {
get(dependency).add(dependencee);
return false;
}
final FilesCollection list = new FilesCollection(null);
list.add(dependencee);
put(dependency, list);
return true;
}
}
void addDependencies(final FileObject file, final DependencyMap map,
final boolean overriding)
{
for (final Dependency dependency : file.getDependencies()) {
final FileObject other = get(dependency.filename);
if (other == null || overriding != dependency.overrides ||
!other.isUpdateablePlatform(this)) continue;
if (other.isObsolete() && other.willNotBeInstalled()) {
log.warn("Ignoring obsolete dependency " + dependency.filename
+ " of " + file.filename);
continue;
}
if (dependency.overrides) {
if (other.willNotBeInstalled()) continue;
}
else if (other.willBeUpToDate()) continue;
if (!map.add(other, file)) continue;
// overriding dependencies are not recursive
if (!overriding) addDependencies(other, map, overriding);
}
}
/**
* Gets a map listing all the dependencees of files to be installed or
* updated.
*
* @param overridingOnes
* whether to include files that override a particular dependency
* @return the map
*/
public DependencyMap getDependencies(final boolean overridingOnes) {
return getDependencies(toInstallOrUpdate(), overridingOnes);
}
/**
* Gets a map listing all the dependencees of the specified files.
*
* @param files
* the dependencies
* @param overridingOnes
* whether to include files that override a particular dependency
* @return the map
*/
public DependencyMap getDependencies(final Iterable<FileObject> files, final boolean overridingOnes) {
final DependencyMap result = new DependencyMap();
for (final FileObject file : files)
addDependencies(file, result, overridingOnes);
return result;
}
public void sort() {
// first letters in this order: 'C', 'I', 'f', 'p', 'j', 's', 'i', 'm', 'l,
final ArrayList<FileObject> files = new ArrayList<FileObject>();
for (final FileObject file : this) {
files.add(file);
}
Collections.sort(files, new Comparator<FileObject>() {
@Override
public int compare(final FileObject a, final FileObject b) {
final int result = firstChar(a) - firstChar(b);
return result != 0 ? result : a.filename.compareTo(b.filename);
}
int firstChar(final FileObject file) {
final char c = file.filename.charAt(0);
final int index = "CIfpjsim".indexOf(c);
return index < 0 ? 0x200 + c : index;
}
});
this.clear();
for (final FileObject file : files) {
super.put(file.filename, file);
}
}
String checkForCircularDependency(final FileObject file,
final Set<FileObject> seen, final String updateSite)
{
if (seen.contains(file)) return "";
final String result =
checkForCircularDependency(file, seen, new HashSet<FileObject>(), updateSite);
if (result == null) return "";
// Display only the circular dependency
final int last = result.lastIndexOf(' ');
final int off = result.lastIndexOf(result.substring(last), last - 1);
return "Circular dependency detected: " + result.substring(off + 1) + "\n";
}
String checkForCircularDependency(final FileObject file,
final Set<FileObject> seen, final Set<FileObject> chain, final String updateSite)
{
if (seen.contains(file)) return null;
for (final String dependency : file.dependencies.keySet()) {
final FileObject dep = get(dependency);
if (dep == null) continue;
if (updateSite != null && !updateSite.equals(dep.updateSite)) continue;
if (chain.contains(dep)) return " " + dependency;
chain.add(dep);
final String result = checkForCircularDependency(dep, seen, chain, updateSite);
seen.add(dep);
if (result != null) return " " + dependency + " ->" + result;
chain.remove(dep);
}
return null;
}
/* returns null if consistent, error string when not */
public String checkConsistency() {
final Collection<String> uploadSiteNames = getSiteNamesToUpload();
final String uploadSiteName = uploadSiteNames.isEmpty() ? null :
uploadSiteNames.iterator().next();
final StringBuilder result = new StringBuilder();
final Set<FileObject> circularChecked = new HashSet<FileObject>();
for (final FileObject file : this) {
if (uploadSiteName != null && !uploadSiteName.equals(file.updateSite)) {
continue;
}
result.append(checkForCircularDependency(file, circularChecked, uploadSiteName));
// only non-obsolete components can have dependencies
final Set<String> deps = file.dependencies.keySet();
if (deps.size() > 0 && file.isObsolete() && file.getAction() != Action.UPLOAD) {
result.append("Obsolete file " + file + " has dependencies: " + UpdaterUtil.join(", ", deps) + "!\n");
}
for (final String dependency : deps) {
final FileObject dep = get(dependency);
if (dep == null || dep.current == null) result.append("The file " +
file + " has the obsolete/local-only " + "dependency " + dependency +
"!\n");
}
}
return result.length() > 0 ? result.toString() : null;
}
public File prefix(final FileObject file) {
return prefix(file.getFilename());
}
public File prefix(final String path) {
final File file = new File(path);
if (file.isAbsolute()) return file;
assert (imagejRoot != null);
return new File(imagejRoot, path);
}
public File prefixUpdate(final String path) {
return prefix("update/" + path);
}
public boolean fileExists(final String filename) {
return prefix(filename).exists();
}
@Override
public String toString() {
return UpdaterUtil.join(", ", this);
}
@Deprecated
public FileObject get(final int index) {
throw new UnsupportedOperationException();
}
public void add(final FileObject file) {
super.put(file.getFilename(true), file);
}
@Override
public FileObject get(final Object filename) {
return super.get(FileObject.getFilename((String)filename, true));
}
@Override
public FileObject put(final String key, final FileObject file) {
throw new UnsupportedOperationException();
}
@Override
public FileObject remove(final Object file) {
if (file instanceof FileObject) super.remove(((FileObject) file).getFilename(true));
if (file instanceof String) return super.remove(FileObject.getFilename((String)file, true));
return null;
}
@Override
public Iterator<FileObject> iterator() {
final Iterator<Map.Entry<String, FileObject>> iterator = entrySet().iterator();
return new Iterator<FileObject>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public FileObject next() {
return iterator.next().getValue();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public String downloadIndexAndChecksum(final Progress progress) throws ParserConfigurationException, SAXException {
try {
read();
}
catch (final FileNotFoundException e) {
if (prefix("plugins/Fiji_Updater.jar").exists()) {
// make sure that the Fiji update site is enabled
UpdateSite fiji = getUpdateSite("Fiji", true);
if (fiji == null) {
addUpdateSite("Fiji", "http://fiji.sc/update/", null, null, 0);
}
}
}
catch (final IOException e) { /* ignore */ }
// clear the files
clear();
final XMLFileDownloader downloader = new XMLFileDownloader(this);
downloader.addProgress(progress);
try {
downloader.start(false);
} catch (final UpdateCanceledException e) {
downloader.done();
throw e;
}
new Checksummer(this, progress).updateFromLocal();
// When upstream fixed dependencies, heed them
for (final FileObject file : upToDate()) {
for (final FileObject dependency : file.getFileDependencies(this, false)) {
if (dependency.getAction() == Action.NOT_INSTALLED && dependency.isUpdateablePlatform(this)) {
dependency.setAction(this, Action.INSTALL);
}
}
}
return downloader.getWarnings();
}
public List<Conflict> getConflicts() {
return conflicts;
}
/**
* Utility method for Fiji's Bug Submitter
*
* @return the list of files known to the Updater, with versions, as a String
*/
public static String getInstalledVersions(final File ijDirectory, final Progress progress) {
final StringBuilder sb = new StringBuilder();
final FilesCollection files = new FilesCollection(ijDirectory);
try {
files.read();
} catch (Exception e) {
sb.append("Error while reading db.xml.gz: ").append(e.getMessage()).append("\n\n");
}
final Checksummer checksummer = new Checksummer(files, progress);
try {
checksummer.updateFromLocal();
} catch (UpdateCanceledException t) {
return null;
}
final Map<String, FileObject.Version> checksums = checksummer.getCachedChecksums();
sb.append("Activated update sites:\n");
for (final UpdateSite site : files.getUpdateSites(false)) {
sb.append(site.getName()).append(": ").append(site.getURL())
.append(" (last check:").append(site.getTimestamp())
.append(")\n");
}
boolean notUpToDateShown = false;
for (final Map.Entry<String, FileObject.Version> entry : checksums.entrySet()) {
String file = entry.getKey();
if (file.startsWith(":") && file.length() == 41) continue;
final FileObject fileObject = files.get(file);
if (fileObject != null && fileObject.getStatus() == Status.INSTALLED) continue;
if (!notUpToDateShown) {
sb.append("\nFiles not up-to-date:\n");
notUpToDateShown = true;
}
final FileObject.Version version = entry.getValue();
String checksum = version.checksum;
if (version.checksum != null && version.checksum.length() > 8) {
final StringBuilder rebuild = new StringBuilder();
for (final String element : checksum.split(":")) {
if (rebuild.length() > 0) rebuild.append(":");
if (element == null || element.length() <= 8) rebuild.append(element);
else rebuild.append(element.substring(0, 8));
}
checksum = rebuild.toString();
}
sb.append(" ").append(checksum).append(" ");
if (fileObject != null) sb.append("(").append(fileObject.getStatus()).append(") ");
sb.append(version.timestamp).append(" ");
sb.append(file).append("\n");
}
return sb.toString();
}
public Collection<String> getProtocols(Iterable<FileObject> selected) {
final Set<String> protocols = new LinkedHashSet<String>();
for (final FileObject file : selected) {
final UpdateSite site = getUpdateSite(file.updateSite, false);
if (site != null) {
if (site.getHost() == null)
protocols.add("unknown(" + file.filename + ")");
else
protocols.add(site.getUploadProtocol());
}
}
return protocols;
}
}
|
package org.hisp.dhis.reservedvalue;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.textpattern.TextPattern;
import org.hisp.dhis.textpattern.TextPatternGenerationException;
import org.hisp.dhis.textpattern.TextPatternMethod;
import org.hisp.dhis.textpattern.TextPatternMethodUtils;
import org.hisp.dhis.textpattern.TextPatternSegment;
import org.hisp.dhis.textpattern.TextPatternService;
import org.hisp.dhis.textpattern.TextPatternValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @author Stian Sandvold
*/
public class DefaultReservedValueService
implements ReservedValueService
{
private static final long GENERATION_TIMEOUT = (1000 * 30); // 30 sec
@Autowired
private TextPatternService textPatternService;
@Autowired
private ReservedValueStore reservedValueStore;
@Autowired
private SequentialNumberCounterStore sequentialNumberCounterStore;
private final Log log = LogFactory.getLog( DefaultReservedValueService.class );
@Override
public List<ReservedValue> reserve( TextPattern textPattern, int numberOfReservations, Map<String, String> values, Date expires )
throws ReserveValueException, TextPatternGenerationException
{
long startTime = System.currentTimeMillis();
int attemptsLeft = 10;
List<ReservedValue> resultList = new ArrayList<>();
TextPatternSegment generatedSegment = getGeneratedSegment( textPattern );
String key = textPatternService.resolvePattern( textPattern, values );
// Used for searching value tables
String valueKey = (generatedSegment != null ?
key.replaceAll( Pattern.quote( generatedSegment.getRawSegment() ), "%" ) :
key);
ReservedValue reservedValue = new ReservedValue( textPattern.getOwnerObject().name(), textPattern.getOwnerUid(),
key,
valueKey,
expires );
if ( !hasEnoughValuesLeft( reservedValue,
TextPatternValidationUtils.getTotalValuesPotential( generatedSegment ),
numberOfReservations ) )
{
throw new ReserveValueException( "Not enough values left to reserve " + numberOfReservations + " values." );
}
if ( generatedSegment == null && numberOfReservations == 1 )
{
reservedValue.setValue( key );
return reservedValueStore.reserveValues( reservedValue, Lists.newArrayList( key ) );
}
List<String> usedGeneratedValues = new ArrayList<>();
int numberOfValuesLeftToGenerate = numberOfReservations;
try
{
while ( attemptsLeft-- > 0 && numberOfValuesLeftToGenerate > 0 )
{
if ( System.currentTimeMillis() - startTime >= GENERATION_TIMEOUT )
{
throw new TimeoutException( "Generation and reservation of values took too long" );
}
List<String> resolvedPatterns = new ArrayList<>();
List<String> generatedValues = new ArrayList<>();
int maxGenerateAttempts = 10;
while ( generatedValues.size() < numberOfValuesLeftToGenerate && maxGenerateAttempts
{
generatedValues.addAll( generateValues( textPattern, key, numberOfReservations - resultList.size() ) );
generatedValues.removeAll( usedGeneratedValues );
}
usedGeneratedValues.addAll( generatedValues );
// Get a list of resolved patterns.
for ( int i = 0; i < numberOfReservations - resultList.size(); i++ )
{
resolvedPatterns.add( textPatternService.resolvePattern( textPattern,
ImmutableMap.<String, String>builder()
.putAll( values )
.put( generatedSegment.getMethod().name(), generatedValues.get( i ) )
.build() ) );
}
resultList.addAll( reservedValueStore.reserveValues( reservedValue, resolvedPatterns ) );
numberOfValuesLeftToGenerate = numberOfReservations - resultList.size();
}
}
catch ( TimeoutException ex )
{
log.warn( String.format(
"Generation and reservation of values for %s wih uid %s timed out. %s values was reserved. You might be running low on available values",
textPattern.getOwnerObject().name(), textPattern.getOwnerUid(), resultList.size() ) );
}
return resultList;
}
@Override
public boolean useReservedValue( TextPattern textPattern, String value )
{
return reservedValueStore.useReservedValue( textPattern.getOwnerUid(), value );
}
@Override
public boolean isReserved( TextPattern textPattern, String value )
{
return reservedValueStore.isReserved( textPattern.getOwnerObject().name(), textPattern.getOwnerUid(), value );
}
// Helper methods
private TextPatternSegment getGeneratedSegment( TextPattern textPattern )
{
return textPattern.getSegments()
.stream()
.filter( ( tp ) -> tp.getMethod().isGenerated() )
.findFirst()
.orElse( null );
}
private List<String> generateValues( TextPattern textPattern, String key, int numberOfValues )
{
List<String> generatedValues = new ArrayList<>();
TextPatternSegment segment = getGeneratedSegment( textPattern );
if ( segment.getMethod().equals( TextPatternMethod.SEQUENTIAL ) )
{
generatedValues.addAll( sequentialNumberCounterStore
.getNextValues( textPattern.getOwnerUid(), key, numberOfValues )
.stream()
.map( ( n ) -> String.format( "%0" + segment.getParameter().length() + "d", n ) )
.collect( Collectors.toList() ) );
}
else if ( segment.getMethod().equals( TextPatternMethod.RANDOM ) )
{
for ( int i = 0; i < numberOfValues; i++ )
{
generatedValues.add( TextPatternMethodUtils.generateRandom( new Random(), segment.getParameter() ) );
}
}
return generatedValues;
}
private boolean hasEnoughValuesLeft( ReservedValue reservedValue, long totalValues, int valuesRequired )
{
int used = reservedValueStore.getNumberOfUsedValues( reservedValue );
return totalValues >= valuesRequired + used;
}
}
|
package org.eclipse.birt.report.engine.layout.pdf;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.css.engine.StyleConstants;
import org.eclipse.birt.report.engine.emitter.IContentEmitter;
import org.eclipse.birt.report.engine.executor.IReportItemExecutor;
import org.eclipse.birt.report.engine.layout.IBlockStackingLayoutManager;
import org.eclipse.birt.report.engine.layout.content.ItemExecutorWrapper;
import org.eclipse.birt.report.engine.layout.content.LineStackingExecutor;
public class PDFImageBlockContainerLM extends PDFBlockContainerLM
implements
IBlockStackingLayoutManager
{
public PDFImageBlockContainerLM( PDFLayoutEngineContext context,
PDFStackingLM parent, IContent content, IContentEmitter emitter,
IReportItemExecutor executor )
{
super( context, parent, content, emitter, executor );
child = new PDFLineAreaLM( context, this, emitter,
new LineStackingExecutor( new ItemExecutorWrapper( executor,
content ), executor ) );
}
protected boolean traverseChildren( )
{
return traverseSingleChild( );
}
protected void closeLayout( )
{
assert ( parent != null );
IStyle areaStyle = root.getStyle( );
// set dimension property for root TODO suppport user defined height
root
.setHeight( getCurrentBP( )
+ getOffsetY( )
+ getDimensionValue( areaStyle
.getProperty( StyleConstants.STYLE_PADDING_BOTTOM ) )
+ getDimensionValue( areaStyle
.getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ) );
}
protected void createRoot( )
{
super.createRoot( );
IStyle style = root.getStyle( );
removeBoxProperty( root.getStyle( ) );
style.setProperty( StyleConstants.STYLE_BACKGROUND_IMAGE, IStyle.NONE_VALUE );
style.setProperty( StyleConstants.STYLE_BACKGROUND_COLOR, IStyle.AUTO_VALUE );
}
protected void closeExecutor( )
{
}
}
|
package io.spine.gradle.compiler.validate;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import io.spine.base.ConversionException;
import io.spine.base.Types;
import io.spine.gradle.compiler.message.MessageTypeCache;
import io.spine.gradle.compiler.message.fieldtype.FieldType;
import io.spine.gradle.compiler.message.fieldtype.ProtoScalarType;
import io.spine.validate.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.lang.model.element.Modifier;
import java.util.Collection;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type.TYPE_ENUM;
import static io.spine.gradle.compiler.util.JavaCode.toJavaFieldName;
import static io.spine.gradle.compiler.validate.ClassNames.getClassName;
import static io.spine.gradle.compiler.validate.ClassNames.getParameterClassName;
import static io.spine.gradle.compiler.validate.MethodConstructors.clearPrefix;
import static io.spine.gradle.compiler.validate.MethodConstructors.clearProperty;
import static io.spine.gradle.compiler.validate.MethodConstructors.createConvertSingularValue;
import static io.spine.gradle.compiler.validate.MethodConstructors.createDescriptorStatement;
import static io.spine.gradle.compiler.validate.MethodConstructors.createValidateStatement;
import static io.spine.gradle.compiler.validate.MethodConstructors.getMessageBuilder;
import static io.spine.gradle.compiler.validate.MethodConstructors.rawSuffix;
import static io.spine.gradle.compiler.validate.MethodConstructors.removePrefix;
import static io.spine.gradle.compiler.validate.MethodConstructors.returnThis;
import static java.lang.String.format;
/**
* A method constructor of the {@code MethodSpec} objects based on the Protobuf message declaration.
*
* <p>Constructs the {@code MethodSpec} objects for the repeated fields.
*
* @author Illia Shepilov
*/
@SuppressWarnings("DuplicateStringLiteralInspection")
// It cannot be used as the constant across the project.
// Although it has the equivalent literal they have the different meaning.
class RepeatedFieldMethodConstructor implements MethodConstructor {
private static final String VALUE = "value";
private static final String INDEX = "index";
private static final String ADD_PREFIX = "add";
private static final String SET_PREFIX = "set";
private static final String ADD_RAW_PREFIX = "addRaw";
private static final String SET_RAW_PREFIX = "setRaw";
private static final String CONVERTED_VALUE = "convertedValue";
private final int fieldIndex;
private final FieldType fieldType;
private final String javaFieldName;
private final String methodNamePart;
private final ClassName builderClassName;
private final ClassName listElementClassName;
private final ClassName builderGenericClassName;
private final FieldDescriptorProto fieldDescriptor;
private final boolean isScalarOrEnum;
/**
* Constructs the {@code RepeatedFieldMethodConstructor}.
*
* @param builder the {@code RepeatedFieldMethodConstructorBuilder} instance
*/
@SuppressWarnings("ConstantConditions")
// The fields are checked in the {@code #build()} method
// of the {@code RepeatedFieldMethodsConstructorBuilder} class.
private RepeatedFieldMethodConstructor(RepeatedFieldMethodsConstructorBuilder builder) {
super();
this.fieldType = builder.getFieldType();
this.fieldIndex = builder.getFieldIndex();
this.fieldDescriptor = builder.getFieldDescriptor();
this.builderGenericClassName = builder.getGenericClassName();
this.javaFieldName = toJavaFieldName(fieldDescriptor.getName(), false);
this.methodNamePart = toJavaFieldName(fieldDescriptor.getName(), true);
final String javaClass = builder.getJavaClass();
final String javaPackage = builder.getJavaPackage();
this.builderClassName = getClassName(javaPackage, javaClass);
final MessageTypeCache messageTypeCache = builder.getMessageTypeCache();
this.listElementClassName = getParameterClassName(fieldDescriptor, messageTypeCache);
this.isScalarOrEnum = isScalarType(fieldDescriptor) || isEnumType(fieldDescriptor);
}
@Override
public Collection<MethodSpec> construct() {
log().trace("The methods construction for the {} repeated field is started.",
javaFieldName);
final List<MethodSpec> methods = newArrayList();
methods.add(createGetter());
methods.addAll(createRepeatedMethods());
methods.addAll(createRepeatedRawMethods());
log().trace("The methods construction for the {} repeated field is finished.",
javaFieldName);
return methods;
}
private MethodSpec createGetter() {
log().trace("The getter construction for the repeated field is started.");
final String methodName = "get" + methodNamePart;
final ClassName rawType = ClassName.get(List.class);
final ParameterizedTypeName returnType = ParameterizedTypeName.get(rawType,
listElementClassName);
final String returnStatement = format("return %s.get%sList()",
getMessageBuilder(), methodNamePart);
final MethodSpec methodSpec =
MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PUBLIC)
.returns(returnType)
.addStatement(returnStatement)
.build();
log().trace("The getter construction for the repeated field is finished.");
return methodSpec;
}
private Collection<MethodSpec> createRepeatedRawMethods() {
log().trace("The raw methods construction for the repeated field is is started.");
final List<MethodSpec> methods = newArrayList();
methods.add(createRawAddObjectMethod());
methods.add(createRawSetObjectByIndexMethod());
methods.add(createRawAddAllMethod());
// Some methods are not available in Protobuf Message.Builder for scalar types.
if (!isScalarOrEnum) {
methods.add(createRawAddObjectByIndexMethod());
}
log().trace("The raw methods construction for the repeated field is is finished.");
return methods;
}
private Collection<MethodSpec> createRepeatedMethods() {
final List<MethodSpec> methods = newArrayList();
methods.add(createClearMethod());
methods.add(createAddObjectMethod());
methods.add(createSetObjectByIndexMethod());
methods.add(createAddAllMethod());
// Some methods are not available in Protobuf Message.Builder for scalar types and enums.
if (!isScalarOrEnum) {
methods.add(createAddObjectByIndexMethod());
methods.add(createRemoveObjectByIndexMethod());
}
return methods;
}
private static boolean isScalarType(FieldDescriptorProto fieldDescriptor) {
boolean isScalarType = false;
final Type type = fieldDescriptor.getType();
for (ProtoScalarType scalarType : ProtoScalarType.values()) {
if (scalarType.getProtoScalarType() == type) {
isScalarType = true;
}
}
return isScalarType;
}
private static boolean isEnumType(FieldDescriptorProto fieldDescriptor) {
final Type type = fieldDescriptor.getType();
final boolean result = type == TYPE_ENUM;
return result;
}
private MethodSpec createRawAddObjectMethod() {
final String methodName = ADD_RAW_PREFIX + methodNamePart;
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final String addValueStatement = getMessageBuilder() + '.'
+ ADD_PREFIX + methodNamePart + "(convertedValue)";
final String convertStatement = createValidateStatement(CONVERTED_VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, VALUE)
.addException(ValidationException.class)
.addException(ConversionException.class)
.addStatement(createConvertSingularValue(VALUE),
listElementClassName,
listElementClassName)
.addStatement(descriptorCodeLine, FieldDescriptor.class)
.addStatement(convertStatement,
fieldDescriptor.getName())
.addStatement(addValueStatement)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createRawAddObjectByIndexMethod() {
final MethodSpec result = modifyCollectionByIndexWithRaw(ADD_RAW_PREFIX, ADD_PREFIX);
return result;
}
private MethodSpec createRawSetObjectByIndexMethod() {
return modifyCollectionByIndexWithRaw(SET_RAW_PREFIX, SET_PREFIX);
}
@SuppressWarnings("MethodParameterNamingConvention") // named according to its meaning.
private MethodSpec modifyCollectionByIndexWithRaw(String methodNamePrefix,
String realBuilderCallPrefix) {
final String methodName = methodNamePrefix + methodNamePart;
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final String modificationStatement =
format("%s.%s%s(%s, convertedValue)",
getMessageBuilder(), realBuilderCallPrefix, methodNamePart, INDEX);
final String convertStatement = createValidateStatement(CONVERTED_VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(TypeName.INT, INDEX)
.addParameter(String.class, VALUE)
.addException(ValidationException.class)
.addException(ConversionException.class)
.addStatement(createConvertSingularValue(VALUE),
listElementClassName,
listElementClassName)
.addStatement(descriptorCodeLine, FieldDescriptor.class)
.addStatement(convertStatement,
fieldDescriptor.getName())
.addStatement(modificationStatement)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createRawAddAllMethod() {
final String rawMethodName = fieldType.getSetterPrefix() + rawSuffix() + methodNamePart;
final String methodName = toJavaFieldName(rawMethodName, false);
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final String addAllValues = getMessageBuilder()
+ format(".addAll%s(%s)", methodNamePart, CONVERTED_VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, VALUE)
.addException(ValidationException.class)
.addException(ConversionException.class)
.addStatement(createGetConvertedCollectionValue(),
List.class,
listElementClassName,
Types.class,
listElementClassName)
.addStatement(descriptorCodeLine, FieldDescriptor.class)
.addStatement(createValidateStatement(CONVERTED_VALUE),
fieldDescriptor.getName())
.addStatement(addAllValues)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createAddAllMethod() {
final String methodName = fieldType.getSetterPrefix() + methodNamePart;
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final ClassName rawType = ClassName.get(List.class);
final ParameterizedTypeName parameter = ParameterizedTypeName.get(rawType,
listElementClassName);
final String fieldName = fieldDescriptor.getName();
final String addAllValues = getMessageBuilder()
+ format(".addAll%s(%s)", methodNamePart, VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(parameter, VALUE)
.addException(ValidationException.class)
.addStatement(descriptorCodeLine,
FieldDescriptor.class)
.addStatement(createValidateStatement(VALUE),
fieldName)
.addStatement(addAllValues)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createAddObjectMethod() {
final String methodName = ADD_PREFIX + methodNamePart;
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final String addValue = format("%s.%s%s(%s)",
getMessageBuilder(), ADD_PREFIX, methodNamePart, VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(listElementClassName, VALUE)
.addException(ValidationException.class)
.addStatement(descriptorCodeLine, FieldDescriptor.class)
.addStatement(createValidateStatement(VALUE),
javaFieldName)
.addStatement(addValue)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createAddObjectByIndexMethod() {
return modifyCollectionByIndex(ADD_PREFIX);
}
private MethodSpec createSetObjectByIndexMethod() {
return modifyCollectionByIndex(SET_PREFIX);
}
private MethodSpec createRemoveObjectByIndexMethod() {
final String methodName = removePrefix() + methodNamePart;
final String addValue = format("%s.%s%s(%s)", getMessageBuilder(),
removePrefix(), methodNamePart, INDEX);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(TypeName.INT, INDEX)
.addStatement(addValue)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec modifyCollectionByIndex(String methodPrefix) {
final String methodName = methodPrefix + methodNamePart;
final String descriptorCodeLine = createDescriptorStatement(fieldIndex,
builderGenericClassName);
final String modificationStatement = format("%s.%s%s(%s, %s)", getMessageBuilder(),
methodPrefix, methodNamePart, INDEX, VALUE);
final MethodSpec result = MethodSpec.methodBuilder(methodName)
.returns(builderClassName)
.addModifiers(Modifier.PUBLIC)
.addParameter(TypeName.INT, INDEX)
.addParameter(listElementClassName, VALUE)
.addException(ValidationException.class)
.addStatement(descriptorCodeLine, FieldDescriptor.class)
.addStatement(createValidateStatement(VALUE),
javaFieldName)
.addStatement(modificationStatement)
.addStatement(returnThis())
.build();
return result;
}
private MethodSpec createClearMethod() {
final String clearField = getMessageBuilder() + clearProperty(methodNamePart);
final MethodSpec result = MethodSpec.methodBuilder(clearPrefix() + methodNamePart)
.addModifiers(Modifier.PUBLIC)
.returns(builderClassName)
.addStatement(clearField)
.addStatement(returnThis())
.build();
return result;
}
private static String createGetConvertedCollectionValue() {
final String result = "final $T<$T> convertedValue = " +
"convert(value, $T.listTypeOf($T.class))";
return result;
}
/**
* Creates a new builder for the {@code RepeatedFieldMethodConstructor} class.
*
* @return created builder
*/
static RepeatedFieldMethodsConstructorBuilder newBuilder() {
return new RepeatedFieldMethodsConstructorBuilder();
}
/**
* A builder for the {@code RepeatedFieldMethodConstructor} class.
*/
static class RepeatedFieldMethodsConstructorBuilder
extends AbstractMethodConstructorBuilder<RepeatedFieldMethodConstructor> {
@Override
RepeatedFieldMethodConstructor build() {
super.build();
return new RepeatedFieldMethodConstructor(this);
}
}
private enum LogSingleton {
INSTANCE;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Logger value = LoggerFactory.getLogger(RepeatedFieldMethodConstructor.class);
}
private static Logger log() {
return LogSingleton.INSTANCE.value;
}
}
|
package org.vaadin.grid.cellrenderers.client.editable;
import java.util.Date;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.user.client.ui.PopupPanel;
import com.vaadin.client.VConsole;
import com.vaadin.client.ui.VPopupCalendar;
import com.vaadin.shared.ui.datefield.Resolution;
/*
* Purpose of this class is to get rid of extra baggage of updateValue which is not needed in renderer usecase
*/
public class VMyPopupCalendar extends VPopupCalendar {
private static final String PARSE_ERROR_CLASSNAME = "-parseerror";
@Override
public void updateValue(Date newDate) {
setCurrentDate(newDate);
}
@Override
public void onClick(ClickEvent event) {
if (event.getSource() == calendarToggle && isEnabled()) {
openCalendarPanel();
}
}
@Override
@SuppressWarnings("deprecation")
public void onChange(ChangeEvent event) {
if (!text.getText().equals("")) {
try {
String enteredDate = text.getText();
setDate(getDateTimeService().parseDate(enteredDate,
getFormatString(), lenient));
if (lenient) {
// If date value was leniently parsed, normalize text
// presentation.
// FIXME: Add a description/example here of when this is
// needed
text.setValue(
getDateTimeService().formatDate(getDate(),
getFormatString()), false);
}
// remove possibly added invalid value indication
removeStyleName(getStylePrimaryName() + PARSE_ERROR_CLASSNAME);
} catch (final Exception e) {
VConsole.log(e);
addStyleName(getStylePrimaryName() + PARSE_ERROR_CLASSNAME);
setDate(null);
}
} else {
setDate(null);
// remove possibly added invalid value indication
removeStyleName(getStylePrimaryName() + PARSE_ERROR_CLASSNAME);
}
}
}
|
package org.blockjam.oceanman;
import static org.spongepowered.api.Sponge.getServer;
import com.google.common.collect.Sets;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.world.Chunk;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.WorldArchetype;
import org.spongepowered.api.world.WorldArchetypes;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import org.spongepowered.api.world.storage.WorldProperties;
import java.io.IOException;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
public class WorldScanner {
private static final Set<BiomeType> OCEAN_BIOMES
= Sets.newHashSet(BiomeTypes.OCEAN, BiomeTypes.DEEP_OCEAN, BiomeTypes.FROZEN_OCEAN);
private World world;
private int total;
private int ocean;
public Optional<Long> scanWorld() {
WorldProperties wp = null;
try {
UUID id = UUID.randomUUID();
WorldArchetype wa = WorldArchetype.builder().build(id.toString(), id.toString());
OceanManPlugin.logger().info("Creating new world");
wp = Sponge.getServer().createWorldProperties(id.toString(), wa);
Sponge.getServer().saveWorldProperties(wp);
long seed = wp.getSeed();
OceanManPlugin.logger().info("Starting scan for seed " + seed);
world = getServer().loadWorld(id.toString()).get();
total = 0;
ocean = 0;
boolean failed = false;
outer:
for (int r = 0; r <= OceanManPlugin.config().scanRadius; r++) {
OceanManPlugin.logger().info("Scanning radius level " + r);
boolean intolerant = r <= OceanManPlugin.config().minOceanDistance;
// this isn't even close to DRY but idk how else to write it
for (int i = -r; i <= r; i++) {
if (!scanAndCheck(-r, i, intolerant)) {
failed = true;
break outer;
}
if (!scanAndCheck(r, i, intolerant)) {
failed = true;
break outer;
}
if (r != i && r != -i) {
if (!scanAndCheck(i, -r, intolerant)) {
failed = true;
break outer;
}
if (!scanAndCheck(i, r, intolerant)) {
failed = true;
break outer;
}
}
}
}
if (failed) {
OceanManPlugin.logger().info("World failed requirements; discarding");
}
return !failed ? Optional.of(seed) : Optional.empty();
} catch (IOException ex) {
OceanManPlugin.logger().error("Failed to create world");
ex.printStackTrace();
return Optional.empty();
} finally {
if (world != null) {
Sponge.getServer().unloadWorld(world);
world = null;
}
if (wp != null) {
wp.setEnabled(false);
Sponge.getServer().saveWorldProperties(wp);
Sponge.getServer().deleteWorld(wp);
}
}
}
private boolean scanAndCheck(int x, int z, boolean intolerant) {
Chunk chunk = world.loadChunk(world.getSpawnLocation().getChunkPosition().add(x, 0, z), true).get();
int minX = chunk.getPosition().getX() * 16;
int minZ = chunk.getPosition().getZ() * 16;
for (int cx = 0; cx < 16; cx++) {
for (int cz = 0; cz < 16; cz++) {
total++;
if (OCEAN_BIOMES.contains(chunk.getLocation(minX + cx, 0, minZ + cz).getBiome())) {
if (intolerant) {
return false;
}
ocean++;
if (!check()) {
return false;
}
}
}
}
return true;
}
private boolean check() {
return (float) ocean / (float) total > OceanManPlugin.config().maxOceanContent;
}
}
|
package org.codehaus.mojo.build;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmResult;
import org.apache.maven.scm.command.status.StatusScmResult;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.command.update.UpdateScmResultWithRevision;
import org.apache.maven.scm.log.ScmLogDispatcher;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.provider.ScmProvider;
import org.apache.maven.scm.provider.ScmProviderRepository;
import org.apache.maven.scm.provider.svn.AbstractSvnScmProvider;
import org.apache.maven.scm.provider.svn.command.info.SvnInfoItem;
import org.apache.maven.scm.provider.svn.command.info.SvnInfoScmResult;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.StringUtils;
/**
* This mojo is designed to give you a build number. So when you might make 100 builds of version
* 1.0-SNAPSHOT, you can differentiate between them all. The build number is based on the revision
* number retrieved from scm. It only works with subversion, currently. This mojo can also check to
* make sure that you have checked everything into scm, before issuing the build number. That
* behaviour can be suppressed, and then the latest local build number is used. Build numbers are
* not reflected in your artifact's filename (automatically), but can be added to the metadata. You
* can access the build number in your pom with ${buildNumber}. You can also access ${timestamp} and
* the scm branch of the build (if applicable) in ${buildScmBranch}
*
* @author <a href="mailto:woodj@ucalgary.ca">Julian Wood</a>
* @version $Id$
* @goal create
* @requiresProject
* @description create a timestamp and a build number from scm or an integer sequence
*/
public class CreateMojo
extends AbstractMojo
{
/**
* @parameter expression="${project.scm.developerConnection}"
* @readonly
*/
private String urlScm;
/**
* The username that is used when connecting to the SCM system.
*
* @parameter expression="${username}"
* @since 1.0-beta-1
*/
private String username;
/**
* The password that is used when connecting to the SCM system.
*
* @parameter expression="${password}"
* @since 1.0-beta-1
*/
private String password;
/**
* Local directory to be used to issue SCM actions
*
* @parameter expression="${maven.buildNumber.scmDirectory}" default-value="${basedir}
* @since 1.0-beta-
*/
private File scmDirectory;
/**
* You can rename the buildNumber property name to another property name if desired.
*
* @parameter expression="${maven.buildNumber.buildNumberPropertyName}"
* default-value="buildNumber"
* @since 1.0-beta-1
*/
private String buildNumberPropertyName;
/**
* You can rename the timestamp property name to another property name if desired.
*
* @parameter expression="${maven.buildNumber.timestampPropertyName}" default-value="timestamp"
* @since 1.0-beta-1
*/
private String timestampPropertyName;
/**
* If this is made true, we check for modified files, and if there are any, we fail the build.
* Note that this used to be inverted (skipCheck), but needed to be changed to allow releases to
* work. This corresponds to 'svn status'.
*
* @parameter expression="${maven.buildNumber.doCheck}" default-value="false"
* @since 1.0-beta-1
*/
private boolean doCheck;
/**
* If this is made true, then the revision will be updated to the latest in the repo, otherwise
* it will remain what it is locally. Note that this used to be inverted (skipUpdate), but
* needed to be changed to allow releases to work. This corresponds to 'svn update'.
*
* Note that these expressions (doCheck, doUpdate, etc) are the first thing evaluated. If there
* is no matching expression, we get the default-value. If there is (ie
* -Dmaven.buildNumber.doCheck=false), we get that value. The configuration, however, gets the
* last say, through use of the getters/setters below. So if <doCheck>true</doCheck>, then
* normally that's the final value of the param in question. However, this mojo reverses that
* behaviour, such that the command line parameters get the last say.
*
* @parameter expression="${maven.buildNumber.doUpdate}" default-value="false"
* @since 1.0-beta-1
*/
private boolean doUpdate;
/**
* Specify a message as specified by java.text.MessageFormat. This triggers "items"
* configuration to be read
*
* @parameter
* @since 1.0-beta-1
*/
private String format;
/**
* Properties file to be created when "format" is not null and item has "buildNumber". See Usage
* for details
*
* @parameter default-value="${basedir}/buildNumber.properties";
* @since 1.0-beta-2
*/
private File buildNumberPropertiesFileLocation;
/**
* Specify the corresponding items for the format message, as specified by
* java.text.MessageFormat. Special item values are "timestamp" and "buildNumber/d*".
*
* @parameter
* @since 1.0-beta-1
*/
private List items;
/**
* The locale used for date and time formatting. The locale name should be in the format defined
* in {@link Locale#toString()}. The default locale is the platform default returned by
* {@link Locale#getDefault()}.
*
* @parameter expression="${maven.buildNumber.locale}"
* @since 1.0-beta-2
*/
private String locale;
/**
* whether to retrieve the revision for the last commit, or the last revision of the repository.
*
* @parameter expression="${maven.buildNumber.useLastCommittedRevision}" default-value="false"
* @since 1.0-beta-2
*/
private boolean useLastCommittedRevision;
/**
* Apply this java.text.MessageFormat to the timestamp only (as opposed to the
* <code>format</code> parameter).
*
* @parameter
* @since 1.0-beta-2
*/
private String timestampFormat;
/**
* Setting this value allows the build to continue even in the event of an SCM failure. The value set will be
* used as the revision string in the event of a failure to retrieve the revision it from the SCM.
*
* @parameter
* @since 1.0-beta-2
*/
private String revisionOnScmFailure;
/**
* Selects alternative SCM provider implementations. Each map key denotes the original provider type as given in the
* SCM URL like "cvs" or "svn", the map value specifies the provider type of the desired implementation to use
* instead. In other words, this map configures a substitition mapping for SCM providers.
*
* @parameter
* @since 1.0-beta-3
*/
private Map providerImplementations;
/**
* @component
*/
private ScmManager scmManager;
/**
* The maven project.
*
* @parameter expression="${project}"
* @readonly
*/
private MavenProject project;
/**
* Contains the full list of projects in the reactor.
*
* @parameter expression="${reactorProjects}"
* @readonly
* @since 1.0-beta-3
*/
private List reactorProjects;
/**
* If set to true, will get the scm revision once for all modules of a multi-module project
* instead of fetching once for each module.
*
* @parameter default-value="false"
* @since 1.0-beta-3
*
*/
private boolean getRevisionOnlyOnce;
/**
* You can rename the buildScmBranch property name to another property name if desired.
*
* @parameter expression="${maven.buildNumber.scmBranchPropertyName}"
* default-value="scmBranch"
* @since 1.0-beta-4
*/
private String scmBranchPropertyName;
/**
* @parameter expression="${session}"
* @readonly
* @required
*/
protected MavenSession session;
private ScmLogDispatcher logger;
private String revision;
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( providerImplementations != null )
{
for ( Iterator i = providerImplementations.keySet().iterator(); i.hasNext(); )
{
String providerType = (String) i.next();
String providerImplementation = (String) providerImplementations.get( providerType );
getLog().info(
"Change the default '" + providerType + "' provider implementation to '"
+ providerImplementation + "'." );
scmManager.setScmProviderImplementation( providerType, providerImplementation );
}
}
Date now = Calendar.getInstance().getTime();
if ( format != null )
{
if ( items == null )
{
throw new MojoExecutionException(
" if you set a format, you must provide at least one item, please check documentation " );
}
// needs to be an array
// look for special values
Object[] itemAry = new Object[items.size()];
for ( int i = 0; i < items.size(); i++ )
{
Object item = items.get( i );
if ( item instanceof String )
{
String s = (String) item;
if ( s.equals( "timestamp" ) )
{
itemAry[i] = now;
}
else if ( s.startsWith( "buildNumber" ) )
{
// check for properties file
File propertiesFile = this.buildNumberPropertiesFileLocation;
// create if not exists
if ( !propertiesFile.exists() )
{
try
{
propertiesFile.createNewFile();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't create properties file: " + propertiesFile,
e );
}
}
Properties properties = new Properties();
String buildNumberString = null;
try
{
// get the number for the buildNumber specified
properties.load( new FileInputStream( propertiesFile ) );
buildNumberString = properties.getProperty( s );
if ( buildNumberString == null )
{
buildNumberString = "0";
}
int buildNumber = Integer.valueOf( buildNumberString ).intValue();
// store the increment
properties.setProperty( s, String.valueOf( ++buildNumber ) );
properties.store( new FileOutputStream( propertiesFile ),
"maven.buildNumber.plugin properties file" );
// use in the message (format)
itemAry[i] = new Integer( buildNumber );
}
catch ( NumberFormatException e )
{
throw new MojoExecutionException(
"Couldn't parse buildNumber in properties file to an Integer: "
+ buildNumberString );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Couldn't load properties file: " + propertiesFile, e );
}
}
else
{
itemAry[i] = item;
}
}
else
{
itemAry[i] = item;
}
}
revision = format( itemAry );
}
else
{
// Check if the plugin has already run.
revision = project.getProperties().getProperty( this.buildNumberPropertyName );
if ( this.getRevisionOnlyOnce && revision != null)
{
getLog().debug( "Revision available from previous execution" );
return;
}
if ( doCheck )
{
// we fail if there are local mods
checkForLocalModifications();
}
else
{
getLog().info( "Checking for local modifications: skipped." );
}
if ( session.getSettings().isOffline() )
{
getLog().info( "maven is executed in offline mode, Updating project files from SCM: skipped." );
}
else
{
if ( doUpdate )
{
// we update your local repo
// even after you commit, your revision stays the same until you update, thus this
// action
List changedFiles = update();
for ( Iterator i = changedFiles.iterator(); i.hasNext(); )
{
ScmFile file = (ScmFile) i.next();
getLog().info( "Updated: " + file );
}
if ( changedFiles.size() == 0 )
{
getLog().info( "No files needed updating." );
}
}
else
{
getLog().info( "Updating project files from SCM: skipped." );
}
}
revision = getRevision();
}
if ( project != null )
{
String timestamp = String.valueOf( now.getTime() );
if ( timestampFormat != null )
{
timestamp = MessageFormat.format( timestampFormat, new Object[] { now } );
}
getLog().info(
MessageFormat.format( "Storing buildNumber: {0} at timestamp: {1}", new Object[] {
revision,
timestamp } ) );
if ( revision != null )
{
project.getProperties().put( buildNumberPropertyName, revision );
}
project.getProperties().put( timestampPropertyName, timestamp );
String scmBranch = getScmBranch();
getLog().info("Storing buildScmBranch: " + scmBranch);
project.getProperties().put( scmBranchPropertyName, scmBranch );
// Add the revision and timestamp properties to each project in the reactor
if ( getRevisionOnlyOnce && reactorProjects != null )
{
Iterator projIter = reactorProjects.iterator();
while ( projIter.hasNext() )
{
MavenProject nextProj = (MavenProject) projIter.next();
nextProj.getProperties().put( this.buildNumberPropertyName, revision );
nextProj.getProperties().put( this.timestampPropertyName, timestamp );
nextProj.getProperties().put( this.scmBranchPropertyName, scmBranch );
}
}
}
}
/**
* Formats the given argument using the configured format template and locale.
*
* @param arguments arguments to be formatted @ @return formatted result
*/
private String format( Object[] arguments )
{
Locale l = Locale.getDefault();
if ( locale != null )
{
String[] parts = locale.split( "_", 3 );
if ( parts.length <= 1 )
{
l = new Locale( locale );
}
else if ( parts.length == 2 )
{
l = new Locale( parts[0], parts[1] );
}
else
{
l = new Locale( parts[0], parts[1], parts[2] );
}
}
return new MessageFormat( format, l ).format( arguments );
}
private void checkForLocalModifications()
throws MojoExecutionException
{
getLog().info( "Verifying there are no local modifications ..." );
List changedFiles;
try
{
changedFiles = getStatus();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "An error has occurred while checking scm status.", e );
}
if ( !changedFiles.isEmpty() )
{
StringBuffer message = new StringBuffer();
for ( Iterator i = changedFiles.iterator(); i.hasNext(); )
{
ScmFile file = (ScmFile) i.next();
message.append( file.toString() );
message.append( "\n" );
}
throw new MojoExecutionException(
"Cannot create the build number because you have local modifications : \n"
+ message );
}
}
public List update()
throws MojoExecutionException
{
try
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
UpdateScmResult result = scmProvider.update( repository, new ScmFileSet( scmDirectory ) );
checkResult( result );
if ( scmProvider instanceof AbstractSvnScmProvider )
{
String revision = ( (UpdateScmResultWithRevision) result ).getRevision();
getLog().info( "Got a revision during update: " + revision );
this.revision = revision;
}
return result.getUpdatedFiles();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Couldn't update project.", e );
}
}
public List getStatus()
throws ScmException
{
ScmRepository repository = getScmRepository();
ScmProvider scmProvider = scmManager.getProviderByRepository( repository );
StatusScmResult result = scmProvider.status( repository, new ScmFileSet( scmDirectory ) );
checkResult( result );
return result.getChangedFiles();
}
/**
* Get the branch info for this revision from the repository. For svn, it is in svn info.
*
* @return
* @throws MojoExecutionException
* @throws MojoExecutionException
*/
public String getScmBranch()
throws MojoExecutionException
{
String scmUrl;
try
{
ScmRepository repository = getScmRepository();
SvnInfoScmResult scmResult = info( repository, new ScmFileSet( scmDirectory ) );
checkResult( scmResult );
SvnInfoItem info = (SvnInfoItem) scmResult.getInfoItems().get( 0 );
scmUrl = info.getURL();
}
catch ( ScmException e )
{
throw new MojoExecutionException( "Cannot get the branch information from the scm repository : \n" +
e.getLocalizedMessage(), e );
}
return filterBranchFromScmUrl( scmUrl );
}
protected String filterBranchFromScmUrl( String scmUrl )
{
String scmBranch = "UNKNOWN";
if ( scmUrl.indexOf( "/trunk" ) != -1 )
{
scmBranch = "trunk";
}
else if ( ( scmUrl.indexOf( "/branches" ) != -1 ) || scmUrl.indexOf( "/tags" ) != -1 )
{
scmBranch = scmUrl.replaceFirst( ".*((branches|tags)[^/]*).*?", "$1" );
}
return scmBranch;
}
/**
* Get the revision info from the repository. For svn, it is svn info
*
* @return
* @throws MojoExecutionException
*/
public String getRevision()
throws MojoExecutionException
{
if ( format != null )
{
return revision;
}
try
{
ScmRepository repository = getScmRepository();
SvnInfoScmResult scmResult = info( repository, new ScmFileSet( scmDirectory ) );
checkResult( scmResult );
SvnInfoItem info = (SvnInfoItem) scmResult.getInfoItems().get( 0 );
if ( useLastCommittedRevision )
{
return info.getLastChangedRevision();
}
return info.getRevision();
}
catch ( ScmException e )
{
if ( !StringUtils.isEmpty( revisionOnScmFailure ) )
{
getLog().warn(
"Cannot get the revision information from the scm repository, proceeding with "
+ "revision of " + revisionOnScmFailure + " : \n" + e.getLocalizedMessage() );
setDoCheck( false );
setDoUpdate( false );
return revisionOnScmFailure;
}
throw new MojoExecutionException( "Cannot get the revision information from the scm repository : \n"
+ e.getLocalizedMessage(), e );
}
}
/**
* Get info from svn.
*
* @param repository
* @param fileSet
* @return
* @throws ScmException
* @todo this should be rolled into org.apache.maven.scm.provider.ScmProvider and
* org.apache.maven.scm.provider.svn.SvnScmProvider
*/
public SvnInfoScmResult info( ScmRepository repository, ScmFileSet fileSet )
throws ScmException
{
AbstractSvnScmProvider abstractSvnScmProvider = (AbstractSvnScmProvider) scmManager.getProviderByType( "svn" );
return abstractSvnScmProvider.info( repository.getProviderRepository(), fileSet, null );
//org.apache.maven.scm.provider.svn.svnexe.command.info.SvnInfoCommand command =
// new org.apache.maven.scm.provider.svn.svnexe.command.info.SvnInfoCommand();
//command.setLogger( getLogger() );
//return (SvnInfoScmResult) command.execute( repository.getProviderRepository(), fileSet, null );
}
/**
* @return
* @todo normally this would be handled in AbstractScmProvider
*/
private ScmLogger getLogger()
{
if ( logger == null )
{
logger = new ScmLogDispatcher();
}
return logger;
}
private ScmRepository getScmRepository()
throws ScmException
{
ScmRepository repository;
repository = scmManager.makeScmRepository( urlScm );
ScmProviderRepository scmRepo = repository.getProviderRepository();
if ( !StringUtils.isEmpty( username ) )
{
scmRepo.setUser( username );
}
if ( !StringUtils.isEmpty( password ) )
{
scmRepo.setPassword( password );
}
return repository;
}
private void checkResult( ScmResult result )
throws ScmException
{
if ( !result.isSuccess() )
{
// TODO: improve error handling
System.err.println( "Provider message:" );
System.err.println( result.getProviderMessage() );
System.err.println( "Command output:" );
System.err.println( result.getCommandOutput() );
throw new ScmException( "Error!" );
}
}
// setters to help with test
public void setScmManager( ScmManager scmManager )
{
this.scmManager = scmManager;
}
public void setUrlScm( String urlScm )
{
this.urlScm = urlScm;
}
public void setUsername( String username )
{
this.username = username;
}
public void setPassword( String password )
{
this.password = password;
}
public void setDoCheck( boolean doCheck )
{
String doCheckSystemProperty = System.getProperty( "maven.buildNumber.doCheck" );
if ( doCheckSystemProperty != null )
{
// well, this gets the final say
this.doCheck = Boolean.valueOf( doCheckSystemProperty ).booleanValue();
}
else
{
this.doCheck = doCheck;
}
}
public void setDoUpdate( boolean doUpdate )
{
String doUpdateSystemProperty = System.getProperty( "maven.buildNumber.doUpdate" );
if ( doUpdateSystemProperty != null )
{
// well, this gets the final say
this.doUpdate = Boolean.valueOf( doUpdateSystemProperty ).booleanValue();
}
else
{
this.doUpdate = doUpdate;
}
}
void setFormat( String format )
{
this.format = format;
}
void setLocale( String locale )
{
this.locale = locale;
}
void setItems( List items )
{
this.items = items;
}
public void setBuildNumberPropertiesFileLocation( File buildNumberPropertiesFileLocation )
{
this.buildNumberPropertiesFileLocation = buildNumberPropertiesFileLocation;
}
public void setScmDirectory( File scmDirectory )
{
this.scmDirectory = scmDirectory;
}
public void setRevisionOnScmFailure( String revisionOnScmFailure )
{
this.revisionOnScmFailure = revisionOnScmFailure;
}
}
|
package org.concord.energy3d.gui;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import java.util.concurrent.CancellationException;
import javax.imageio.ImageIO;
import javax.net.ssl.SSLKeyException;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.concord.energy3d.scene.Scene;
import com.ardor3d.math.MathUtils;
public class MapDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static final int zoomMin = 0;
private static final int zoomMax = 21;
private final JTextField addressField = new JTextField("25 Love lane, Concord, MA, USA");
private final JSpinner latitudeSpinner = new JSpinner(new SpinnerNumberModel(42.45661, -90, 90, 0.00001));
private final JSpinner longitudeSpinner = new JSpinner(new SpinnerNumberModel(-71.35823, -90, 90, 0.00001));
private final JSpinner zoomSpinner = new JSpinner(new SpinnerNumberModel(20, zoomMin, zoomMax, 1));
private final JLabel mapLabel = new JLabel();
private static MapDialog instance;
private boolean lock = false;
private GoogleMapImageLoader mapImageLoader;
class GoogleMapImageLoader extends SwingWorker<BufferedImage, Void> {
final String googleMapUrl = getGoogleMapUrl(false);
@Override
protected BufferedImage doInBackground() throws Exception {
return ImageIO.read(new URL(googleMapUrl));
}
protected void displayError(final Exception e) {
if (e instanceof CancellationException) {
return;
}
e.printStackTrace();
if (e.getCause() instanceof SSLKeyException) {
JOptionPane.showMessageDialog(MapDialog.this, "Missing feature! To use this feature you need to download and install the latest version of Energy3D.", getTitle(), JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(MapDialog.this, "Could not retrieve map from google!\nPlease check your internet connection and try again.", getTitle(), JOptionPane.WARNING_MESSAGE);
}
}
}
public static void showDialog() {
if (instance == null) {
instance = new MapDialog(MainFrame.getInstance());
}
instance.setVisible(true);
}
private MapDialog(final JFrame owner) {
super(owner);
setTitle("Map");
final JSpinner.NumberEditor latEditor = new JSpinner.NumberEditor(latitudeSpinner, "0.00000");
final JSpinner.NumberEditor lngEditor = new JSpinner.NumberEditor(longitudeSpinner, "0.00000");
latEditor.getTextField().setColumns(6);
lngEditor.getTextField().setColumns(6);
latitudeSpinner.setEditor(latEditor);
longitudeSpinner.setEditor(lngEditor);
mapLabel.setAlignmentX(0.5f);
mapLabel.setPreferredSize(new Dimension(640, 640));
final Point point = new Point();
mapLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
point.setLocation(e.getPoint());
}
@Override
public void mouseReleased(final MouseEvent e) {
point.setLocation(0, 0);
}
});
mapLabel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(final MouseEvent e) {
if (point.getX() != 0 && point.getY() != 0) {
final double dx = e.getX() - point.getX();
final double dy = e.getY() - point.getY();
final Double lat = (Double) latitudeSpinner.getValue();
final Double lng = (Double) longitudeSpinner.getValue();
lock = true;
final double scale = getScale();
latitudeSpinner.setValue(lat + dy / 1000000.0 * scale);
longitudeSpinner.setValue(lng - dx / 750000.0 * scale);
lock = false;
updateMap();
}
point.setLocation(e.getPoint());
}
});
mapLabel.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
lock = true;
zoomSpinner.setValue(MathUtils.clamp((Integer) zoomSpinner.getValue() - e.getWheelRotation(), zoomMin, zoomMax));
lock = false;
updateMap();
}
});
addressField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final double[] coordinates = getGoogleMapAddressCoordinates();
if (coordinates != null) {
lock = true;
latitudeSpinner.setValue(coordinates[0]);
longitudeSpinner.setValue(coordinates[1]);
zoomSpinner.setValue(20);
lock = false;
updateMap();
}
}
});
final ChangeListener changeListener = new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent event) {
if (lock) {
return;
}
updateMap();
}
};
latitudeSpinner.addChangeListener(changeListener);
longitudeSpinner.addChangeListener(changeListener);
zoomSpinner.addChangeListener(changeListener);
this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
final JPanel panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.setBorder(new EmptyBorder(5, 5, 0, 5));
panel1.add(new JLabel("Address:"));
panel1.add(addressField);
this.getContentPane().add(panel1);
final JPanel panel2 = new JPanel();
panel2.add(new JLabel("Latitude:"));
panel2.add(latitudeSpinner);
panel2.add(new JLabel("Longitude:"));
panel2.add(longitudeSpinner);
panel2.add(new JLabel("Zoom:"));
panel2.add(zoomSpinner);
this.getContentPane().add(panel2);
this.getContentPane().add(mapLabel);
final JPanel bottomPanel = new JPanel();
final JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
if ((Integer) zoomSpinner.getValue() < 16) {
JOptionPane.showMessageDialog(MapDialog.this, "The selected region is too large. Please zoom in and try again.", MapDialog.this.getTitle(), JOptionPane.WARNING_MESSAGE);
return;
}
new GoogleMapImageLoader() {
@Override
protected void done() {
try {
final BufferedImage mapImage = get();
Scene.getInstance().setGroundImage(mapImage, getScale());
Scene.getInstance().setGroundImageEarthView(true);
Scene.getInstance().setEdited(true);
setVisible(false);
} catch (final Exception e) {
displayError(e);
}
};
}.execute();
}
});
final JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
setVisible(false);
}
});
bottomPanel.add(okButton);
bottomPanel.add(cancelButton);
this.getContentPane().add(bottomPanel);
updateMap();
this.pack();
this.setLocationRelativeTo(owner);
}
private void updateMap() {
if (mapImageLoader != null) {
mapImageLoader.cancel(true);
}
mapImageLoader = new GoogleMapImageLoader() {
@Override
protected void done() {
try {
final BufferedImage mapImage = get();
final int w = getContentPane().getPreferredSize().width;
mapLabel.setIcon(new ImageIcon(mapImage.getScaledInstance(w, w, Image.SCALE_DEFAULT)));
pack();
mapImageLoader = null;
} catch (final Exception e) {
displayError(e);
}
}
};
mapImageLoader.execute();
}
private String getGoogleMapUrl(final boolean highResolution) {
final double x = (Double) latitudeSpinner.getValue();
final double y = (Double) longitudeSpinner.getValue();
final int zoom = (Integer) zoomSpinner.getValue();
final int scale = highResolution & zoom <= 20 ? 2 : 1;
final String googleMapUrl = "https://maps.googleapis.com/maps/api/staticmap?maptype=satellite¢er=" + x + "," + y + "&zoom=" + zoom + "&size=640x640&scale=" + scale + "&key=AIzaSyBEGiCg33CccHloDdPENWk1JDhwTEQaZQ0";
return googleMapUrl;
}
private double[] getGoogleMapAddressCoordinates() {
final String address = addressField.getText().replace(' ', '+');
try {
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=AIzaSyD7MfCQjMAlsdFA3OmfGZ_rzC8ldJPnoHc");
final Scanner scanner = new Scanner(url.openStream());
try {
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.indexOf("formatted_address") != -1) {
addressField.setText(line.substring(line.indexOf(':') + 3, line.length() - 2));
} else if (line.indexOf("\"lat\" :") != -1) {
final double[] result = new double[2];
result[0] = Double.valueOf(line.substring(line.indexOf(':') + 1, line.length() - 1));
line = scanner.nextLine();
result[1] = Double.valueOf(line.substring(line.indexOf(':') + 1));
return result;
}
}
} finally {
scanner.close();
}
} catch (final IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Could not retrieve map from google!\nPlease check your internet connection and try again.", "Error", JOptionPane.WARNING_MESSAGE);
}
JOptionPane.showMessageDialog(this, "Could not find the address!", "Error", JOptionPane.WARNING_MESSAGE);
return null;
}
private double getScale() {
final int zoom = (Integer) zoomSpinner.getValue();
final double scale;
if (zoom == 21) {
scale = 0.5;
} else if (zoom == 20) {
scale = 1;
} else {
scale = Math.pow(2, 20 - zoom);
}
return scale;
}
}
|
package org.dezord.coherence.client;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModClassLoader;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.main.Main;
import net.minecraft.client.multiplayer.ServerAddress;
import net.minecraft.launchwrapper.Launch;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dezord.coherence.Coherence;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cpw.mods.fml.common.Loader;
@SideOnly(Side.CLIENT)
public class Cohere {
private static final Logger logger = LogManager.getLogger("Coherence");
public String url, address;
public List<String> modlist;
private List<String> neededmods;
private File cohereDir;
private String[] currentMods;
public Cohere(String link, String addr) throws ClientProtocolException, IOException, InterruptedException {
if (!Coherence.instance.postCohered) {
detectCrash();
url = link;
address = addr;
/*SiteVerifier verifier = new SiteVerifier(addr);
if (!verifier.verify()) {
logger.warn(address + " has been flagged as suspicious by several services."
+ "As such, Coherence will not attempt to synchronize with this server.");
return;
}*/
cohereDir = new File("coherence", address);
modlist = getModList();
neededmods = getNeededModsList();
downloadNeededMods();
getConfigs();
moveMods();
writeConfigFile();
restartMinecraft();
}
}
private void detectCrash() {
File curMods = new File("coherence", "localhost");
if (curMods.isDirectory() && curMods.list().length > 0 && !Coherence.instance.postCohered) {
logger.info("Possible crash detected. Stopping minecraft.");
new PostCohere();
FMLCommonHandler.instance().exitJava(1, true);
}
}
private List<String> getModList() throws ClientProtocolException, IOException {
logger.info("Getting mod list");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
POSTGetter.get(url + "/modlist", stream);
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> modlist = new Gson().fromJson(stream.toString(), listType);
return modlist;
}
private List<String> getNeededModsList() {
File modDir = new File(cohereDir, "mods");
StringBuilder logList = new StringBuilder();
logList.append("Needed mods: ");
if ((!modDir.isDirectory()) || modDir.list().length == 0) { //If folder doesn't exist or is empty, return entire mod list
modDir.mkdirs();
for (String mod : modlist) {
logList.append(mod);
logList.append(", ");
}
logger.info(logList.toString());
return modlist;
}
List<String> currentMods = Arrays.asList(modDir.list());
List<String> neededMods = new ArrayList<String>();
for (String mod : modlist) { //Get list of mods that need to be downloaded from the server
if (!currentMods.contains(mod))
neededMods.add(mod);
}
for (String mod : currentMods) { //Delete all mods on client that are not on the server
if (!modlist.contains(mod)) {
logger.info("Deleting " + mod + " from local storage");
new File(modDir, mod).delete();
}
}
for (String mod : neededMods) { //List all needed mods
logList.append(mod);
logList.append(", ");
}
logger.info(logList.toString());
return neededMods;
}
private void downloadNeededMods() throws ClientProtocolException, IOException {
if (neededmods.isEmpty()) {
logger.info("No new mods needed.");
return;
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
HashMap<String, String> map = new HashMap<String, String>();
final File modDir = new File(cohereDir, "mods");
if (!modDir.isDirectory())
modDir.mkdirs();
int size = neededmods.size();
for (int i = 0; i < size; i++) {
stream.reset();
String mod = neededmods.get(i);
logger.info("Downloading mod " + mod + " (" + (i + 1) + "/" + size + ")");
map.clear(); map.put("mod", mod);
POSTGetter.get(url + "/mod", map, stream);
FileOutputStream fstream = new FileOutputStream(new File(modDir, neededmods.get(i)));
fstream.write(stream.toByteArray());
fstream.close();
}
}
private void getConfigs() throws IOException {
logger.info("Downloading configs");
try {
FileUtils.moveDirectory(new File("config"), new File("oldConfig")); //Move config folder
}
catch (FileExistsException e) {}
File configZip = new File(cohereDir, "config.zip");
if (configZip.exists())
configZip.delete();
configZip.createNewFile();
FileOutputStream fstream = new FileOutputStream(configZip);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
POSTGetter.get(url + "/config", stream);
stream.writeTo(fstream);
fstream.close();
stream.close();
logger.info("Extracting configs");
new UnzipUtility().unzip(configZip.getPath(), new File("config").getPath());
FileUtils.deleteQuietly(Coherence.instance.configName); //Make sure that Coherence config carries over
FileUtils.copyFile(new File("oldConfig", Coherence.instance.configName.getName()), Coherence.instance.configName);
}
private void moveMods() throws IOException {
File modDir = new File("mods"); File curMods = new File("coherence", "localhost");
FileUtils.copyDirectory(modDir, curMods);
File cohereMods = new File(cohereDir, "mods");
for (File mod : cohereMods.listFiles()) {
if (!mod.isDirectory() && !mod.getName().contains("coherence"))
FileUtils.copyFile(mod, new File(modDir, mod.getName()));
}
}
private void writeConfigFile() {
logger.info("Writing configuration file for persistence");
Configuration config = new Configuration(Coherence.instance.configName);
config.load();
Property addressProperty = config.get(config.CATEGORY_GENERAL, "connectToServer", "null");
addressProperty.set(address);
config.save();
}
private void restartMinecraft() throws IOException, InterruptedException {
logger.info("Restarting Minecraft");
StringBuilder cmd = new StringBuilder();
cmd.append("\"").append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java\" ");
for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
cmd.append(jvmArg + " ");
}
cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
String mcCommand = System.getProperty("sun.java.command"); //Get commands passed to Minecraft jar
if (!mcCommand.contains("GradleStart")) //Only run the LaunchWrapper if not in a development environment
cmd.append(Launch.class.getName()).append(" ");
logger.info("Command half-string: " + cmd.toString());
cmd.append(mcCommand);
Process process = Runtime.getRuntime().exec(cmd.toString());
/*byte[] b = new byte[1024]; //Debug code
InputStream stream = process.getInputStream();
while (true) {
stream.read(b);
logger.info(new String(b));
}*/
FMLCommonHandler.instance().exitJava(0, false);
}
}
|
package org.freedesktop.dbus;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import org.freedesktop.Hexdump;
import org.freedesktop.dbus.messages.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cx.ath.matthew.unix.USOutputStream;
public class MessageWriter implements Closeable {
private final Logger logger = LoggerFactory.getLogger(getClass());
private OutputStream outputStream;
private boolean unixSocket;
public MessageWriter(OutputStream _out) {
this.outputStream = _out;
this.unixSocket = false;
try {
if (_out instanceof USOutputStream) {
this.unixSocket = true;
}
} catch (Throwable t) {
}
if (!this.unixSocket) {
this.outputStream = new BufferedOutputStream(_out);
}
}
public void writeMessage(Message m) throws IOException {
logger.debug("<= {}", m);
if (null == m) {
return;
}
if (null == m.getWireData()) {
logger.warn("Message {} wire-data was null!", m);
return;
}
if (unixSocket) {
if (logger.isTraceEnabled()) {
logger.debug("Writing all {} buffers simultaneously to Unix Socket", m.getWireData().length );
for (byte[] buf : m.getWireData()) {
logger.trace("({}):{}", buf, (null == buf ? "" : Hexdump.format(buf)));
}
}
((USOutputStream) outputStream).write(m.getWireData());
} else {
for (byte[] buf : m.getWireData()) {
logger.trace("({}):{}", buf, (null == buf ? "" : Hexdump.format(buf)));
if (null == buf) {
break;
}
outputStream.write(buf);
}
}
outputStream.flush();
}
@Override
public void close() throws IOException {
logger.info("Closing Message Writer");
if (outputStream != null) {
outputStream.close();
}
outputStream = null;
}
public boolean isClosed() {
return outputStream != null;
}
}
|
package org.eclipse.birt.report.model.api.elements.structures;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.SimpleValueHandle;
import org.eclipse.birt.report.model.api.StructureHandle;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.core.DesignElement;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.core.Structure;
/**
* Represents one computed column. A computed column is a virtual column
* produced as an expression of other columns within the data set.
* <p>
* This is a managed object, meaning that all changes should be made though the
* command layer so that they can be undone and redone. Each computed column has
* the following properties:
*
* <p>
* <dl>
* <dt><strong>Column Name </strong></dt>
* <dd>a computed column has a required column name.</dd>
*
* <dt><strong>Expression </strong></dt>
* <dd>expression of the computation for the column.</dd>
* </dl>
*
*/
public class ComputedColumn extends Structure
{
/**
* Name of this structure. Matches the definition in the meta-data
* dictionary.
*/
public static final String COMPUTED_COLUMN_STRUCT = "ComputedColumn"; //$NON-NLS-1$
/**
* Name of the column name member.
*/
public static final String NAME_MEMBER = "name"; //$NON-NLS-1$
/**
* DisplayName of the column name member.
*/
public static final String DISPLAY_NAME_MEMBER = "displayName"; //$NON-NLS-1$
/**
* Name of the column name member.
*
* @deprecated using {@link #NAME_MEMBER} instead.
*/
public static final String COLUMN_NAME_MEMBER = "columnName"; //$NON-NLS-1$
/**
* Name of the expression member.
*/
public static final String EXPRESSION_MEMBER = "expression"; //$NON-NLS-1$
/**
* Name of the data-type member.
*/
public static final String DATA_TYPE_MEMBER = "dataType"; //$NON-NLS-1$
/**
* Name of the aggregateOn member.
*/
public static final String AGGREGATEON_MEMBER = "aggregateOn"; //$NON-NLS-1$
/**
* Name of the aggregateOn member.
*
* @deprecated
*/
public static final String AGGREGRATEON_MEMBER = "aggregrateOn"; //$NON-NLS-1$
/**
* Name of the aggregateOn member.
*/
public static final String AGGREGATEON_FUNCTION_MEMBER = "aggregateFunction"; //$NON-NLS-1$
/**
* Name of arguments of function member.
*/
public static final String ARGUMENTS_MEMBER = "arguments"; //$NON-NLS-1$
/**
* Name of the filter member.
*/
public static final String FILTER_MEMBER = "filterExpr"; //$NON-NLS-1$
/**
* The column display name.
*/
private String columnDisplayName = null;
/**
* The column name.
*/
private String columnName = null;
/**
* The expression for this computed column.
*/
private String expression = null;
/**
* The data type of this column.
*/
private String dataType = null;
/**
* The column name.
*/
private String aggregateFunc = null;
/**
* The aggregrateOn expression for the computed column.
*/
private List aggregrateOn = null;
/**
* The column display name.
*/
private List arguments = null;
/**
* The expression for this computed column.
*/
private String filterexpr = null;
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.IStructure#getStructName()
*/
public String getStructName( )
{
return COMPUTED_COLUMN_STRUCT;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.Structure#getIntrinsicProperty(java.lang.String)
*/
protected Object getIntrinsicProperty( String memberName )
{
if ( NAME_MEMBER.equals( memberName ) )
return columnName;
else if ( EXPRESSION_MEMBER.equals( memberName ) )
return expression;
else if ( DATA_TYPE_MEMBER.equals( memberName ) )
return dataType;
else if ( AGGREGRATEON_MEMBER.equalsIgnoreCase( memberName ) )
{
if ( aggregrateOn == null || aggregrateOn.isEmpty( ) )
return null;
return aggregrateOn.get( 0 );
}
else if ( DISPLAY_NAME_MEMBER.equalsIgnoreCase( memberName ) )
return columnDisplayName;
else if ( AGGREGATEON_MEMBER.equals( memberName ) )
return aggregrateOn;
else if ( AGGREGATEON_FUNCTION_MEMBER.equalsIgnoreCase( memberName ) )
return aggregateFunc;
else if ( ARGUMENTS_MEMBER.equalsIgnoreCase( memberName ) )
return arguments;
else if ( FILTER_MEMBER.equalsIgnoreCase( memberName ) )
return filterexpr;
assert false;
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.Structure#setIntrinsicProperty(java.lang.String,
* java.lang.Object)
*/
protected void setIntrinsicProperty( String propName, Object value )
{
if ( NAME_MEMBER.equals( propName ) )
columnName = (String) value;
else if ( EXPRESSION_MEMBER.equals( propName ) )
expression = (String) value;
else if ( DATA_TYPE_MEMBER.equals( propName ) )
dataType = (String) value;
else if ( DISPLAY_NAME_MEMBER.equalsIgnoreCase( propName ) )
columnDisplayName = (String) value;
else if ( AGGREGATEON_MEMBER.equals( propName )
|| AGGREGRATEON_MEMBER.equals( propName ) )
{
List tmpList = null;
if ( value instanceof String )
{
tmpList = new ArrayList( );
tmpList.add( value );
}
else if ( value instanceof List )
tmpList = (List) value;
aggregrateOn = tmpList;
}
else if ( AGGREGATEON_FUNCTION_MEMBER.equalsIgnoreCase( propName ) )
aggregateFunc = (String) value;
else if ( ARGUMENTS_MEMBER.equalsIgnoreCase( propName ) )
arguments = (List) value;
else if ( FILTER_MEMBER.equalsIgnoreCase( propName ) )
filterexpr = (String) value;
else
assert false;
}
/**
* Returns the column name.
*
* @return the column name
* @deprecated using {@link #getName()} instead.
*/
public String getColumnName( )
{
return getName( );
}
/**
* Returns the column name.
*
* @return the column name
*/
public String getName( )
{
return (String) getProperty( null, NAME_MEMBER );
}
/**
* Returns column display name.
*
* @return column display name.
*/
public String getDisplayName( )
{
return (String) getProperty( null, ComputedColumn.DISPLAY_NAME_MEMBER );
}
/**
* Sets the column display name.
*
* @param columnDisplayName
* the column display name to set.
*
*/
public void setDisplayName( String columnDisplayName )
{
setProperty( ComputedColumn.DISPLAY_NAME_MEMBER, columnDisplayName );
}
/**
* Sets the column name.
*
* @param columnName
* the column name to set
* @deprecated using {@link #setName(String)} instead.
*/
public void setColumnName( String columnName )
{
setName( columnName );
}
/**
* Sets the column name
*
* @param name
* the column name to set.
*/
public void setName( String name )
{
setProperty( NAME_MEMBER, name );
}
/**
* Returns the expression to compute.
*
* @return the expression to compute
*/
public String getExpression( )
{
return (String) getProperty( null, EXPRESSION_MEMBER );
}
/**
* Sets the expression.
*
* @param expression
* the expression to set
*/
public void setExpression( String expression )
{
setProperty( EXPRESSION_MEMBER, expression );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.Structure#handle(org.eclipse.birt.report.model.api.SimpleValueHandle,
* int)
*/
public StructureHandle handle( SimpleValueHandle valueHandle, int index )
{
return new ComputedColumnHandle( valueHandle, index );
}
/**
* Validates this structure. The following are the rules:
* <ul>
* <li>The column name is required.
* </ul>
*
* @see org.eclipse.birt.report.model.core.Structure#validate(Module,
* org.eclipse.birt.report.model.core.DesignElement)
*/
public List validate( Module module, DesignElement element )
{
List list = super.validate( module, element );
String columnName = getName( );
if ( StringUtil.isBlank( columnName ) )
{
list.add( new PropertyValueException( element, getDefn( )
.getMember( NAME_MEMBER ), columnName,
PropertyValueException.DESIGN_EXCEPTION_VALUE_REQUIRED ) );
}
return list;
}
/**
* Returns the data type of this column. The possible values are defined in
* {@link org.eclipse.birt.report.model.api.elements.DesignChoiceConstants},
* and they are:
* <ul>
* <li>COLUMN_DATA_TYPE_ANY
* <li>COLUMN_DATA_TYPE_INTEGER
* <li>COLUMN_DATA_TYPE_STRING
* <li>COLUMN_DATA_TYPE_DATETIME
* <li>COLUMN_DATA_TYPE_DECIMAL
* <li>COLUMN_DATA_TYPE_FLOAT
* <li>COLUMN_DATA_TYPE_STRUCTURE
* <li>COLUMN_DATA_TYPE_TABLE
* </ul>
*
* @return the data type of this column.
*/
public String getDataType( )
{
return (String) getProperty( null, DATA_TYPE_MEMBER );
}
/**
* Sets the data type of this column. The allowed values are defined in
* {@link org.eclipse.birt.report.model.api.elements.DesignChoiceConstants},
* and they are:
* <ul>
* <li>COLUMN_DATA_TYPE_ANY
* <li>COLUMN_DATA_TYPE_INTEGER
* <li>COLUMN_DATA_TYPE_STRING
* <li>COLUMN_DATA_TYPE_DATETIME
* <li>COLUMN_DATA_TYPE_DECIMAL
* <li>COLUMN_DATA_TYPE_FLOAT
* <li>COLUMN_DATA_TYPE_STRUCTURE
* <li>COLUMN_DATA_TYPE_TABLE
* </ul>
*
* @param dataType
* the data type to set
*/
public void setDataType( String dataType )
{
setProperty( DATA_TYPE_MEMBER, dataType );
}
/**
* Returns the aggregrateOn expression to compute.
*
* @return the aggregrateOn expression to compute.
*
* @deprecated by {@link #getAggregateOn()}
*/
public String getAggregrateOn( )
{
return getAggregateOn( );
}
/**
* Sets the aggregateOn expression.
*
* @param aggregateOn
* the aggregateOn expression to set
* @deprecated by {@link #setAggregateOn(String)}
*
*/
public void setAggregrateOn( String aggregateOn )
{
setAggregateOn( aggregateOn );
}
/**
* Returns the aggregateOn expression to compute.
*
* @return the aggregateOn expression to compute.
*
*/
public String getAggregateOn( )
{
List aggres = getAggregateOnList( );
if ( aggres == null || aggres.isEmpty( ) )
return null;
return (String) aggres.get( 0 );
}
/**
* Returns the list containing levels to be aggregated on.
*
* @return the list containing levels to be aggregated on
*/
public List getAggregateOnList( )
{
return (List) getProperty( null, AGGREGATEON_MEMBER );
}
/**
* Sets the aggregateOn expression.
*
* @param aggregateOn
* the aggregateOn expression to set
*/
public void setAggregateOn( String aggregateOn )
{
setProperty( AGGREGATEON_MEMBER, aggregateOn );
}
/**
* Adds an aggregate level to the list.
*
* @param aggreValue
* the aggregate name. For listing elements, this can be "All" or
* the name of a single group.
*/
public void addAggregateOn( String aggreValue )
{
if ( aggregrateOn == null )
aggregrateOn = new ArrayList( );
aggregrateOn.add( aggreValue );
}
/**
* Removes an aggregate level from the list.
*
* @param aggreValue
* the aggregate name. For listing elements, this can be "All" or
* the name of a single group.
*/
public void removeAggregateOn( String aggreValue )
{
if ( aggregrateOn == null )
return;
aggregrateOn.remove( aggreValue );
}
/**
* Returns the expression used to define this computed column.
*
* @return the expression used to define this computed column
*/
public String getAggregateFunction( )
{
return (String) getProperty( null,
ComputedColumn.AGGREGATEON_FUNCTION_MEMBER );
}
/**
* Returns additional arguments to the aggregate function.
*
* @return a list containing additional arguments
*/
public List getArgumentList( )
{
return (List) getProperty( null, AGGREGATEON_MEMBER );
}
/**
* Returns the expression used to define this computed column.
*
* @return the expression used to define this computed column
*/
public String getFilterExpression( )
{
return (String) getProperty( null, ComputedColumn.FILTER_MEMBER );
}
/**
* Sets the expression used to define this computed column.
*
* @param expression
* the expression to set
* @throws SemanticException
* value required exception
*/
public void setAggregateFunction( String expression )
{
setProperty( ComputedColumn.AGGREGATEON_FUNCTION_MEMBER, expression );
}
/**
* Sets the expression used to define this computed column.
*
* @param expression
* the expression to set
* @throws SemanticException
* value required exception
*/
public void setFilterExpression( String expression )
{
setProperty( ComputedColumn.FILTER_MEMBER, expression );
}
}
|
package org.jsoupstream.example;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import org.jsoupstream.HtmlParser;
import org.jsoupstream.HtmlLexer;
public class TestParser {
public static void main(String[] args) {
InputStream css_is = null;
InputStream html_is = null;
char c = (char)0;
int count = 1;
int line = 1;
try
{
if ( args.length > 2 )
{
count = Integer.parseInt( args[2] );
}
// parse the CSS and create a parser 1 time only
css_is = new FileInputStream(args[0]);
HtmlParser parser = new HtmlParser(css_is);
css_is.close();
if ( args.length > 3 )
{
if ( args[3].startsWith( "min" ) || args[3].equalsIgnoreCase( "yes" ) )
{
parser.setMinimizeHtml( true );
}
}
for (int i = 0; i < count; i++)
{
if ( args[1].startsWith( "http" ) )
{
URL url = new URL( args[1] );
html_is = url.openStream();
}
else
{
html_is = new FileInputStream( args[1] );
}
HtmlLexer lexer = new HtmlLexer( html_is );
String result = parser.parse( lexer );
html_is.close();
System.out.print( result );
// parser must be reset if it to be reused
parser.reset();
}
} catch(Exception e) {
// if any I/O error occurs
System.err.println("ERROR: "+e.getMessage());
e.printStackTrace();
}
}
}
|
package org.openmole.plugin.task.netlogo;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.nlogo.api.CompilerException;
import org.nlogo.api.LogoException;
import org.nlogo.headless.HeadlessWorkspace;
import org.openmole.core.implementation.tools.VariableExpansion;
import org.openmole.core.model.data.IPrototype;
import org.openmole.core.model.execution.IProgress;
import org.openmole.core.model.data.IContext;
import org.openmole.misc.exception.InternalProcessingError;
import org.openmole.misc.exception.UserBadDataError;
import org.openmole.misc.workspace.Workspace;
import org.openmole.plugin.task.external.system.ExternalSystemTask;
import scala.Tuple2;
import scala.Tuple3;
/**
*
* @author reuillon
*/
public class NetLogoTask extends ExternalSystemTask {
Iterable<String> launchingCommands;
List<Tuple2<IPrototype, String>> inputBinding = new LinkedList<Tuple2<IPrototype, String>>();
List<Tuple3<String, IPrototype, Boolean>> outputBinding = new LinkedList<Tuple3<String, IPrototype, Boolean>>();
String relativeScriptPath;
public NetLogoTask(String name,
File workspace,
String sriptName,
Iterable<String> launchingCommands) throws UserBadDataError, InternalProcessingError {
super(name);
this.relativeScriptPath = workspace.getName() + "/" + sriptName;
addResource(workspace);
this.launchingCommands = launchingCommands;
}
public NetLogoTask(String name,
String workspace,
String sriptName,
Iterable<String> launchingCommands) throws UserBadDataError, InternalProcessingError {
this(name, new File(workspace), sriptName, launchingCommands);
}
@Override
public void process(IContext context, IProgress progress) throws UserBadDataError, InternalProcessingError, InterruptedException {
try {
File tmpDir = Workspace.instance().newDir("netLogoTask");
prepareInputFiles(context, progress, tmpDir);
File script = new File(tmpDir, relativeScriptPath);
HeadlessWorkspace workspace = HeadlessWorkspace.newInstance();
try {
workspace.open(script.getAbsolutePath());
for (Tuple2<IPrototype, String> inBinding : getInputBinding()) {
Object val = context.value(inBinding._1()).get();
workspace.command("set " + inBinding._2() + " " + val.toString());
}
for (String cmd : launchingCommands) {
workspace.command(VariableExpansion.expandData(context, cmd));
}
for (Tuple3<String, IPrototype, Boolean> outBinding : getOutputBinding()) {
Object outputValue = workspace.report(outBinding._1());
if (!outBinding._3()) {
context.add(outBinding._2(), outputValue);
} else {
AbstractCollection netlogoCollection = (AbstractCollection) outputValue;
Object array = Array.newInstance(outBinding._2().type().erasure().getComponentType(), netlogoCollection.size());
Iterator it = netlogoCollection.iterator();
for(int i = 0; i < netlogoCollection.size(); i++) {
Array.set(array, i, it.next());
}
}
}
fetchOutputFiles(context, progress, tmpDir);
} catch (CompilerException ex) {
throw new UserBadDataError(ex);
} catch (LogoException ex) {
throw new InternalProcessingError(ex);
} finally {
workspace.dispose();
}
} catch (IOException e) {
throw new InternalProcessingError(e);
}
}
public NetLogoTask addNetLogoInput(IPrototype prototype) {
addInput(prototype);
return this;
}
public NetLogoTask addNetLogoInput(IPrototype prototype, String binding) {
inputBinding.add(new Tuple2<IPrototype, String>(prototype, binding));
super.addInput(prototype);
return this;
}
public NetLogoTask addNetLogoOutput(String binding, IPrototype prototype) {
addNetLogoOutput(binding, prototype, false);
return this;
}
public NetLogoTask addNetLogoOutput(String binding, IPrototype prototype, Boolean toArray) {
outputBinding.add(new Tuple3<String, IPrototype, Boolean>(binding, prototype, toArray));
super.addOutput(prototype);
return this;
}
private List<Tuple2<IPrototype, String>> getInputBinding() {
return inputBinding;
}
private List<Tuple3<String, IPrototype, Boolean>> getOutputBinding() {
return outputBinding;
}
}
|
package org.jtrfp.trcl;
import java.awt.geom.Point2D;
import org.jtrfp.trcl.core.TriangleVertexWindow;
import org.jtrfp.trcl.gpu.DynamicTexture;
public class TexturePageAnimator implements Tickable{
private final TriangleVertexWindow vertexWindow;
private final int gpuTVIndex;
private String debugName = "[not set]";
private final DynamicTexture dynamicTexture;
private int currentTexturePage;
private Double u,v;
public TexturePageAnimator(DynamicTexture at, TriangleVertexWindow vw, int gpuTVIndex) {
this.vertexWindow =vw;
this.gpuTVIndex =gpuTVIndex;
dynamicTexture =at;
}//end constructor
@Override
public void tick() {
try{final int newTexturePage = dynamicTexture.getCurrentTexturePage();
if(currentTexturePage != newTexturePage){//TODO: Cache vertexWindow var
vertexWindow.textureIDLo .set(gpuTVIndex, (byte)(newTexturePage & 0xFF));
vertexWindow.textureIDMid.set(gpuTVIndex, (byte)((newTexturePage >> 8) & 0xFF));
vertexWindow.textureIDHi .set(gpuTVIndex, (byte)((newTexturePage >> 16) & 0xFF));
//Update U,V coords if they are expected to change.
final Point2D.Double size = dynamicTexture.getSize();
if(u!=null)
vertexWindow.u.set(gpuTVIndex, (short) Math.rint(size.getX() * u));
if(v!=null)
vertexWindow.v.set(gpuTVIndex, (short) Math.rint(size.getY() * v));
currentTexturePage = newTexturePage;
vertexWindow.flush();
}
}catch(Exception e){e.printStackTrace();}
}//end tick()
public TexturePageAnimator setDebugName(String debugName) {
this.debugName=debugName;
return this;
}//end setDebugName(...)
/**
* @return the debugName
*/
public String getDebugName() {
return debugName;
}//end getDebugName()
public double getU() {
return u;
}
public void setU(double u) {
this.u = u;
}
public double getV() {
return v;
}
public void setV(double v) {
this.v = v;
}
}//end TextureIDAnimator
|
package com.planetmayo.debrief.satc.model.contributions;
import java.awt.Color;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.jfree.data.statistics.Regression;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesDataItem;
import org.mwc.debrief.track_shift.controls.ZoneChart;
import org.mwc.debrief.track_shift.controls.ZoneChart.ColorProvider;
import org.mwc.debrief.track_shift.controls.ZoneChart.Zone;
import org.mwc.debrief.track_shift.views.BaseStackedDotsView;
import org.mwc.debrief.track_shift.views.StackedDotHelper;
import org.mwc.debrief.track_shift.zig_detector.Precision;
import org.mwc.debrief.track_shift.zig_detector.target.ILegStorer;
import org.mwc.debrief.track_shift.zig_detector.target.IZigStorer;
import org.mwc.debrief.track_shift.zig_detector.target.ZigDetector;
import com.planetmayo.debrief.satc.model.GeoPoint;
import com.planetmayo.debrief.satc.model.generator.IContributions;
import com.planetmayo.debrief.satc.model.legs.CoreRoute;
import com.planetmayo.debrief.satc.model.legs.LegType;
import com.planetmayo.debrief.satc.model.manager.ISolversManager;
import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException;
import com.planetmayo.debrief.satc.model.states.BoundedState;
import com.planetmayo.debrief.satc.model.states.LocationRange;
import com.planetmayo.debrief.satc.model.states.ProblemSpace;
import com.planetmayo.debrief.satc.model.states.State;
import com.planetmayo.debrief.satc.util.GeoSupport;
import com.planetmayo.debrief.satc.util.MathUtils;
import com.planetmayo.debrief.satc.util.ObjectUtils;
import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator;
import com.planetmayo.debrief.satc.zigdetector.LegOfData;
import com.planetmayo.debrief.satc_rcp.SATC_Activator;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
import MWC.Utilities.TextFormatting.GMTDateFormat;
import junit.framework.TestCase;
public class BearingMeasurementContribution extends
CoreMeasurementContribution<BearingMeasurementContribution.BMeasurement>
{
private static final long serialVersionUID = 1L;
public static final String BEARING_ERROR = "bearingError";
public static final String RUN_MDA = "autoDetect";
public static interface MDAResultsListener
{
public void startingSlice(String contName);
public void ownshipLegs(String contName, ArrayList<BMeasurement> bearings,
List<LegOfData> ownshipLegs, ArrayList<HostState> hostStates);
public void sliced(String contName,
ArrayList<StraightLegForecastContribution> arrayList);
}
/**
* the allowable bearing error (in radians)
*
*/
private Double bearingError = 0d;
/**
* flag for whether this contribution should run an MDA on the data
*
*/
private boolean runMDA = true;
/**
* store the ownship states, if possible. We use this to run the manoeuvre
* detection algorithm
*/
private ArrayList<HostState> states;
/**
* array of listeners interested in MDA
*
*/
private transient ArrayList<MDAResultsListener> _listeners = null;
/**
* store any sliced legs
*
*/
private transient List<LegOfData> ownshipLegs;
@Override
public void actUpon(ProblemSpace space) throws IncompatibleStateException
{
// ok, here we really go for it!
Iterator<BMeasurement> iter = measurements.iterator();
// sort out a geometry factory
GeometryFactory factory = GeoSupport.getFactory();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement = iter.next();
// is it active?
if (measurement.isActive())
{
// ok, create the polygon for this measurement
GeoPoint origin = measurement.origin;
double bearing = measurement.bearingAngle;
double range = measurement.range;
// sort out the left/right edges
double leftEdge = bearing - bearingError;
double rightEdge = bearing + bearingError;
// ok, generate the polygon
Coordinate[] coords = new Coordinate[5];
// start off with the origin
final double lon = origin.getLon();
final double lat = origin.getLat();
coords[0] = new Coordinate(lon, lat);
// create a utility object to help with calcs
GeodeticCalculator calc = GeoSupport.createCalculator();
// now the top-left
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(leftEdge)),
range);
Point2D dest = calc.getDestinationGeographicPoint();
coords[1] = new Coordinate(dest.getX(), dest.getY());
// now the centre bearing
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(bearing)),
range);
dest = calc.getDestinationGeographicPoint();
coords[2] = new Coordinate(dest.getX(), dest.getY());
// now the top-right
calc.setStartingGeographicPoint(new Point2D.Double(lon, lat));
calc.setDirection(Math.toDegrees(MathUtils.normalizeAngle2(rightEdge)),
range);
dest = calc.getDestinationGeographicPoint();
coords[3] = new Coordinate(dest.getX(), dest.getY());
// and back to the start
coords[4] = new Coordinate(coords[0]);
// ok, store the coordinates
CoordinateArraySequence seq = new CoordinateArraySequence(coords);
// and construct the bounded location object
LinearRing ls = new LinearRing(seq, factory);
Polygon poly = new Polygon(ls, null, factory);
LocationRange lr = new LocationRange(poly);
// do we have a bounds at this time?
BoundedState thisState = space.getBoundedStateAt(measurement.time);
if (thisState == null)
{
// ok, do the bounds
thisState = new BoundedState(measurement.time);
// and store it
space.add(thisState);
}
// ok, override any existing color for this state, if we have one
if (measurement.getColor() != null)
thisState.setColor(measurement.getColor());
// well, if we didn't - we do now! Apply it!
thisState.constrainTo(lr);
LineString bearingLine = GeoSupport.getFactory().createLineString(
new Coordinate[] { coords[0], coords[2] });
thisState.setBearingLine(bearingLine);
// also store the bearing value in the state - since it's of value in
// other processes (1959)
thisState.setBearingValue(bearing);
}
}
// hmm, do we run the MDA?
if (getAutoDetect())
{
// get a few bounded states
Collection<BoundedState> testStates = space.getBoundedStatesBetween(
this.getStartDate(), this.getFinishDate());
int ctr = 0;
for (Iterator<BoundedState> iterator = testStates.iterator(); iterator
.hasNext();)
{
BoundedState boundedState = iterator.next();
ctr++;
if (ctr >= 0 && ctr <= 3)
{
boundedState.setMemberOf("test MDA leg");
}
}
}
}
@Override
protected double cumulativeScoreFor(CoreRoute route)
{
double bearingError = this.bearingError == null ? 0 : this.bearingError;
if (!isActive() || route.getType() == LegType.ALTERING || bearingError == 0)
{
return 0;
}
double res = 0;
int count = 0;
for (BMeasurement measurement : measurements)
{
Date dateMeasurement = measurement.getDate();
if (dateMeasurement.compareTo(route.getStartTime()) >= 0
&& dateMeasurement.compareTo(route.getEndTime()) <= 0)
{
State state = route.getStateAt(dateMeasurement);
if (state != null && state.getLocation() != null)
{
GeodeticCalculator calculator = GeoSupport.createCalculator();
calculator.setStartingGeographicPoint(measurement.origin.getLon(),
measurement.origin.getLat());
calculator.setDestinationGeographicPoint(state.getLocation().getX(),
state.getLocation().getY());
double radians = MathUtils.normalizeAngle(Math.toRadians(calculator
.getAzimuth()));
double angleDiff = MathUtils.angleDiff(measurement.bearingAngle,
radians, true);
// make the error a proportion of the bearing error
angleDiff = angleDiff / (this.getBearingError());
// store the error
state.setScore(this, angleDiff * this.getWeight() / 10);
// and prepare the cumulative score
double thisError = angleDiff * angleDiff;
res += thisError;
count++;
}
}
}
if (count > 0)
{
res = Math.sqrt(res / count) / bearingError;
}
return res;
}
public void addMeasurement(double lat, double lon, Date date, double brg,
double range)
{
GeoPoint loc = new GeoPoint(lat, lon);
BMeasurement measure = new BMeasurement(loc, brg, date, range);
addMeasurement(measure);
}
public void loadFrom(List<String> lines)
{
// load from this source
// ;;IGNORE YYMMDD HHMMSS IGNORE IGNORE LAT_DEG LAT_MIN LAT_SEC LAT_HEM
// LONG_DEG LONG_MIN LONG_SEC LONG_HEM BEARING MAX_RNG
// ;SENSOR: 100112 121329 SENSOR @A 0 3 57.38 S 30 0 8.65 W 1.5 15000
// Read File Line By Line
for (String strLine : lines)
{
// hey, is this a comment line?
if (strLine.startsWith(";;"))
{
continue;
}
// ok, get parseing it
String[] elements = strLine.split("\\s+");
// now the date
String date = elements[1];
// and the time
String time = elements[2];
String latDegs = elements[5];
String latMins = elements[6];
String latSecs = elements[7];
String latHemi = elements[8];
String lonDegs = elements[9];
String lonMins = elements[10];
String lonSecs = elements[11];
String lonHemi = elements[12];
// and the beraing
String bearing = elements[13];
// and the range
String range = elements[14];
// ok,now construct the date=time
Date theDate = ObjectUtils.safeParseDate(new GMTDateFormat(
"yyMMdd HHmmss"), date + " " + time);
// and the location
double lat = Double.valueOf(latDegs) + Double.valueOf(latMins) / 60d
+ Double.valueOf(latSecs) / 60d / 60d;
if (latHemi.toUpperCase().equals("S"))
lat = -lat;
double lon = Double.valueOf(lonDegs) + Double.valueOf(lonMins) / 60d
+ Double.valueOf(lonSecs) / 60d / 60d;
if (lonHemi.toUpperCase().equals("W"))
lon = -lon;
GeoPoint theLoc = new GeoPoint(lat, lon);
double angle = Math.toRadians(Double.parseDouble(bearing));
BMeasurement measure = new BMeasurement(theLoc, angle, theDate,
Double.parseDouble(range));
addMeasurement(measure);
}
this.setBearingError(Math.toRadians(3d));
}
/**
* get the bearing error
*
* @param errorRads
* (in radians)
*/
public Double getBearingError()
{
return bearingError;
}
public List<HostState> getHostState()
{
return states;
}
/**
* provide the bearing error
*
* @return (in radians)
*/
public void setBearingError(Double errorRads)
{
// IDIOT CHECK - CHECK WE HAVEN'T ACCIDENTALLY GOT DEGREES
if (errorRads > 2)
SATC_Activator.log(Status.WARNING,
"Looks like error is being presented in Degs", null);
Double old = bearingError;
this.bearingError = errorRads;
firePropertyChange(BEARING_ERROR, old, errorRads);
fireHardConstraintsChange();
}
public void setAutoDetect(boolean onAuto)
{
boolean previous = runMDA;
runMDA = onAuto;
firePropertyChange(RUN_MDA, previous, onAuto);
firePropertyChange(HARD_CONSTRAINTS, previous, onAuto);
}
public boolean getAutoDetect()
{
return runMDA;
}
/**
* utility class for storing a measurement
*
* @author ian
*
*/
public static class BMeasurement extends
CoreMeasurementContribution.CoreMeasurement
{
private static final double MAX_RANGE_METERS = RangeForecastContribution.MAX_SELECTABLE_RANGE_M;
private final GeoPoint origin;
private final double bearingAngle;
/**
* the (optional) maximum range for this measurement
*
*/
private final double range;
public BMeasurement(GeoPoint loc, double bearing, Date time, Double range)
{
super(time);
this.origin = loc;
this.bearingAngle = MathUtils.normalizeAngle(bearing);
// tidying up. Give the maximum possible range for this bearing if the
// data is missing
this.range = range == null ? MAX_RANGE_METERS : range;
}
public double getBearingRads()
{
return bearingAngle;
}
}
protected long[] getTimes()
{
long[] res = new long[states.size()];
int ctr = 0;
Iterator<HostState> iter = states.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.time;
}
return res;
}
protected double[] getCourses()
{
double[] res = new double[states.size()];
Iterator<HostState> iter = states.iterator();
int ctr = 0;
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.courseDegs;
}
return res;
}
protected double[] getSpeeds()
{
double[] res = new double[states.size()];
Iterator<HostState> iter = states.iterator();
int ctr = 0;
while (iter.hasNext())
{
BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
res[ctr++] = hostState.speedKts;
}
return res;
}
public static class HostState
{
final public long time;
final public double courseDegs;
final public double speedKts;
final public double dLat;
final public double dLong;
public HostState(long time, double courseDegs, double speedKts,
double dLat, double dLong)
{
this.time = time;
this.courseDegs = courseDegs;
this.speedKts = speedKts;
this.dLat = dLat;
this.dLong = dLong;
}
}
public void sliceOwnship(final IContributions contributions)
{
// ok share the good news - we're about to start
if (_listeners != null)
{
Iterator<MDAResultsListener> iter = _listeners.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.MDAResultsListener thisL = (BearingMeasurementContribution.MDAResultsListener) iter
.next();
thisL.startingSlice(this.getName());
}
}
TimeSeries ownshipCourseSeries = getOwnshipCourses();
ColorProvider blueProv = new ZoneChart.ColorProvider()
{
@Override
public java.awt.Color getZoneColor()
{
return java.awt.Color.blue;
}
};
ArrayList<Zone> slicedZones = StackedDotHelper.sliceOwnship(ownshipCourseSeries,
blueProv);
if (ownshipLegs != null)
{
ownshipLegs.clear();
}
else
{
ownshipLegs = new ArrayList<LegOfData>();
}
int ctr = 1;
for(Zone zone: slicedZones)
{
final long startT = zone.getStart();
final long endT = zone.getEnd();
LegOfData newLeg = new LegOfData("Leg-" + ctr++, startT, endT);
System.out.println("Leg:" + newLeg);
ownshipLegs.add(newLeg);
}
// ok, share the ownship legs
// ok, slicing done!
if (_listeners != null)
{
Iterator<MDAResultsListener> iter = _listeners.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.MDAResultsListener thisL = (BearingMeasurementContribution.MDAResultsListener) iter
.next();
thisL.ownshipLegs(this.getName(), this.getMeasurements(), ownshipLegs,
states);
}
}
}
/** collate a list of time stamped course values
*
* @return
*/
private TimeSeries getOwnshipCourses()
{
final TimeSeries res = new TimeSeries("OS_Courses");
final Iterator<HostState> iter = states.iterator();
while (iter.hasNext())
{
final BearingMeasurementContribution.HostState hostState =
(BearingMeasurementContribution.HostState) iter.next();
res.add(new TimeSeriesDataItem(new FixedMillisecond(hostState.time),
hostState.courseDegs));
}
return res;
}
public void runMDA(final IContributions contributions)
{
// ok, we've got to find the ownship data, somehow :-(
if ((states == null) || (states.size() == 0))
{
return;
}
// decide if we are going to split at ownship and target zigs, or just
// target zigs
final boolean justTargetZigs = false;
// ok, now ditch any straight leg contributions that we generated
ditchExistingStraightLegContributions(contributions);
// create object that can store the new legs
IContributions zigConts, legConts;
if (justTargetZigs)
{
zigConts = contributions;
legConts = null;
}
else
{
legConts = contributions;
zigConts = null;
}
MyLegStorer legStorer = new MyLegStorer(legConts, this.getMeasurements(),
this.getName());
MyZigStorer zigStorer = new MyZigStorer(zigConts, this.getMeasurements(),
this.getName(), states.get(0).time, states.get(states.size() - 1).time);
// ok, now collate the bearing data
ZigDetector detector = new ZigDetector();
// whether we break up bearing data in blocks of ownship course
// or not. In 2019, the algorithm is working better when it
// just receives all of the bearing ata in one chunk
final boolean sliceByOwnship = false;
if(sliceByOwnship)
{
// first slice the bearing data into ownship legs, then identify
// target legs within these chunks
sliceByOwnshipLegs(legStorer, zigStorer, detector);
}
else
{
// just pass all the data to the algorithm as one big chunk
sliceAllData(legStorer, zigStorer, detector);
}
// ok, slicing done!
if (_listeners != null)
{
final Iterator<MDAResultsListener> iter = _listeners.iterator();
while (iter.hasNext())
{
final BearingMeasurementContribution.MDAResultsListener thisL = (BearingMeasurementContribution.MDAResultsListener) iter
.next();
if (justTargetZigs)
{
thisL.sliced(this.getName(), zigStorer.getSlices());
}
else
{
thisL.sliced(this.getName(), legStorer.getSlices());
}
}
}
}
public void sliceAllData(final MyLegStorer legStorer, final MyZigStorer zigStorer,
final ZigDetector detector)
{
List<Long> thisLegTimes = new ArrayList<Long>();
List<Double> thisLegBearings = new ArrayList<Double>();
ArrayList<BMeasurement> meas = getMeasurements();
Iterator<BMeasurement> iter = meas.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement =
(BearingMeasurementContribution.BMeasurement) iter.next();
thisLegTimes.add(measurement.getDate().getTime());
thisLegBearings.add(Math.toDegrees(measurement.bearingAngle));
}
final double zigTolerance = 0.000001;
ISolversManager solversManager = SATC_Activator.getDefault().getService(
ISolversManager.class, false);
final Precision precision;
if (solversManager != null)
{
precision = solversManager.getActiveSolver().getPrecision();
}
else
{
precision = Precision.MEDIUM;
}
final double zigScore = BaseStackedDotsView.getPrecision(precision);
detector.sliceThis2(SATC_Activator.getDefault().getLog(),
SATC_Activator.PLUGIN_ID, "some name", legStorer, zigScore,
zigTolerance, thisLegTimes, thisLegBearings);
}
public void ditchExistingStraightLegContributions(
final IContributions contributions)
{
Iterator<BaseContribution> ditchIter = contributions.iterator();
ArrayList<StraightLegForecastContribution> toRemove = new ArrayList<StraightLegForecastContribution>();
while (ditchIter.hasNext())
{
BaseContribution baseContribution = (BaseContribution) ditchIter.next();
if (baseContribution instanceof StraightLegForecastContribution)
{
StraightLegForecastContribution sfl = (StraightLegForecastContribution) baseContribution;
if (sfl.getAutoGenBy().equals(getName()))
{
toRemove.add(sfl);
}
}
}
// ditch any that we did find
Iterator<StraightLegForecastContribution> remover = toRemove.iterator();
while (remover.hasNext())
{
StraightLegForecastContribution toDitch = (StraightLegForecastContribution) remover
.next();
contributions.removeContribution(toDitch);
}
}
private boolean checkForTargetZig(String legName, List<Long> lastLegTimes,
List<Double> lastLegBearings, List<Long> thisLegTimes,
List<Double> thisLegBearings)
{
boolean res = false;
// ok, what's the 1936 range?
NumberFormat dp2 = new DecimalFormat("0.00");
// ok, trim the leg 1 bearings
int leg1Len = Math.min(6, lastLegTimes.size());
int leg2Len = Math.min(6, thisLegTimes.size());
// drop out if either are too small
if ((leg1Len >= 3) && (leg2Len >= 3))
{
// OSA 1
double leg1Bearing = lastLegBearings.get(lastLegBearings.size() - 1);
double leg1Speed = speedAt(lastLegTimes.get(lastLegTimes.size() - 1));
double leg1Course = courseAt(lastLegTimes.get(lastLegTimes.size() - 1));
double leg1RelBrg = leg1Course - leg1Bearing ;
double osa1 = leg1Speed * Math.sin(Math.toRadians(leg1RelBrg));
// OSA 2
double leg2Bearing = thisLegBearings.get(0);
double leg2Speed = speedAt(thisLegTimes.get(0));
double leg2Course = courseAt(thisLegTimes.get(0));
double leg2RelBrg = leg2Course - leg2Bearing;
double osa2 = leg2Speed * Math.sin(Math.toRadians(leg2RelBrg));
// dOSA
double dOSA = osa2 - osa1;
// bearing rate
double l1BearingRate = bearingRateFor(
lastLegTimes.subList(lastLegTimes.size() - leg1Len,
lastLegTimes.size() - 1),
lastLegBearings.subList(lastLegTimes.size() - leg1Len,
lastLegTimes.size() - 1));
double l2BearingRate = bearingRateFor(thisLegTimes.subList(0, leg2Len),
thisLegBearings.subList(0, leg2Len));
double deltaBRate = l1BearingRate - l2BearingRate; // (order changed, according to Iain doc)
// and the range
double rng1936m = 1770.28 * dOSA / deltaBRate;
// ok, what's the bearing rate for this range?
// double pBoot = 1770.28 * dOSA / rng1936m;
// hmm, what are the two TSAs?
double l1RSA = (l1BearingRate * rng1936m) / 1770.28;
double l1TSA = osa1 - l1RSA;
double l2RSA = (l2BearingRate * rng1936m) / 1770.28;
double l2TSA = osa2 - l2RSA;
// ok, make a decision - we need a dTSA of less than the threshold,
// with a +ve range estimate there to be no zig.
double deltaTSA = Math.abs(Math.abs(l2TSA) - Math.abs(l1TSA));
final double deltaTSA_Threshold = 4;
if((deltaTSA <= deltaTSA_Threshold)&&(rng1936m > 0))
res = false;
else
res = true;
// ok, output diagnostics
SATC_Activator.log(Status.INFO, "turning onto:" + legName + " range:" + (int)rng1936m +
" osa1:" + dp2.format(osa1) + " osa2:" + dp2.format(osa2) +
" dOSA:" + dp2.format(dOSA) +
" l1Rate:" + dp2.format(l1BearingRate) + " l2Rate:" + dp2.format(l2BearingRate) +
" dRate:" + dp2.format(deltaBRate) +
" l1TSA:" + dp2.format(l1TSA) +
" l2TSA:" + dp2.format(l2TSA)+
" is Zig:" + res
, null);
}
return res;
}
private double bearingRateFor(List<Long> legTimes, List<Double> legBearings)
{
// how large is the data?
final int len = legTimes.size();
// keep track of the max/min bearings
double minBrg = Double.MAX_VALUE;
double maxBrg = Double.MIN_NORMAL;
long timeStart = legTimes.get(0);
// store the data
double[][] data = new double[len][2];
for (int i = 0; i < len; i++)
{
data[i][0] = (legTimes.get(i) - timeStart) / (1000 * 60d); // convert to mins
Double thisBrg = legBearings.get(i);
if(thisBrg < minBrg)
minBrg = thisBrg;
if(thisBrg > maxBrg)
maxBrg = thisBrg;
data[i][1] = thisBrg;
}
// ok, we need to check that we don't pass through zero in this data.
if(maxBrg - minBrg > 180)
{
// ok, we need to put them into the same cycle (180..540)
for (int i = 0; i < len; i++)
{
double thisVal = data[i][1];
if(thisVal < 180)
{
thisVal += 360;
data[i][1] = thisVal;
}
}
}
// calculate the line
double[] res = Regression.getOLSRegression(data);
// and the rate
return res[1];
}
private double speedAt(long time)
{
double res = -1;
final Iterator<HostState> iter = states.iterator();
while (iter.hasNext())
{
final BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
if (hostState.time >= time)
{
res = hostState.speedKts;
break;
}
}
return res;
}
private double courseAt(long time)
{
double res = -1;
final Iterator<HostState> iter = states.iterator();
while (iter.hasNext())
{
final BearingMeasurementContribution.HostState hostState = (BearingMeasurementContribution.HostState) iter
.next();
if (hostState.time >= time)
{
res = hostState.courseDegs;
break;
}
}
return res;
}
public List<LegOfData> getOwnshipLegs()
{
return ownshipLegs;
}
public void addSliceListener(MDAResultsListener listener)
{
if (_listeners == null)
_listeners = new ArrayList<MDAResultsListener>();
_listeners.add(listener);
}
public void removeSliceListener(MDAResultsListener listener)
{
if (_listeners != null)
_listeners.remove(listener);
}
private static class MyLegStorer extends MyStorer implements ILegStorer
{
public MyLegStorer(final IContributions theConts,
ArrayList<BMeasurement> cuts, String genName)
{
super(theConts, cuts, genName);
}
}
private static class MyZigStorer extends MyStorer implements IZigStorer
{
private long _startTime;
private final long _endTime;
public MyZigStorer(final IContributions theConts,
final ArrayList<BMeasurement> cuts, final String genName,
final long startTime, final long endTime)
{
super(theConts, cuts, genName);
_startTime = startTime;
_endTime = endTime;
}
@Override
public void storeZig(String scenarioName, long tStart, long tEnd,
double rms)
{
storeLeg(scenarioName, _startTime, tStart, rms);
// and move foward the end time
_startTime = tEnd;
}
@Override
public ArrayList<StraightLegForecastContribution> getSlices()
{
finish();
return super.getSlices();
}
@Override
public void finish()
{
// ok, just check if there is a missing last leg
if (_startTime != Long.MIN_VALUE)
{
// ok, append the last leg
storeLeg(null, _startTime, _endTime, 0);
_startTime = Long.MIN_VALUE;
}
}
}
private static class MyStorer
{
int ctr = 1;
protected ArrayList<StraightLegForecastContribution> slices = new ArrayList<StraightLegForecastContribution>();
protected final IContributions _contributions;
protected final ArrayList<BMeasurement> _cuts;
protected final String _genName;
public MyStorer(final IContributions theConts,
ArrayList<BMeasurement> cuts, String genName)
{
_contributions = theConts;
_cuts = cuts;
_genName = genName;
}
public ArrayList<StraightLegForecastContribution> getSlices()
{
return slices;
}
private Color colorAt(Date date)
{
Color res = null;
Iterator<BMeasurement> iter = _cuts.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement = (BearingMeasurementContribution.BMeasurement) iter
.next();
// check if it's on or after the supplied date
if (!measurement.getDate().before(date))
{
res = measurement.getColor();
}
}
return res;
}
public void storeLeg(String scenarioName, long tStart, long tEnd, double rms)
{
String name = "Tgt-" + ctr++;
SATC_Activator.log(Status.INFO, " FOUND LEG FROM " + new Date(tStart)
+ " - " + new Date(tEnd), null);
StraightLegForecastContribution slf = new CompositeStraightLegForecastContribution();
slf.setStartDate(new Date(tStart));
slf.setAutoGenBy(_genName);
slf.setFinishDate(new Date(tEnd));
slf.setColor(colorAt(slf.getStartDate()));
slf.setActive(true);
slf.setName(name);
if (_contributions != null)
{
_contributions.addContribution(slf);
}
slices.add(slf);
}
}
public void addState(final HostState newState)
{
// check we have our states
if (states == null)
states = new ArrayList<HostState>();
// and store this new one
states.add(newState);
}
public void sliceByOwnshipLegs(MyLegStorer legStorer, MyZigStorer zigStorer,
ZigDetector detector)
{
// get ready to remember the previous leg
List<Long> lastLegTimes = null;
List<Double> lastLegBearings = null;
// ok, work through the legs. In the absence of a Discrete
// Optimisation algorithm we're taking a brute force approach.
// Hopefully we can find an optimised alternative to this.
for (final Iterator<LegOfData> iterator2 = ownshipLegs.iterator(); iterator2
.hasNext();)
{
final LegOfData thisLeg = iterator2.next();
// ok, slice the data for this leg
long legStart = thisLeg.getStart();
long legEnd = thisLeg.getEnd();
// trim the start/end to the sensor data
legStart = Math.max(legStart, getStartDate().getTime());
legEnd = Math.min(legEnd, getFinishDate().getTime());
List<Long> thisLegTimes = new ArrayList<Long>();
List<Double> thisLegBearings = new ArrayList<Double>();
ArrayList<BMeasurement> meas = getMeasurements();
Iterator<BMeasurement> iter = meas.iterator();
while (iter.hasNext())
{
BearingMeasurementContribution.BMeasurement measurement = (BearingMeasurementContribution.BMeasurement) iter
.next();
long thisTime = measurement.getDate().getTime();
if ((thisTime >= legStart) && (thisTime <= legEnd))
{
thisLegTimes.add(measurement.getDate().getTime());
thisLegBearings.add(Math.toDegrees(measurement.bearingAngle));
}
}
// ok, before we slice this leg, let's just try to see if there was
// probably a target zig during the
// ownship zig
if (lastLegTimes != null)
{
boolean probWasZig = checkForTargetZig(thisLeg.getName(), lastLegTimes, lastLegBearings,
thisLegTimes, thisLegBearings);
if (probWasZig)
{
// inject a target leg for the period spanning the ownship manouvre
long tStart = lastLegTimes.get(lastLegTimes.size()-1);
long tEnd = thisLegTimes.get(0);
zigStorer.storeZig("some name", tStart, tEnd, 0);
}
}
final double zigTolerance = 0.000001;
ISolversManager solversManager = SATC_Activator.getDefault().getService(
ISolversManager.class, false);
final Precision precision;
if(solversManager != null)
{
precision = solversManager.getActiveSolver().getPrecision();
}
else
{
precision = Precision.MEDIUM;
}
final double zigScore = BaseStackedDotsView.getPrecision(precision);
detector.sliceThis2(SATC_Activator.getDefault().getLog(), SATC_Activator.PLUGIN_ID,
"some name", legStorer,
zigScore, zigTolerance, thisLegTimes, thisLegBearings);
lastLegTimes = thisLegTimes;
lastLegBearings = thisLegBearings;
}
}
public static class AssumptionsTest extends TestCase
{
public void testOLS()
{
double[][] data = { { 0.5, 3 }, { 1.5, 2.5 }, { 3, 1 }, { 3.5, 0.5 } };
double[] res = Regression.getOLSRegression(data);
double gradient = res[1];
double intercept = res[0];
assertEquals("correctly identified gradient", -0.8, gradient, 0.1);
assertEquals("correctly identified intercept", 3.5, intercept, 0.1);
}
}
}
|
package org.lantern;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.ChannelGroupFuture;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.littleshoot.proxy.KeyStoreManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP proxy server for local requests from the browser to Lantern.
*/
public class LanternHttpProxyServer implements HttpProxyServer {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ChannelGroup allChannels =
new DefaultChannelGroup("Local-HTTP-Proxy-Server");
private final int port;
private final KeyStoreManager keyStoreManager;
private final int sslProxyRandomPort;
private final int plainTextProxyRandomPort;
/**
* Creates a new proxy server.
*
* @param port The port the server should run on.
* @param filters HTTP filters to apply.
* @param sslProxyRandomPort The port of the HTTP proxy that other peers will
* relay to.
* @param plainTextProxyRandomPort The port of the HTTP proxy running
* only locally and accepting plain-text sockets.
*/
public LanternHttpProxyServer(final int port,
final KeyStoreManager keyStoreManager, final int sslProxyRandomPort,
final int plainTextProxyRandomPort) {
this.port = port;
this.keyStoreManager = keyStoreManager;
this.sslProxyRandomPort = sslProxyRandomPort;
this.plainTextProxyRandomPort = plainTextProxyRandomPort;
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(final Thread t, final Throwable e) {
log.error("Uncaught exception", e);
}
});
}
public void start() {
log.info("Starting proxy on port: "+this.port);
final ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(final Runnable r) {
final Thread t =
new Thread(r, "Daemon-Netty-Boss-Executor");
t.setDaemon(true);
return t;
}
}),
Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(final Runnable r) {
final Thread t =
new Thread(r, "Daemon-Netty-Worker-Executor");
t.setDaemon(true);
return t;
}
})));
final HttpServerPipelineFactory factory =
new HttpServerPipelineFactory(this.allChannels,
this.keyStoreManager, this.sslProxyRandomPort,
this.plainTextProxyRandomPort);
bootstrap.setPipelineFactory(factory);
// We always only bind to localhost here for better security.
final Channel channel =
bootstrap.bind(new InetSocketAddress("127.0.0.1", port));
allChannels.add(channel);
/*
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
log.info("Got shutdown hook...closing all channels.");
final ChannelGroupFuture future = allChannels.close();
try {
future.await(6*1000);
} catch (final InterruptedException e) {
log.info("Interrupted", e);
}
bootstrap.releaseExternalResources();
log.info("Closed all channels...");
}
}));
*/
}
}
|
package org.lantern.util;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.params.CoreConnectionPNames;
import org.lantern.Censored;
import org.lantern.LanternConstants;
import org.lantern.LanternUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* Class for handling HTTP client interaction.
*
* TODO: We really need all of these methods to follow similar logic to
* OauthUtils and to try to connect directly.
*/
@Singleton
public class HttpClientFactory {
private static final Logger log = LoggerFactory.getLogger(HttpClientFactory.class);
private final Censored censored;
@Inject
public HttpClientFactory(final Censored censored) {
this.censored = censored;
}
/**
* Returns a proxied client if we have access to a proxy in get mode.
*
* @return The proxied {@link HttpClient} if available in get mode,
* otherwise an unproxied client.
* @throws IOException If we could not obtain a proxied client.
*/
public HttpClient newClient() {
if (this.censored.isCensored() || LanternUtils.isGet()) {
return newProxiedClient();
} else {
return newDirectClient();
}
}
public static HttpClient newDirectClient() {
log.debug("Returning direct client");
return newClient(null);
}
public static HttpClient newProxiedClient() {
log.debug("Returning proxied client");
HttpHost proxy = new HttpHost("127.0.0.1",
LanternConstants.LANTERN_LOCALHOST_HTTP_PORT,
"http");
return newClient(proxy);
}
public static HttpClient newClient(final HttpHost proxy) {
final DefaultHttpClient client = new DefaultHttpClient();
configureDefaults(client);
if (proxy != null) {
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
LanternUtils.waitForServer(proxy.getHostName(), proxy.getPort(), 10000);
}
return client;
}
public static void configureDefaults(final DefaultHttpClient httpClient) {
log.debug("Configuring defaults...");
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(2,true));
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 50000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);
}
}
|
package org.geomajas.plugin.caching.service;
import com.twmacinta.util.MD5;
import com.vividsolutions.jts.geom.Geometry;
import org.geomajas.geometry.Crs;
import org.geomajas.global.CacheableObject;
import org.geomajas.global.GeomajasException;
import org.geomajas.service.pipeline.PipelineContext;
import org.jboss.serial.io.JBossObjectOutputStream;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Random;
/**
* Implementation of {@link CacheKeyService}.
*
* @author Joachim Van der Auwera
*/
@Component
public class CacheKeyServiceImpl implements CacheKeyService {
private static final int BASE_KEY_LENGTH = 512;
private static final char[] CHARACTERS = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static final String ENCODING = "UTF-8";
private final Logger log = LoggerFactory.getLogger(CacheKeyServiceImpl.class);
private Random random = new Random();
public String getCacheKey(CacheContext context) {
try {
MD5 md5 = new MD5();
StringBuilder toHash = new StringBuilder(BASE_KEY_LENGTH);
if (context instanceof CacheContextImpl) {
CacheContextImpl cci = (CacheContextImpl) context;
for (Map.Entry<String, Object> entry : cci.entries()) {
md5.Update(entry.getKey(), ENCODING);
md5.Update(":");
if (log.isDebugEnabled()) {
toHash.append(entry.getKey());
toHash.append(":");
}
Object value = entry.getValue();
if (null != value) {
String cid = getCacheId(value);
md5.Update(cid, ENCODING);
if (log.isDebugEnabled()) {
toHash.append(cid);
}
}
md5.Update("-");
if (log.isDebugEnabled()) {
toHash.append("-");
}
}
} else {
String cid = getCacheId(context);
md5.Update(cid, ENCODING);
if (log.isDebugEnabled()) {
toHash.append(cid);
}
}
String key = md5.asHex();
log.debug("key for context {} which is a hash for {}", key, toHash.toString());
return key;
} catch (UnsupportedEncodingException uee) {
log.error("Impossible error, UTF-8 should be supported:" + uee.getMessage(), uee);
return null;
}
}
private String getCacheId(Object value) {
if (value instanceof CacheableObject) {
return ((CacheableObject) value).getCacheId();
} else if (value instanceof Crs) {
return ((Crs) value).getId();
} else if (value instanceof CoordinateReferenceSystem) {
return ((CoordinateReferenceSystem) value).toWKT();
} else if (value instanceof Geometry) {
return ((Geometry) value).toText();
} else if (value instanceof Filter) {
return value.toString();
} else if (value instanceof Integer) {
return Integer.toString((Integer) value);
} else if (value instanceof String) {
return value.toString();
} else {
try {
log.debug("Serializing {} for unique id", value.getClass().getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
JBossObjectOutputStream serialize = new JBossObjectOutputStream(baos);
serialize.writeObject(value);
serialize.flush();
serialize.close();
return baos.toString("UTF-8");
} catch (IOException ioe) {
String fallback = value.toString();
log.error("Could not serialize " + value + ", falling back to toString() which may cause problems.",
ioe);
return fallback;
}
}
}
public CacheContext getCacheContext(PipelineContext pipelineContext, String[] keys) {
CacheContext res = new CacheContextImpl();
for (String key : keys) {
try {
res.put(key, pipelineContext.get(key));
} catch (GeomajasException ge) {
log.error(ge.getMessage(), ge);
}
}
return res;
}
public String makeUnique(String duplicateKey) {
log.debug("Need to make key {} unique.", duplicateKey);
return duplicateKey + CHARACTERS[random.nextInt(CHARACTERS.length)];
}
}
|
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.yaml.snakeyaml.Yaml;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// Cache for all configuration passed programmatically or read from file
private final Map<Object, Object> config = new HashMap<Object, Object>();
// Runtime to get available processors
private static final Runtime RUNTIME = Runtime.getRuntime();
public static final String DATA_SOURCE_PATH_DEF = "./ds";
// Properties which version of server is running remote it requires server
// client RPC infrastructure or local (embedded mode)
private static final String CONFIG_FILE = "./config/configuration.yaml";
// Configuration keys properties for deployment
private static final String HOT_DEPLOYMENT_KEY = "hotDeployment";
private static final String WATCH_STATUS_KEY = "watchStatus";
private static final String LIBRARY_PATH_KEY = "libraryPaths";
// Persistence provider property keys
private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig";
private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities";
private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName";
private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath";
private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar";
private static final String SWAP_DATASOURCE_KEY = "swapDataSource";
private static final String SCAN_ARCHIVES_KEY = "scanArchives";
private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource";
private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties";
// Connection pool provider property keys
private static final String POOL_CONFIG_KEY = "poolConfig";
private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath";
private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType";
private static final String POOL_PROPERTIES_KEY = "poolProperties";
// Configuration properties for deployment
private static String ADMIN_USERS_PATH;
// Is configuration server or client (default is server)
private static boolean server = (Boolean) Config.SERVER.value;
private static boolean remote;
// Instance of pool configuration
private static final PoolConfig POOL_CONFIG = new PoolConfig();
private static final String META_INF_PATH = "META-INF/";
// Error messages
private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration";
private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file";
private static final String RESOURCE_NOT_EXISTS_ERROR = "Configuration resource doesn't exist";
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) {
if (from == null) {
from = config;
}
@SuppressWarnings("unchecked")
Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from);
return value;
}
private <K, V> Map<K, V> getAsMap(Object key) {
return getAsMap(key, null);
}
private <K, V> void setSubConfigValue(Object key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (ObjectUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K> boolean containsSubConfigKey(Object key, K subKey) {
Map<K, ?> subConfig = getAsMap(key);
boolean valid = ObjectUtils.available(subConfig);
if (valid) {
valid = subConfig.containsKey(subKey);
}
return valid;
}
private <K> boolean containsConfigKey(K key) {
return containsSubConfigKey(Config.DEPLOY_CONFIG.key, key);
}
private <K, V> V getSubConfigValue(Object key, K subKey) {
return getSubConfigValue(key, subKey, null);
}
private <K, V> void setConfigValue(K subKey, V value) {
setSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, value);
}
private <K, V> V getConfigValue(K subKey, V defaultValue) {
return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey, defaultValue);
}
private <K, V> V getConfigValue(K subKey) {
return getSubConfigValue(Config.DEPLOY_CONFIG.key, subKey);
}
private <K, V> Map<K, V> getWithInitialization(Object key) {
Map<K, V> result = getConfigValue(key);
if (result == null) {
result = new HashMap<K, V>();
setConfigValue(key, result);
}
return result;
}
private <K, V> void setWithInitialization(Object key, K subKey, V value) {
Map<K, V> result = getWithInitialization(key);
result.put(subKey, value);
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration if value is null then returns passed default value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key,
Config.PERSISTENCE_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection persistence sub {@link Map}
* of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPersistenceConfigValue(Object key) {
return getPersistenceConfigValue(key, null);
}
/**
* Sets specific value for appropriated key in persistence configuration sub
* {@link Map} of configuration
*
* @param key
* @param value
*/
public void setPersistenceConfigValue(Object key, Object value) {
setWithInitialization(Config.PERSISTENCE_CONFIG.key, key, value);
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration if value is null then returns passed default
* value
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key, V defaultValue) {
V value = ObjectUtils.getSubValue(config, Config.DEPLOY_CONFIG.key,
Config.POOL_CONFIG.key, key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Gets value for specific key from connection pool configuration sub
* {@link Map} of configuration
*
* @param key
* @return <code>V</code>
*/
public <V> V getPoolConfigValue(Object key) {
V value = getPoolConfigValue(key, null);
return value;
}
/**
* Sets specific value for appropriated key in connection pool configuration
* sub {@link Map} of configuraion
*
* @param key
* @param value
*/
public void setPoolConfigValue(Object key, Object value) {
setWithInitialization(Config.POOL_CONFIG.key, key, value);
}
/**
* Configuration for {@link PoolConfig} instance
*/
private void configurePool() {
Map<Object, Object> poolProperties = getPoolConfigValue(Config.POOL_PROPERTIES.key);
if (ObjectUtils.available(poolProperties)) {
setPoolProperties(poolProperties);
}
String type = getPoolConfigValue(Config.POOL_PROVIDER_TYPE.key);
if (ObjectUtils.available(type)) {
getPoolConfig().setPoolProviderType(type);
}
String path = getPoolConfigValue(Config.POOL_PROPERTIES_PATH.key);
if (ObjectUtils.available(path)) {
setPoolPropertiesPath(path);
}
}
/**
* Configures server from properties
*/
private void configureServer() {
// Sets default values to remote server configuration
boolean contains = containsConfigKey(Config.IP_ADDRESS.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.IP_ADDRESS.key, Config.IP_ADDRESS.value);
}
contains = containsConfigKey(Config.PORT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.PORT.key, Config.PORT.value);
}
contains = containsConfigKey(Config.BOSS_POOL.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.BOSS_POOL.key, Config.BOSS_POOL.value);
}
contains = containsConfigKey(Config.WORKER_POOL.key);
if (ObjectUtils.notTrue(contains)) {
int workers = RUNTIME.availableProcessors()
* (Integer) Config.WORKER_POOL.value;
String workerProperty = String.valueOf(workers);
setConfigValue(Config.WORKER_POOL.key, workerProperty);
}
contains = containsConfigKey(Config.CONNECTION_TIMEOUT.key);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(Config.CONNECTION_TIMEOUT.key,
Config.CONNECTION_TIMEOUT.value);
}
// Sets default values is application on server or client mode
Object serverValue = getConfigValue(Config.SERVER.key);
if (ObjectUtils.notNull(serverValue)) {
if (serverValue instanceof Boolean) {
server = (Boolean) serverValue;
} else {
server = Boolean.valueOf(serverValue.toString());
}
}
Object remoteValue = getConfigValue(Config.REMOTE.key);
if (ObjectUtils.notNull(remoteValue)) {
if (remoteValue instanceof Boolean) {
remote = (Boolean) remoteValue;
} else {
remote = Boolean.valueOf(remoteValue.toString());
}
}
}
/**
* Merges configuration with default properties
*/
@SuppressWarnings("unchecked")
public void configureDeployments() {
// Checks if application run in hot deployment mode
Boolean hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key);
if (hotDeployment == null) {
setConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE);
hotDeployment = getConfigValue(Config.HOT_DEPLOYMENT.key);
}
// Check if application needs directory watch service
boolean watchStatus;
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
setConfigValue(Config.WATCH_STATUS.key, watchStatus);
// Sets deployments directories
Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = (Set<DeploymentDirectory>) Config.DEMPLOYMENT_PATH.value;
setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths);
}
}
/**
* Configures server and connection pooling
*/
public void configure() {
configureServer();
configureDeployments();
configurePool();
}
/**
* Merges two {@link Map}s and if second {@link Map}'s value is instance of
* {@link Map} merges this value with first {@link Map}'s value recursively
*
* @param map1
* @param map2
* @return <code>{@link Map}<Object, Object></code>
*/
@SuppressWarnings("unchecked")
protected Map<Object, Object> deepMerge(Map<Object, Object> map1,
Map<Object, Object> map2) {
if (map1 == null) {
map1 = map2;
} else {
Set<Map.Entry<Object, Object>> entries2 = map2.entrySet();
Object key;
Map<Object, Object> value1;
Object value2;
Object mergedValue;
for (Map.Entry<Object, Object> entry2 : entries2) {
key = entry2.getKey();
value2 = entry2.getValue();
if (value2 instanceof Map) {
value1 = ObjectUtils.getAsMap(key, map1);
mergedValue = deepMerge(value1,
(Map<Object, Object>) value2);
} else {
mergedValue = value2;
}
if (ObjectUtils.notNull(mergedValue)) {
map1.put(key, mergedValue);
}
}
}
return map1;
}
/**
* Reads configuration from passed properties
*
* @param configuration
*/
public void configure(Map<Object, Object> configuration) {
deepMerge(config, configuration);
}
/**
* Reads configuration from passed file path
*
* @param configuration
*/
public void configure(String path) throws IOException {
File yamlFile = new File(path);
if (yamlFile.exists()) {
InputStream stream = new FileInputStream(yamlFile);
try {
Yaml yaml = new Yaml();
Object configuration = yaml.load(stream);
if (configuration instanceof Map) {
@SuppressWarnings("unchecked")
Map<Object, Object> innerConfig = (Map<Object, Object>) configuration;
configure(innerConfig);
}
} finally {
ObjectUtils.close(stream);
}
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) throws IOException {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
} catch (IOException ex) {
LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex);
} finally {
ObjectUtils.close(propertiesStream);
}
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
try {
File configFile = new File(CONFIG_FILE);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex);
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader)
throws IOException {
InputStream resourceStream = loader.getResourceAsStream(StringUtils
.concat(META_INF_PATH, resourceName));
if (resourceStream == null) {
LOG.error(RESOURCE_NOT_EXISTS_ERROR);
} else {
loadFromStream(resourceStream);
}
}
public static String getAdminUsersPath() {
return ADMIN_USERS_PATH;
}
public static void setAdminUsersPath(String aDMIN_USERS_PATH) {
ADMIN_USERS_PATH = aDMIN_USERS_PATH;
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remoteValue) {
remote = remoteValue;
}
public static boolean isServer() {
return server;
}
public static void setServer(boolean serverValue) {
server = serverValue;
}
public boolean isClient() {
return getConfigValue(Config.CLIENT.key, Boolean.FALSE);
}
public void setClient(boolean client) {
setConfigValue(Config.CLIENT.key, client);
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
Set<DeploymentDirectory> deploymentPaths = getConfigValue(Config.DEMPLOYMENT_PATH.key);
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
setConfigValue(Config.DEMPLOYMENT_PATH.key, deploymentPaths);
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
Set<String> dataSourcePaths = getConfigValue(Config.DATA_SOURCE_PATH.key);
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
setConfigValue(Config.DATA_SOURCE_PATH.key, dataSourcePaths);
}
dataSourcePaths.add(path);
}
public Set<DeploymentDirectory> getDeploymentPath() {
return getConfigValue(Config.DEMPLOYMENT_PATH.key);
}
public Set<String> getDataSourcePath() {
return getConfigValue(Config.DATA_SOURCE_PATH.key);
}
public String[] getLibraryPaths() {
return getConfigValue(Config.LIBRARY_PATH.key);
}
public void setLibraryPaths(String[] libraryPaths) {
setConfigValue(Config.LIBRARY_PATH.key, libraryPaths);
}
public boolean isHotDeployment() {
return getConfigValue(Config.HOT_DEPLOYMENT.key, Boolean.FALSE);
}
public void setHotDeployment(boolean hotDeployment) {
setConfigValue(Config.HOT_DEPLOYMENT.key, hotDeployment);
}
public boolean isWatchStatus() {
return getConfigValue(Config.WATCH_STATUS.key, Boolean.FALSE);
}
public void setWatchStatus(boolean watchStatus) {
setConfigValue(Config.WATCH_STATUS.key, watchStatus);
}
/**
* Property for persistence configuration
*
* @return <code>boolean</code>
*/
public boolean isScanForEntities() {
return getPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key,
Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setPersistenceConfigValue(Config.SCAN_FOR_ENTITIES.key, scanForEntities);
}
public String getAnnotatedUnitName() {
return getPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setPersistenceConfigValue(Config.ANNOTATED_UNIT_NAME.key,
annotatedUnitName);
}
public String getPersXmlPath() {
return getPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key);
}
public void setPersXmlPath(String persXmlPath) {
setPersistenceConfigValue(Config.PERSISTENCE_XML_PATH.key, persXmlPath);
}
public boolean isPersXmlFromJar() {
return getPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key,
Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setPersistenceConfigValue(Config.PERSISTENCE_XML_FROM_JAR.key,
persXmlFromJar);
}
public boolean isSwapDataSource() {
return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource);
}
public boolean isScanArchives() {
return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives);
}
public boolean isPooledDataSource() {
return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource);
}
public Map<Object, Object> getPersistenceProperties() {
return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY,
persistenceProperties);
}
/**
* Property for connection pool configuration
*
* @return {@link PoolConfig}
*/
public static PoolConfig getPoolConfig() {
return POOL_CONFIG;
}
public void setDataSourcePooledType(boolean dsPooledType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPooledDataSource(dsPooledType);
}
public void setPoolPropertiesPath(String path) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolPath(path);
}
public void setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().putAll(properties);
}
public void addPoolProperty(Object key, Object value) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().put(key, value);
}
public void setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolProviderType(poolProviderType);
}
@Override
public Object clone() throws CloneNotSupportedException {
Configuration cloneConfig = (Configuration) super.clone();
cloneConfig.config.clear();
cloneConfig.configure(this.config);
return cloneConfig;
}
}
|
package org.jkiss.dbeaver.model.sql.format.tokenized;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.DBPIdentifierCase;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class SQLFormatterTokenizedTest {
SQLFormatterTokenized formatter = new SQLFormatterTokenized();
@Mock
private SQLFormatterConfiguration configuration;
@Mock
private DBPPreferenceStore preferenceStore;
@Mock
private SQLSyntaxManager syntaxManager;
private SQLDialect dialect = BasicSQLDialect.INSTANCE;
private final String lineBreak = System.getProperty("line.separator");
@Before
public void init() throws Exception {
Mockito.when(configuration.getSyntaxManager()).thenReturn(syntaxManager);
String[] delimiters = new String[]{";"};
Mockito.when(syntaxManager.getStatementDelimiters()).thenReturn(delimiters);
Mockito.when(syntaxManager.getDialect()).thenReturn(dialect);
Mockito.when(syntaxManager.getCatalogSeparator()).thenReturn(".");
Mockito.when(configuration.getKeywordCase()).thenReturn(DBPIdentifierCase.UPPER);
Mockito.when(configuration.getIndentString()).thenReturn("\t");
Mockito.doReturn(preferenceStore).when(configuration).getPreferenceStore();
}
@Test
public void shouldDoDefaultFormat() {
//given
String expectedString = getExpectedString();
String inputString = "SELECT * FROM TABLE1 t WHERE a > 100 AND b BETWEEN 12 AND 45; SELECT t.*, j1.x, j2.y FROM TABLE1 t JOIN JT1 j1 ON j1.a = t.a LEFT OUTER JOIN JT2 j2 ON j2.a = t.a AND j2.b = j1.b WHERE t.xxx NOT NULL; DELETE FROM TABLE1 WHERE a = 1; UPDATE TABLE1 SET a = 2 WHERE a = 1; SELECT table1.id, table2.number, SUM(table1.amount) FROM table1 INNER JOIN table2 ON table.id = table2.table1_id WHERE table1.id IN ( SELECT table1_id FROM table3 WHERE table3.name = 'Foo Bar' AND table3.type = 'unknown_type') GROUP BY table1.id, table2.number ORDER BY table1.id;\n";
Mockito.when(preferenceStore.getBoolean(Mockito.eq(ModelPreferences.SQL_FORMAT_LF_BEFORE_COMMA))).thenReturn(false);
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldReturnEmptyStringWhenThereIsOnlyOneSpace() {
//given
String expectedString = "";
String inputString = " ";
//when
String format = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, format);
}
@Test
public void shouldMakeUpperCaseForKeywords() {
//given
String expectedString = "SELECT" + lineBreak + "\t*" + lineBreak + "FROM" + lineBreak + "\tmytable;";
String inputString = "select * from mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
}
@Test
public void shouldRemoveSpacesAroundCommentSymbol() {
/*
//given
String expectedString = "-- SELECT * FROM mytable;";
String inputString = " -- SELECT * FROM mytable;";
//when
String formattedString = formatter.format(inputString, configuration);
//then
assertEquals(expectedString, formattedString);
*/
}
private String getExpectedString() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT").append(lineBreak)
.append("\t*").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta > 100").append(lineBreak)
.append("\tAND b BETWEEN 12 AND 45;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\tt.*,").append(lineBreak)
.append("\tj1.x,").append(lineBreak)
.append("\tj2.y").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1 t").append(lineBreak)
.append("JOIN JT1 j1 ON").append(lineBreak)
.append("\tj1.a = t.a").append(lineBreak)
.append("LEFT OUTER JOIN JT2 j2 ON").append(lineBreak)
.append("\tj2.a = t.a").append(lineBreak)
.append("\tAND j2.b = j1.b").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\tt.xxx NOT NULL;").append(lineBreak).append(lineBreak)
.append("DELETE").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\tTABLE1").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ta = 1;").append(lineBreak).append(lineBreak)
.append("UPDATE").append(lineBreak)
.append("\tTABLE1 SET").append(lineBreak)
.append("\t\ta = 2").append(lineBreak)
.append("\tWHERE").append(lineBreak)
.append("\t\ta = 1;").append(lineBreak).append(lineBreak)
.append("SELECT").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number,").append(lineBreak)
.append("\tSUM(table1.amount)").append(lineBreak)
.append("FROM").append(lineBreak)
.append("\ttable1").append(lineBreak)
.append("INNER JOIN table2 ON").append(lineBreak)
.append("\ttable.id = table2.table1_id").append(lineBreak)
.append("WHERE").append(lineBreak)
.append("\ttable1.id IN (").append(lineBreak)
.append("\tSELECT").append(lineBreak)
.append("\t\ttable1_id").append(lineBreak)
.append("\tFROM").append(lineBreak)
.append("\t\ttable3").append(lineBreak)
.append("\tWHERE").append(lineBreak)
.append("\t\ttable3.name = 'Foo Bar'").append(lineBreak)
.append("\t\tAND table3.type = 'unknown_type')").append(lineBreak)
.append("GROUP BY").append(lineBreak)
.append("\ttable1.id,").append(lineBreak)
.append("\ttable2.number").append(lineBreak)
.append("ORDER BY").append(lineBreak)
.append("\ttable1.id;").append(lineBreak);
return sb.toString();
}
}
|
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxnSys;
import jing.rxn.*;
import jing.chem.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import jing.chem.Species;
import jing.rxn.Reaction;
import jing.rxn.Structure;
import jing.rxn.TROEReaction;
import jing.rxn.ThirdBodyReaction;
import jing.param.Global;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.param.ParameterInfor;
//## package jing::rxnSys
// jing\rxnSys\JDASPK.java
//## class JDASPK
public class JDASPK extends JDAS {
protected StringBuilder thermoString = new StringBuilder();
private JDASPK() {
super();
}
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor,
InitialStatus p_initialStatus, int p_index, ValidityTester p_vt,
boolean p_autoflag) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, p_vt,
p_autoflag);
}
//6/25/08 gmagoon: defined alternate constructor for use with sensitivity analysis (lacks autoflag and validityTester parameters)
//6/25/08 gmagoon: set autoflag to be false with this constructor (not used for sensitivity analysis)
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, null,
false);
}
//## operation generateSensitivityStatus(ReactionModel,double [],double [],int)
private double [] generateSensitivityStatus(ReactionModel p_reactionModel, double [] p_y, double [] p_yprime, int p_paraNum) {
//#[ operation generateSensitivityStatus(ReactionModel,double [],double [],int)
int neq = p_reactionModel.getSpeciesNumber()*(p_paraNum+1);
if (p_y.length != neq) throw new DynamicSimulatorException();
if (p_yprime.length != neq) throw new DynamicSimulatorException();
double [] senStatus = new double[nParameter*nState];
for (int i = p_reactionModel.getSpeciesNumber();i<neq;i++){
double sens = p_y[i];
int index = i-p_reactionModel.getSpeciesNumber();
senStatus[index] = p_y[i];
}
return senStatus;
//
}
//## operation solve(boolean,ReactionModel,boolean,SystemSnapshot,ReactionTime,ReactionTime,Temperature,Pressure,boolean)
public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) {
outputString = new StringBuilder();
//first generate an id for all the species
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
}
//6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true
int af = 0;
if (autoflag) af = 1;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1" +"\t"+ af + "\n"); //6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
outputString.append(conversionSet[p_iterationNum]+"\n");
}
else{
outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\t"+ af + "\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe
outputString.append(0+"\n");
}
outputString.append( tBegin+" "+tEnd+"\n" );
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true
if (autoflag)
getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure);
int idid=0;
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
//idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P);
idid = solveDAE();
if (idid !=1 && idid != 2 && idid != 3) {
System.out.println("The idid from DASPK was "+idid );
throw new DynamicSimulatorException("DASPK: SA off.");
}
System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC");
Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0);
Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60;
SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
sss.setReactionFlux(reactionFlux);
return sss;
//
}
private int solveDAE() {
super.solveDAE("daspkAUTO.exe");
return readOutputFile("ODESolver/SolverOutput.dat");
}
public int readOutputFile(String path) {
//read the result
File SolverOutput = new File(path);
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
//StringTokenizer st = new StringTokenizer(line);
Global.solverIterations = Integer.parseInt(line.trim());
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
endTime = Double.parseDouble(br.readLine().trim());
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
for (int i=0; i<30; i++){
line = br.readLine();
info[i] = Integer.parseInt(line.trim());
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return 1;
}
public LinkedList solveSEN(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt) {
outputString = new StringBuilder();
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
//if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
int iterNum;
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
iterNum = conversionSet.length;
outputString.append(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t" +conversionSet.length+"\n");
for (int i=0; i<conversionSet.length; i++){
outputString.append(conversionSet[i] + " ");
}
outputString.append("\n");
}
else{
LinkedList timeSteps = ((ReactionTimeTT)tt).timeStep;
iterNum = timeSteps.size();
outputString.append(nState + "\t" + neq + "\t" + -1 + "\t" +timeSteps.size()+"\n");
for (int i=0; i<timeSteps.size(); i++){
outputString.append(((ReactionTime)timeSteps.get(i)).time + " ");
}
outputString.append("\n");
}
outputString.append( tBegin+" "+tEnd+ "\n");
for (int i=0; i<nState; i++)
outputString.append(y[i]+" ");
outputString.append("\n");
for (int i=0; i<nState; i++)
outputString.append(yprime[i]+" ");
outputString.append("\n");
for (int i=0; i<30; i++)
outputString.append(info[i]+" ");
outputString.append("\n"+ rtol + " "+atol);
outputString.append("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n");
// Add list of flags for constantConcentration
// one for each species, and a final one for the volume
// if 1: will not change the number of moles of that species (or the volume)
// if 0: will integrate the ODE as normal
// eg. liquid phase calculations with a constant concentration of O2 (the solubility limit - replenished from the gas phase)
// for normal use, this will be a sequence of '0 's
for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) {
Species spe = (Species)iter.next();
if (spe.isConstantConcentration())
System.err.println("WARNING. 'ConstantConcentration' option not implemented in DASPK solver. Use DASSL if you need this.");
/*outputString.append("1 ");
else
outputString.append("0 ");*/
}
// outputString.append("0 \n"); // for liquid EOS or constant volume this should be 1
int idid=0;
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
LinkedList systemSnapshotList = callSolverSEN(iterNum, p_reactionModel, p_beginStatus);
return systemSnapshotList;
//
}
private LinkedList callSolverSEN(int p_numSteps, ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
double startTime = System.currentTimeMillis();
String workingDirectory = System.getProperty("RMG.workingDirectory");
LinkedList systemSnapshotList = new LinkedList();
ReactionTime beginT = new ReactionTime(0.0, "sec");
ReactionTime endT;
//write the input file
File SolverInput = new File("ODESolver/SolverInput.dat");
try {
FileWriter fw = new FileWriter(SolverInput);
fw.write(outputString.toString());
fw.close();
} catch (IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
Global.writeSolverFile +=(System.currentTimeMillis()-startTime)/1000/60;
//run the solver on the input file
boolean error = false;
try {
// system call for therfit
String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"};
File runningDir = new File("ODESolver");
Process ODESolver = Runtime.getRuntime().exec(command, null, runningDir);
InputStream is = ODESolver.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//System.out.println(line);
line = line.trim();
//if (!(line.contains("ODESOLVER SUCCESSFUL"))) {
System.out.println(line);
//error = true;
}
int exitValue = 4;
exitValue = ODESolver.waitFor();
//System.out.println(br.readLine() + exitValue);
}
catch (Exception e) {
String err = "Error in running ODESolver \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
startTime = System.currentTimeMillis();
//read the result
File SolverOutput = new File("ODESolver/SolverOutput.dat");
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line ;
double presentTime = 0;
for (int k=0; k<p_numSteps; k++){
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
presentTime = Double.parseDouble(br.readLine().trim());
endT = new ReactionTime(presentTime, "sec");
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
System.out.println("After ODE: from " + String.valueOf(beginT.time) + " SEC to " + String.valueOf(endT.time) + "SEC");
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, nParameter);
senStatus = generateSensitivityStatus(p_reactionModel,y,yprime,nParameter);
SystemSnapshot sss = new SystemSnapshot(endT, speStatus, senStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
sss.setIDTranslator(IDTranslator);
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
sss.setReactionList(reactionList);
systemSnapshotList.add(sss);
sss.setReactionFlux(reactionFlux);
beginT = endT;
//tEnd = tEnd.add(tStep);
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
Global.readSolverFile += (System.currentTimeMillis() - startTime)/1000/60;
return systemSnapshotList;
}
@Override
protected void initializeWorkSpace() {
super.initializeWorkSpace();
info[4] = 1; //use analytical jacobian
if (nParameter != 0) {
info[18] = nParameter; //the number of parameters
info[19] = 2; //perform senstivity analysis
info[24] = 1;//staggered corrector method is used
}
}
@Override
protected void initializeConcentrations(SystemSnapshot p_beginStatus, ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, LinkedList initialSpecies) {
super.initializeConcentrations(p_beginStatus, p_reactionModel,
p_beginTime, p_endTime, initialSpecies);
if (nParameter != 0){//svp
double [] sensitivityStatus = new double[nState*nParameter];
int speciesNumber = p_reactionModel.getSpeciesNumber();
for (int i=0; i<nParameter*speciesNumber;i++){
sensitivityStatus[i] = 0;
}
p_beginStatus.addSensitivity(sensitivityStatus);
}
}
}
|
// RMG - Reaction Mechanism Generator
// RMG Team (rmg_dev@mit.edu)
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
package jing.rxnSys;
import jing.rxn.*;
import jing.chem.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import jing.chem.Species;
import jing.rxn.Reaction;
import jing.rxn.Structure;
import jing.rxn.TROEReaction;
import jing.rxn.ThirdBodyReaction;
import jing.param.Global;
import jing.param.Pressure;
import jing.param.Temperature;
import jing.param.ParameterInfor;
//## package jing::rxnSys
// jing\rxnSys\JDASPK.java
//## class JDASPK
public class JDASPK extends JDAS {
private JDASPK() {
super();
}
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor,
InitialStatus p_initialStatus, int p_index, ValidityTester p_vt,
boolean p_autoflag) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, p_vt,
p_autoflag);
}
//6/25/08 gmagoon: defined alternate constructor for use with sensitivity analysis (lacks autoflag and validityTester parameters)
//6/25/08 gmagoon: set autoflag to be false with this constructor (not used for sensitivity analysis)
public JDASPK(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index) {
super(p_rtol, p_atol, p_parameterInfor, p_initialStatus, p_index, null,
false);
}
//## operation generateSensitivityStatus(ReactionModel,double [],double [],int)
private double [] generateSensitivityStatus(ReactionModel p_reactionModel, double [] p_y, double [] p_yprime, int p_paraNum) {
//#[ operation generateSensitivityStatus(ReactionModel,double [],double [],int)
int nequ = p_reactionModel.getSpeciesNumber()*(p_paraNum+1);
if (p_y.length != nequ) throw new DynamicSimulatorException();
if (p_yprime.length != nequ) throw new DynamicSimulatorException();
double [] senStatus = new double[nParameter*nState];
for (int i = p_reactionModel.getSpeciesNumber();i<neq;i++){
//double sens = p_y[i]; gmagoon 12/21/09: this doesn't seem to be used anywhere
int ind = i-p_reactionModel.getSpeciesNumber();
senStatus[ind] = p_y[i];
}
return senStatus;
//
}
//## operation solve(boolean,ReactionModel,boolean,SystemSnapshot,ReactionTime,ReactionTime,Temperature,Pressure,boolean)
public SystemSnapshot solve(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt, int p_iterationNum) {
// set up the input file
setupInputFile();
//outputString = new StringBuilder();
//first generate an id for all the species
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
lindemannString = generateLindemannReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + lindemannList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
}
//6/25/08 gmagoon: (next two lines) for autoflag, get binary 0 or 1 corresponding to boolean false/true
int af = 0;
if (autoflag) af = 1;
try{
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
bw.write(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t 1" +"\t"+ af + "\t0\n"); //6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe; 080509 gmagoon: added sensitivity flag = 0
bw.write(conversionSet[p_iterationNum]+"\n");
}
else{
bw.write(nState + "\t" + neq + "\t" + -1 + "\t" +1+"\t"+ af + "\t0\n");//6/25/08 gmagoon: added autoflag, needed when using daspkAUTO.exe; 080509 gmagoon: added sensitivity flag = 0
bw.write(0+"\n");
}
bw.write( tBegin+" "+tEnd+"\n" );
for (int i=0; i<nState; i++)
bw.write(y[i]+" ");
bw.write("\n");
for (int i=0; i<nState; i++)
bw.write(yprime[i]+" ");
bw.write("\n");
for (int i=0; i<30; i++)
bw.write(info[i]+" ");
bw.write("\n"+ rtol + " "+atol);
bw.write("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n" + lindemannList.size() + "\n" + lindemannString.toString() + "\n");
}
catch (IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
///4/30/08 gmagoon: code for providing edge reaction info to DASPK in cases if the automatic time stepping flag is set to true
if (autoflag)
getAutoEdgeReactionInfo((CoreEdgeReactionModel) p_reactionModel, p_temperature, p_pressure);
// Add flags that specify whether the concentrations are constant or not
getConcentractionFlags(p_reactionModel);
//this should be the end of the input file
try{
bw.flush();
bw.close();
fw.close();
}
catch (IOException e) {
System.err.println("Problem closing Solver Input File!");
e.printStackTrace();
}
int idid=0;
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
//idid = solveDAE(p_initialization, reactionList, p_reactionChanged, thirdBodyReactionList, troeReactionList, nState, y, yprime, tBegin, tEnd, this.rtol, this.atol, T, P);
idid = solveDAE();
if (idid !=1 && idid != 2 && idid != 3) {
System.out.println("The idid from DASPK was "+idid );
throw new DynamicSimulatorException("DASPK: SA off.");
}
System.out.println("After ODE: from " + String.valueOf(tBegin) + " SEC to " + String.valueOf(endTime) + "SEC");
Global.solvertime = Global.solvertime + (System.currentTimeMillis() - startTime)/1000/60;
startTime = System.currentTimeMillis();
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, 0);
Global.speciesStatusGenerator = Global.speciesStatusGenerator + (System.currentTimeMillis() - startTime)/1000/60;
SystemSnapshot sss = new SystemSnapshot(new ReactionTime(endTime, "sec"), speStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
//sss.inertGas = p_beginStatus.inertGas; //gmagoon 6/23/09: copy inertGas information from initialStatus
//total the concentrations of non-inert species
double totalNonInertConc = totalNonInertConcentrations();
//calculate the scale factor needed to account for volume change
double inertScaleFactor = 1;
if(p_beginStatus.inertGas != null){//8/5/09 gmagoon: make sure inert gas is defined; otherwise, we will have issues with getTotalInertGas() when we start from non-zero time, as jdmo encountered (null-pointer exception)
if(p_beginStatus.getTotalInertGas() > 0){//this check will ensure we don't try to divide by zero; otherwise, we will end up setting new concentration to be 0.0*Infinity=NaN
inertScaleFactor = (p_beginStatus.getTotalMole()- totalNonInertConc)/p_beginStatus.getTotalInertGas();
}
//scale the initial concentrations of the inertGas to account for volume change
for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) {
String inertName = (String)iter.next();
double originalInertConc = p_beginStatus.getInertGas(inertName);
sss.putInertGas(inertName, originalInertConc*inertScaleFactor);
}
}
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
reactionList.addAll(lindemannList);
sss.setReactionList(reactionList);
sss.setReactionFlux(reactionFlux);
return sss;
//
}
private int solveDAE() {
String workingDirectory = System.getProperty("RMG.workingDirectory");
// write the input file
// File SolverInput = new File("ODESolver/SolverInput.dat");
// try {
// FileWriter fw = new FileWriter(SolverInput);
// fw.write(outputString.toString());
// fw.close();
// } catch (IOException e) {
// System.err.println("Problem writing Solver Input File!");
// e.printStackTrace();
// Rename RWORK and IWORK files if they exist
renameIntermediateFilesBeforeRun();
//run the solver on the input file
boolean error = false;
try {
String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"};//5/5/08 gmagoon: changed to call dasslAUTO.exe
File runningDir = new File("ODESolver");
Process solver = Runtime.getRuntime().exec(command, null, runningDir);
InputStream is = solver.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
line = line.trim();
if (!(line.contains("ODESOLVER SUCCESSFUL"))) {
System.err.println("Error running the ODESolver: "+line);
error = true;
}
}
int exitValue = solver.waitFor();
}
catch (Exception e) {
String err = "Error in running ODESolver \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
//11/1/07 gmagoon: renaming RWORK and IWORK files
renameIntermediateFilesAfterRun();
return readOutputFile("ODESolver/SolverOutput.dat");
}
private void renameIntermediateFilesBeforeRun(){
File f = new File("ODESolver/RWORK_"+index+".DAT");
File newFile = new File("ODESolver/RWORK.DAT");
boolean renameSuccess = false;
if(f.exists()){
if(newFile.exists())
newFile.delete();
renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of RWORK file(s) failed.");
System.exit(0);
}
}
f = new File("ODESolver/IWORK_"+index+".DAT");
newFile = new File("ODESolver/IWORK.DAT");
if(f.exists()){
if(newFile.exists())
newFile.delete();
renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of IWORK file(s) failed.");
System.exit(0);
}
}
f = new File("ODESolver/variables_"+index+".dat");
newFile = new File("ODESolver/variables.dat");
if(f.exists()){
if(newFile.exists())
newFile.delete();
renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of variables.dat file(s) failed.");
System.exit(0);
}
}
}
private void renameIntermediateFilesAfterRun() {
File f = new File("ODESolver/RWORK.DAT");
File newFile = new File("ODESolver/RWORK_"+index+".DAT");
if(newFile.exists())
newFile.delete();
boolean renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of RWORK file(s) failed. (renameIntermediateFiles())");
System.exit(0);
}
f = new File("ODESolver/IWORK.DAT");
newFile = new File("ODESolver/IWORK_"+index+".DAT");
if(newFile.exists())
newFile.delete();
renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of IWORK file(s) failed. (renameIntermediateFiles())");
System.exit(0);
}
f = new File("ODESolver/variables.dat");
newFile = new File("ODESolver/variables_"+index+".dat");
if(newFile.exists())
newFile.delete();
renameSuccess = f.renameTo(newFile);
if (!renameSuccess)
{
System.out.println("Renaming of variables.dat file(s) failed. (renameIntermediateFiles())");
System.exit(0);
}
}
public int readOutputFile(String path) {
//read the result
File SolverOutput = new File(path);
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
//StringTokenizer st = new StringTokenizer(line);
Global.solverIterations = Integer.parseInt(line.trim());
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
endTime = Double.parseDouble(br.readLine().trim());
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
for (int i=0; i<30; i++){
line = br.readLine();
info[i] = Integer.parseInt(line.trim());
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
return 1;
}
public LinkedList solveSEN(boolean p_initialization, ReactionModel p_reactionModel, boolean p_reactionChanged, SystemSnapshot p_beginStatus, ReactionTime p_beginTime, ReactionTime p_endTime, Temperature p_temperature, Pressure p_pressure, boolean p_conditionChanged,TerminationTester tt) {
setupInputFile();
// outputString = new StringBuilder();
Iterator spe_iter = p_reactionModel.getSpecies();
while (spe_iter.hasNext()){
Species spe = (Species)spe_iter.next();
int id = getRealID(spe);
}
double startTime = System.currentTimeMillis();
ReactionTime rt = p_beginStatus.getTime();
if (!rt.equals(p_beginTime)) throw new InvalidBeginStatusException();
double tBegin = p_beginTime.getStandardTime();
double tEnd = p_endTime.getStandardTime();
double T = p_temperature.getK();
double P = p_pressure.getAtm();
LinkedList initialSpecies = new LinkedList();
// set reaction set
//if (p_initialization || p_reactionChanged || p_conditionChanged) {
nState = p_reactionModel.getSpeciesNumber();
// troeString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10, alpha, Tstar, T2star, T3star, lowRate (21 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10, troe(0=T or 1=F) (21 elements)
troeString = generateTROEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
// tbrString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq, inertEfficiency, e1, e2, ..., e10 (16 elements)
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0), ncollider, c1, c2,..c10 (20 elements)
tbrString = generateThirdBodyReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
lindemannString = generateLindemannReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
//rString is a combination of a integer and a real array
//real array format: rate, A, n, Ea, Keq
//int array format : nReac, nProd, r1, r2, r3, p1, p2, p3, HASrev(T=1 or F=0)
rString = generatePDepODEReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure);
nParameter = 0;
if (parameterInfor != 0) {
nParameter = rList.size() + thirdBodyList.size() + troeList.size() + lindemannList.size() + p_reactionModel.getSpeciesNumber();
}
neq = nState*(nParameter + 1);
initializeWorkSpace();
initializeConcentrations(p_beginStatus, p_reactionModel, p_beginTime, p_endTime, initialSpecies);
int iterNum = 0;
try{
if (tt instanceof ConversionTT){
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)tt).speciesGoalConversionSet.get(0);
iterNum = conversionSet.length;
bw.write(nState + "\t" + neq + "\t" + getRealID(sc.species) + "\t" +conversionSet.length+ "\t0\t1\n");//gmagoon 080509: added autoflag=0; later: added sensflag=1
for (int i=0; i<conversionSet.length; i++){
bw.write(conversionSet[i] + " ");
}
bw.write("\n");
}
else{
LinkedList timeSteps = ((ReactionTimeTT)tt).timeStep;
iterNum = timeSteps.size();
bw.write(nState + "\t" + neq + "\t" + -1 + "\t" +timeSteps.size()+"\t0\t1\n");
for (int i=0; i<timeSteps.size(); i++){
bw.write(((ReactionTime)timeSteps.get(i)).time + " ");
}
bw.write("\n");
}
bw.write( tBegin+" "+tEnd+ "\n");
for (int i=0; i<nState; i++)
bw.write(y[i]+" ");
bw.write("\n");
for (int i=0; i<nState; i++)
bw.write(yprime[i]+" ");
bw.write("\n");
for (int i=0; i<30; i++)
bw.write(info[i]+" ");
bw.write("\n"+ rtol + " "+atol);
bw.write("\n" + thermoString.toString() + "\n" + p_temperature.getK() + " " + p_pressure.getPa() + "\n" + rList.size() + "\n" + rString.toString() + "\n" + thirdBodyList.size() + "\n"+tbrString.toString() + "\n" + troeList.size() + "\n" + troeString.toString()+"\n" + lindemannList.size() + "\n" + lindemannString.toString() + "\n");
// Add list of flags for constantConcentration
// one for each species, and a final one for the volume
// if 1: will not change the number of moles of that species (or the volume)
// if 0: will integrate the ODE as normal
// eg. liquid phase calculations with a constant concentration of O2 (the solubility limit - replenished from the gas phase)
// for normal use, this will be a sequence of '0 's
getConcentractionFlags(p_reactionModel);
}
catch (IOException e) {
System.err.println("Problem writing Solver Input File!");
e.printStackTrace();
}
//this should be the end of the input file
try{
bw.close();
}
catch (IOException e) {
System.err.println("Problem closing Solver Input File!");
e.printStackTrace();
}
int idid=0;
int temp = 1;
Global.solverPrepossesor = Global.solverPrepossesor + (System.currentTimeMillis() - startTime)/1000/60;
LinkedList systemSnapshotList = callSolverSEN(iterNum, p_reactionModel, p_beginStatus);
return systemSnapshotList;
//
}
private LinkedList callSolverSEN(int p_numSteps, ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
double startTime = System.currentTimeMillis();
String workingDirectory = System.getProperty("RMG.workingDirectory");
LinkedList systemSnapshotList = new LinkedList();
ReactionTime beginT = new ReactionTime(0.0, "sec");
ReactionTime endT;
//write the input file
// File SolverInput = new File("ODESolver/SolverInput.dat");
// try {
// FileWriter fw = new FileWriter(SolverInput);
// fw.write(outputString.toString());
// fw.close();
// } catch (IOException e) {
// System.err.println("Problem writing Solver Input File!");
// e.printStackTrace();
Global.writeSolverFile +=(System.currentTimeMillis()-startTime)/1000/60;
//run the solver on the input file
boolean error = false;
try {
// system call for therfit
String[] command = {workingDirectory + "/software/ODESolver/daspkAUTO.exe"};
File runningDir = new File("ODESolver");
Process ODESolver = Runtime.getRuntime().exec(command, null, runningDir);
InputStream is = ODESolver.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
//System.out.println(line);
line = line.trim();
//if (!(line.contains("ODESOLVER SUCCESSFUL"))) {
System.out.println(line);
//error = true;
}
int exitValue = 4;
exitValue = ODESolver.waitFor();
//System.out.println(br.readLine() + exitValue);
}
catch (Exception e) {
String err = "Error in running ODESolver \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
startTime = System.currentTimeMillis();
//read the result
File SolverOutput = new File("ODESolver/SolverOutput.dat");
try {
FileReader fr = new FileReader(SolverOutput);
BufferedReader br = new BufferedReader(fr);
String line ;
double presentTime = 0;
for (int k=0; k<p_numSteps; k++){
line = br.readLine();
if (Double.parseDouble(line.trim()) != neq) {
System.out.println("ODESolver didnt generate all species result");
System.exit(0);
}
presentTime = Double.parseDouble(br.readLine().trim());
endT = new ReactionTime(presentTime, "sec");
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
y[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
for (int i=0; i<nParameter+1; i++){
for (int j=0; j<nState; j++) {
line = br.readLine();
yprime[i*nState + j] = Double.parseDouble(line.trim());
}
line = br.readLine();
}
reactionFlux = new double[rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size()];
for (int i=0; i<rList.size()+thirdBodyList.size()+troeList.size()+lindemannList.size(); i++){
line = br.readLine();
reactionFlux[i] = Double.parseDouble(line.trim());
}
LinkedHashMap speStatus = new LinkedHashMap();
double [] senStatus = new double[nParameter*nState];
System.out.println("After ODE: from " + String.valueOf(beginT.time) + " SEC to " + String.valueOf(endT.time) + "SEC");
speStatus = generateSpeciesStatus(p_reactionModel, y, yprime, nParameter);
senStatus = generateSensitivityStatus(p_reactionModel,y,yprime,nParameter);
SystemSnapshot sss = new SystemSnapshot(endT, speStatus, senStatus, p_beginStatus.getTemperature(), p_beginStatus.getPressure());
// sss.inertGas = p_beginStatus.inertGas; //gmagoon 6/23/09: copy inertGas information from initialStatus
sss.inertGas = new LinkedHashMap();//zero out the inert gas info (in principal, this should already be null, but this is done "just-in-case")
//total the concentrations of non-inert species
double totalNonInertConc = totalNonInertConcentrations();
//calculate the scale factor needed to account for volume change
double inertScaleFactor = 1;
if(p_beginStatus.inertGas != null){//8/4/09 gmagoon: make sure inert gas is defined; otherwise, we will have issues with getTotalInertGas() when we start from non-zero time, as jdmo encountered (null-pointer exception)
if(p_beginStatus.getTotalInertGas() > 0){//this check will ensure we don't try to divide by zero; otherwise, we will end up setting new concentration to be 0.0*Infinity=NaN
inertScaleFactor = (p_beginStatus.getTotalMole()- totalNonInertConc)/p_beginStatus.getTotalInertGas();
}
//scale the initial concentrations of the inertGas to account for volume change
for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) {
String inertName = (String)iter.next();
double originalInertConc = p_beginStatus.getInertGas(inertName);
sss.putInertGas(inertName, originalInertConc*inertScaleFactor);
}
}
sss.setIDTranslator(IDTranslator);
LinkedList reactionList = new LinkedList();
reactionList.addAll(rList);
reactionList.addAll(duplicates);
reactionList.addAll(thirdBodyList);
reactionList.addAll(troeList);
reactionList.addAll(lindemannList);
sss.setReactionList(reactionList);
systemSnapshotList.add(sss);
sss.setReactionFlux(reactionFlux);
beginT = endT;
//tEnd = tEnd.add(tStep);
}
}
catch (IOException e) {
String err = "Error in reading Solver Output File! \n";
err += e.toString();
e.printStackTrace();
System.exit(0);
}
Global.readSolverFile += (System.currentTimeMillis() - startTime)/1000/60;
return systemSnapshotList;
}
@Override
protected void initializeWorkSpace() {
super.initializeWorkSpace();
info[4] = 1; //use analytical jacobian
if (nParameter != 0) {
info[18] = nParameter; //the number of parameters
info[19] = 2; //perform senstivity analysis
info[24] = 1;//staggered corrector method is used
}
}
@Override
protected void initializeConcentrations(SystemSnapshot p_beginStatus, ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, LinkedList initialSpecies) {
super.initializeConcentrations(p_beginStatus, p_reactionModel,
p_beginTime, p_endTime, initialSpecies);
if (nParameter != 0){//svp
double [] sensitivityStatus = new double[nState*nParameter];
int speciesNumber = p_reactionModel.getSpeciesNumber();
for (int i=0; i<nParameter*speciesNumber;i++){
sensitivityStatus[i] = 0;
}
p_beginStatus.addSensitivity(sensitivityStatus);
}
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Registration;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.LeapData;
import org.myrobotlab.service.data.LeapHand;
import org.myrobotlab.service.data.PinData;
import org.myrobotlab.service.interfaces.LeapDataListener;
import org.myrobotlab.service.interfaces.PinArrayListener;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* InMoovHand - The Hand sub service for the InMoov Robot. This service has 6
* servos controlled by an ServoController.
* thumb,index,majeure,ringFinger,pinky, and wrist
*
* There is also leap motion support.
*/
public class InMoov2Hand extends Service implements LeapDataListener, PinArrayListener {
public final static Logger log = LoggerFactory.getLogger(InMoov2Hand.class);
private static final long serialVersionUID = 1L;
/**
* peer services
*/
transient public LeapMotion leap;
transient public ServoController controller;
transient public ServoControl thumb;
transient public ServoControl index;
transient public ServoControl majeure;
transient public ServoControl ringFinger;
transient public ServoControl pinky;
transient public ServoControl wrist;
// The pins for the finger tip sensors
public String[] sensorPins = new String[] { "A0", "A1", "A2", "A3", "A4" };
// public int[] sensorLastValues = new int[] {0,0,0,0,0};
public boolean sensorsEnabled = false;
public int[] sensorThresholds = new int[] { 500, 500, 500, 500, 500 };
/**
* list of names of possible controllers
*/
public List<String> controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
public String controllerName;
boolean isAttached = false;
private int sensorPin;
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.startRightHand("COM15");
ServoController controller = (ServoController) Runtime.getService("i01.right");
// arduino.pinMode(13, ServoController.OUTPUT);
// arduino.digitalWrite(13, 1);
InMoov2Hand rightHand = (InMoov2Hand) Runtime.start("r01", "InMoov2Hand");// InMoovHand("r01");
Runtime.createAndStart("gui", "SwingGui");
Runtime.createAndStart("webgui", "WebGui");
// rightHand.connect("COM12"); TEST RECOVERY !!!
rightHand.close();
rightHand.open();
rightHand.openPinch();
rightHand.closePinch();
rightHand.rest();
/*
* SwingGui gui = new SwingGui("gui"); gui.startService();
*/
} catch (Exception e) {
log.error("main threw", e);
}
}
public InMoov2Hand(String n, String id) {
super(n, id);
// FIXME - NO DIRECT REFERENCES ALL PUB SUB
// FIXME - creatPeers()
startPeers();
// createPeers()
thumb.setPin(2);
index.setPin(3);
majeure.setPin(4);
ringFinger.setPin(5);
pinky.setPin(6);
wrist.setPin(7);
/*
* thumb.setSensorPin(A0); index.setSensorPin(A1); majeure.setSensorPin(A2);
* ringFinger.setSensorPin(A3); pinky.setSensorPin(A4);
*/
// TOOD: what are the initial velocities?
// Initial rest positions?
thumb.setRest(2.0);
thumb.setPosition(2.0);
index.setRest(2.0);
index.setPosition(2.0);
majeure.setRest(2.0);
majeure.setPosition(2.0);
ringFinger.setRest(2.0);
ringFinger.setPosition(2.0);
pinky.setRest(2.0);
pinky.setPosition(2.0);
wrist.setRest(90.0);
wrist.setPosition(90.0);
setSpeed(45.0, 45.0, 45.0, 45.0, 45.0, 45.0);
}
public void bird() {
moveTo(150.0, 180.0, 0.0, 180.0, 180.0, 90.0);
}
public void onRegistered(Registration s) {
refreshControllers();
broadcastState();
}
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(ServoController.class);
return controllers;
}
// @Override
public ServoController getController() {
return controller;
}
public String getControllerName() {
String controlerName = null;
if (controller != null) {
controlerName = controller.getName();
}
return controlerName;
}
public boolean isAttached() {
if (controller != null) {
if (((Arduino) controller).getDeviceId((Attachable) this) != null) {
isAttached = true;
return true;
}
controller = null;
}
isAttached = false;
return false;
}
@Override
public void broadcastState() {
thumb.broadcastState();
index.broadcastState();
majeure.broadcastState();
ringFinger.broadcastState();
pinky.broadcastState();
wrist.broadcastState();
}
public void close() {
moveTo(130, 180, 180, 180, 180);
}
public void closePinch() {
moveTo(130, 140, 180, 180, 180);
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
public void count() {
one();
sleep(1);
two();
sleep(1);
three();
sleep(1);
four();
sleep(1);
five();
}
public void devilHorns() {
moveTo(150.0, 0.0, 180.0, 180.0, 0.0, 90.0);
}
public void disable() {
thumb.disable();
index.disable();
majeure.disable();
ringFinger.disable();
pinky.disable();
wrist.disable();
}
public boolean enable() {
thumb.enable();
index.enable();
majeure.enable();
ringFinger.enable();
pinky.enable();
wrist.enable();
return true;
}
@Deprecated
public void enableAutoDisable(Boolean param) {
setAutoDisable(param);
}
@Deprecated
public void enableAutoEnable(Boolean param) {
}
public void five() {
open();
}
public void four() {
moveTo(150.0, 0.0, 0.0, 0.0, 0.0, 90.0);
}
public void fullSpeed() {
thumb.fullSpeed();
index.fullSpeed();
majeure.fullSpeed();
ringFinger.fullSpeed();
pinky.fullSpeed();
wrist.fullSpeed();
}
/**
* this method returns the analog pins that the hand is listening to. The
* InMoovHand listens on analog pins A0-A4 for the finger tip sensors.
*
*/
@Override
public String[] getActivePins() {
// TODO Auto-generated method stub
// for the InMoov hand, we're just going to say A0 - A4 ... for now..
return sensorPins;
}
public long getLastActivityTime() {
long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime());
lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime());
return lastActivityTime;
}
@Deprecated /* use LangUtils */
public String getScript(String inMoovServiceName) {
String side = getName().contains("left") ? "left" : "right";
return String.format(Locale.ENGLISH, "%s.moveHand(\"%s\",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f)\n", inMoovServiceName, side, thumb.getCurrentInputPos(), index.getCurrentInputPos(), majeure.getCurrentInputPos(),
ringFinger.getCurrentInputPos(), pinky.getCurrentInputPos(), wrist.getCurrentInputPos());
}
public void hangTen() {
moveTo(0.0, 180.0, 180.0, 180.0, 0.0, 90.0);
}
public void map(double minX, double maxX, double minY, double maxY) {
thumb.map(minX, maxX, minY, maxY);
index.map(minX, maxX, minY, maxY);
majeure.map(minX, maxX, minY, maxY);
ringFinger.map(minX, maxX, minY, maxY);
pinky.map(minX, maxX, minY, maxY);
}
// TODO - waving thread fun
public void moveTo(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveTo(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveTo(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (log.isDebugEnabled()) {
log.debug("{}.moveTo {} {} {} {} {} {}", getName(), thumb, index, majeure, ringFinger, pinky, wrist);
}
this.thumb.moveTo(thumb);
this.index.moveTo(index);
this.majeure.moveTo(majeure);
this.ringFinger.moveTo(ringFinger);
this.pinky.moveTo(pinky);
this.wrist.moveTo(wrist);
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky) {
moveToBlocking(thumb, index, majeure, ringFinger, pinky, null);
}
public void moveToBlocking(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("init {} moveToBlocking ", getName());
moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
waitTargetPos();
log.info("end {} moveToBlocking ", getName());
}
public void ok() {
moveTo(150.0, 180.0, 0.0, 0.0, 0.0, 90.0);
}
public void one() {
moveTo(150.0, 0.0, 180.0, 180.0, 180.0, 90.0);
}
public void attach(String controllerName, int sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), sensorPin);
}
public void attach(String controllerName, String sensorPin) throws Exception {
attach((ServoController) Runtime.getService(controllerName), Integer.parseInt(sensorPin));
}
public void attach(ServoController controller, int sensorPin) {
try {
if (controller == null) {
error("setting null as controller");
return;
}
if (isAttached) {
log.info("Sensor already attached");
return;
}
this.sensorPin = sensorPin;
controller.attach(controller);
log.info("{} setController {}", getName(), controller.getName());
this.controller = controller;
controllerName = this.controller.getName();
isAttached = true;
broadcastState();
} catch (Exception e) {
error(e);
}
}
public void detach(ServoController controller) {
// let the controller you want to detach this device
if (controller != null) {
controller.detach(this);
}
// setting controller reference to null
this.controller = null;
isAttached = false;
refreshControllers();
broadcastState();
}
public void refresh() {
broadcastState();
}
@Override
public LeapData onLeapData(LeapData data) {
String side = getName().contains("left") ? "left" : "right";
if (!data.frame.isValid()) {
// TODO: we could return void here? not sure
// who wants the return value form this method.
log.info("Leap data frame not valid.");
return data;
}
LeapHand h;
if ("right".equalsIgnoreCase(side)) {
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right hand frame not valid.");
// return this hand isn't valid
return data;
}
} else if ("left".equalsIgnoreCase(side)) {
if (data.frame.hands().leftmost().isValid()) {
h = data.leftHand;
} else {
log.info("Left hand frame not valid.");
// return this frame isn't valid.
return data;
}
} else {
// side could be null?
log.info("Unknown Side or side not set on hand (Side = {})", side);
// we can default to the right side?
// TODO: come up with a better default or at least document this
// behavior.
if (data.frame.hands().rightmost().isValid()) {
h = data.rightHand;
} else {
log.info("Right(unknown) hand frame not valid.");
// return this hand isn't valid
return data;
}
}
return data;
}
// FIXME - use pub/sub attach to set this up without having this method !
@Override
public void onPinArray(PinData[] pindata) {
log.info("On Pin Data: {}", pindata.length);
if (!sensorsEnabled)
return;
// just return ? TOOD: maybe still track the last read values...
// TODO : change the interface to get a map of pin data, keyed off the name.
for (PinData pin : pindata) {
log.info("Pin Data: {}", pin);
// if (sensorPins.contains(pin.pin)) {
// // it's one of our finger pins.. let's operate on it.
// log.info("Pin Data : {} value {}", pin.pin, pin.value );
// if (sensorPins[0].equalsIgnoreCase(pin.pin)) {
// // thumb / A0
// // here we want to test the pin state.. and potentially take an action
// // based on the updated sensor pin state
// if (pin.value > sensorThresholds[0])
// thumb.stop();
// } else if (sensorPins[1].equalsIgnoreCase(pin.pin)) {
// // index / A1
// if (pin.value > sensorThresholds[1])
// index.stop();
// } else if (sensorPins[2].equalsIgnoreCase(pin.pin)) {
// // middle / A2
// if (pin.value > sensorThresholds[2])
// majeure.stop();
// } else if (sensorPins[3].equalsIgnoreCase(pin.pin)) {
// // ring / A3
// if (pin.value > sensorThresholds[3])
// ringFinger.stop();
// } else if (sensorPins[4].equalsIgnoreCase(pin.pin)) {
// // pinky / A4
// if (pin.value > sensorThresholds[4])
// pinky.stop();
}
}
public void open() {
rest();
}
public void openPinch() {
moveTo(0, 0, 180, 180, 180);
}
public void release() {
disable();
}
public void rest() {
thumb.rest();
index.rest();
majeure.rest();
ringFinger.rest();
pinky.rest();
wrist.rest();
}
@Override
public boolean save() {
super.save();
thumb.save();
index.save();
majeure.save();
ringFinger.save();
pinky.save();
wrist.save();
return true;
}
@Deprecated
public boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public void speakBlocking(String text) {
if (speech != null) {
speech.speak(text);
}
}
public void setAutoDisable(Boolean param) {
thumb.setAutoDisable(param);
index.setAutoDisable(param);
majeure.setAutoDisable(param);
ringFinger.setAutoDisable(param);
pinky.setAutoDisable(param);
wrist.setAutoDisable(param);
}
public void setPins(int thumbPin, int indexPin, int majeurePin, int ringFingerPin, int pinkyPin, int wristPin) {
log.info("setPins {} {} {} {} {} {}", thumbPin, indexPin, majeurePin, ringFingerPin, pinkyPin, wristPin);
thumb.setPin(thumbPin);
index.setPin(indexPin);
majeure.setPin(majeurePin);
ringFinger.setPin(ringFingerPin);
pinky.setPin(pinkyPin);
wrist.setPin(wristPin);
}
public void setSensorPins(int thumbSensorPin, int indexSensorPin, int majeureSensorPin, int ringFingerSensorPin, int pinkySensorPin) {
log.info("setSensorPins {} {} {} {} {}", thumbSensorPin, indexSensorPin, majeureSensorPin, ringFingerSensorPin, pinkySensorPin);
/*
* thumb.setSensorPin(thumbSensorPin); index.setSensorPin(indexSensorPin);
* majeure.setSensorPin(majeureSensorPin);
* ringFinger.setSensorPin(ringFingerSensorPin);
* pinky.setSensorPin(pinkySensorPin);
*/
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky) {
setRest(thumb, index, majeure, ringFinger, pinky, null);
}
public void setRest(double thumb, double index, double majeure, double ringFinger, double pinky, Double wrist) {
log.info("setRest {} {} {} {} {} {}", thumb, index, majeure, ringFinger, pinky, wrist);
this.thumb.setRest(thumb);
this.index.setRest(index);
this.majeure.setRest(majeure);
this.ringFinger.setRest(ringFinger);
this.pinky.setRest(pinky);
if (wrist != null) {
this.wrist.setRest(wrist);
}
}
/**
* Set the array of pins that should be listened to.
*
* @param pins
*/
public void setSensorPins(String[] pins) {
// TODO, this should probably be a sorted set.. and sensorPins itself should
// probably be a map to keep the mapping of pin to finger
this.sensorPins = pins;
}
public void setSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
this.thumb.setSpeed(thumb);
this.index.setSpeed(index);
this.majeure.setSpeed(majeure);
this.ringFinger.setSpeed(ringFinger);
this.pinky.setSpeed(pinky);
this.wrist.setSpeed(wrist);
}
@Deprecated
public void setVelocity(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
log.warn("setspeed deprecated please use setSpeed");
setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
// FIXME - if multiple systems are dependent on the ServoControl map and
// limits to be a certain value
// leap should change its output, and leave the map and limits here alone
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void startLeapTracking() throws Exception {
if (leap == null) {
leap = (LeapMotion) startPeer("leap");
}
this.index.map(90.0, 0.0, this.index.getMin(), this.index.getMax());
this.thumb.map(90.0, 50.0, this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(90.0, 0.0, this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(90.0, 0.0, this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(90.0, 0.0, this.pinky.getMin(), this.pinky.getMax());
leap.addLeapDataListener(this);
leap.startTracking();
return;
}
public void stop() {
thumb.stop();
index.stop();
majeure.stop();
ringFinger.stop();
pinky.stop();
wrist.stop();
}
// FIXME !!! - should not have LeapMotion defined here at all - it should be
// pub/sub !!!
public void stopLeapTracking() {
leap.stopTracking();
this.index.map(this.index.getMin(), this.index.getMax(), this.index.getMin(), this.index.getMax());
this.thumb.map(this.thumb.getMin(), this.thumb.getMax(), this.thumb.getMin(), this.thumb.getMax());
this.majeure.map(this.majeure.getMin(), this.majeure.getMax(), this.majeure.getMin(), this.majeure.getMax());
this.ringFinger.map(this.ringFinger.getMin(), this.ringFinger.getMax(), this.ringFinger.getMin(), this.ringFinger.getMax());
this.pinky.map(this.pinky.getMin(), this.pinky.getMax(), this.pinky.getMin(), this.pinky.getMax());
this.rest();
return;
}
public void test() {
thumb.moveTo(thumb.getCurrentInputPos() + 2);
index.moveTo(index.getCurrentInputPos() + 2);
majeure.moveTo(majeure.getCurrentInputPos() + 2);
ringFinger.moveTo(ringFinger.getCurrentInputPos() + 2);
pinky.moveTo(pinky.getCurrentInputPos() + 2);
wrist.moveTo(wrist.getCurrentInputPos() + 2);
info("test completed");
}
public void three() {
moveTo(150.0, 0.0, 0.0, 0.0, 180.0, 90.0);
}
public void thumbsUp() {
moveTo(0.0, 180.0, 180.0, 180.0, 180.0, 90.0);
}
public void two() {
victory();
}
public void victory() {
moveTo(150.0, 0.0, 0.0, 180.0, 180.0, 90.0);
}
public void waitTargetPos() {
thumb.waitTargetPos();
index.waitTargetPos();
majeure.waitTargetPos();
ringFinger.waitTargetPos();
pinky.waitTargetPos();
wrist.waitTargetPos();
}
@Override
public void detach(String controllerName) {
// TODO Auto-generated method stub
}
@Override
public boolean isAttached(String name) {
return controller != null && name.equals(controller.getName());
}
@Override
public Set<String> getAttached() {
Set<String> ret = new HashSet<String>();
if (controller != null) {
ret.add(controller.getName());
}
return ret;
}
}
|
package com.evolveum.midpoint.provisioning.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.evolveum.midpoint.common.QueryUtil;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PropertyPath;
import com.evolveum.midpoint.prism.delta.ChangeType;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.provisioning.api.ChangeNotificationDispatcher;
import com.evolveum.midpoint.provisioning.api.GenericConnectorException;
import com.evolveum.midpoint.provisioning.api.ProvisioningService;
import com.evolveum.midpoint.provisioning.api.ResourceObjectShadowChangeDescription;
import com.evolveum.midpoint.provisioning.api.ResultHandler;
import com.evolveum.midpoint.provisioning.ucf.api.Change;
import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException;
import com.evolveum.midpoint.provisioning.util.ShadowCacheUtil;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttribute;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.api_types_2.PagingType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_2.PropertyReferenceListType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.AccountShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ConnectorHostType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.FailedOperationTypeType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType;
import com.evolveum.prism.xml.ns._public.query_2.QueryType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_1.ScriptsType;
/**
* Implementation of provisioning service.
*
* It is just a "dispatcher" that routes interface calls to appropriate places.
* E.g. the operations regarding resource definitions are routed directly to the
* repository, operations of shadow objects are routed to the shadow cache and
* so on.
*
* WORK IN PROGRESS
*
* There be dragons. Beware the dog. Do not trespass.
*
* @author Radovan Semancik
*/
@Service(value = "provisioningService")
public class ProvisioningServiceImpl implements ProvisioningService {
@Autowired(required = true)
private ShadowCache shadowCache;
@Autowired(required = true)
private ResourceTypeManager resourceTypeManager;
@Autowired(required = true)
@Qualifier("cacheRepositoryService")
private RepositoryService cacheRepositoryService;
@Autowired(required = true)
private ChangeNotificationDispatcher changeNotificationDispatcher;
@Autowired(required = true)
private ConnectorTypeManager connectorTypeManager;
@Autowired(required = true)
private PrismContext prismContext;
private PrismObjectDefinition<ResourceObjectShadowType> resourceObjectShadowDefinition = null;
private static final Trace LOGGER = TraceManager.getTrace(ProvisioningServiceImpl.class);
// private static final QName TOKEN_ELEMENT_QNAME = new QName(
// SchemaConstants.NS_PROVISIONING_LIVE_SYNC, "token");
public ShadowCache getShadowCache() {
return shadowCache;
}
public void setShadowCache(ShadowCache shadowCache) {
this.shadowCache = shadowCache;
}
public ResourceTypeManager getResourceTypeManager() {
return resourceTypeManager;
}
public void setResourceTypeManager(ResourceTypeManager resourceTypeManager) {
this.resourceTypeManager = resourceTypeManager;
}
/**
* Get the value of repositoryService.
*
* @return the value of repositoryService
*/
public RepositoryService getCacheRepositoryService() {
return cacheRepositoryService;
}
/**
* Set the value of repositoryService
*
* Expected to be injected.
*
* @param repositoryService
* new value of repositoryService
*/
public void setCacheRepositoryService(RepositoryService repositoryService) {
this.cacheRepositoryService = repositoryService;
}
@SuppressWarnings("unchecked")
@Override
public <T extends ObjectType> PrismObject<T> getObject(Class<T> type, String oid, OperationResult parentResult)
throws ObjectNotFoundException,
CommunicationException, SchemaException, ConfigurationException, SecurityViolationException {
Validate.notNull(oid, "Oid of object to get must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
// LOGGER.trace("**PROVISIONING: Getting object with oid {}", oid);
// Result type for this operation
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".getObject");
result.addParam(OperationResult.PARAM_OID, oid);
result.addParam(OperationResult.PARAM_TYPE, type);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
PrismObject<T> repositoryObject = null;
try {
repositoryObject = getCacheRepositoryService().getObject(type, oid, result);
} catch (ObjectNotFoundException e) {
logFatalError(LOGGER, result, "Can't get obejct with oid " + oid + ". Reason " + e.getMessage(),
e);
// LOGGER.error("Can't get obejct with oid {}. Reason {}", oid, e);
// result.recordFatalError("Can't get object with oid " + oid +
// ". Reason: " + e.getMessage(), e);
throw e;
} catch (SchemaException ex) {
logFatalError(LOGGER, result, "Can't get obejct with oid " + oid + ". Reason " + ex.getMessage(),
ex);
// LOGGER.error("Can't get obejct with oid {}. Reason {}", oid, ex);
// result.recordFatalError("Can't get object with oid " + oid +
// ". Reason: " + ex.getMessage(), ex);
throw ex;
}
if (repositoryObject.canRepresent(ResourceObjectShadowType.class)) {
// TODO: optimization needed: avoid multiple "gets" of the same
// object
ResourceObjectShadowType shadow = null;
try {
shadow = getShadowCache().getShadow((Class<ResourceObjectShadowType>) type, oid,
(ResourceObjectShadowType) (repositoryObject.asObjectable()), result);
} catch (ObjectNotFoundException e) {
logFatalError(LOGGER, result,
"Can't get obejct with oid " + oid + ". Reason " + e.getMessage(), e);
throw e;
} catch (CommunicationException e) {
logFatalError(LOGGER, result,
"Can't get obejct with oid " + oid + ". Reason " + e.getMessage(), e);
// LOGGER.error("Can't get obejct with oid {}. Reason {}", oid,
// result.recordFatalError(e);
throw e;
} catch (SchemaException e) {
logFatalError(LOGGER, result,
"Can't get obejct with oid " + oid + ". Reason " + e.getMessage(), e);
// LOGGER.error("Can't get obejct with oid {}. Reason {}", oid,
// result.recordFatalError(e);
throw e;
} catch (ConfigurationException e) {
logFatalError(LOGGER, result,
"Can't get obejct with oid " + oid + ". Reason " + e.getMessage(), e);
// LOGGER.error("Can't get obejct with oid {}. Reason {}", oid,
// result.recordFatalError(e);
throw e;
}
// TODO: object resolving
result.recordSuccess();
// LOGGER.trace("Get object finished.");
return shadow.asPrismObject();
} else if (repositoryObject.canRepresent(ResourceType.class)) {
// Make sure that the object is complete, e.g. there is a (fresh)
// schema
try {
ResourceType completeResource = getResourceTypeManager().completeResource(
(ResourceType) repositoryObject.asObjectable(), null, result);
result.computeStatus("Resource retrieval failed");
return completeResource.asPrismObject();
} catch (ObjectNotFoundException ex) {
logFatalError(LOGGER, result, "Resource object not found", ex);
// result.recordFatalError("Resource object not found", ex);
throw ex;
} catch (SchemaException ex) {
logFatalError(LOGGER, result, "Schema violation", ex);
// result.recordFatalError("Schema violation", ex);
throw ex;
} catch (CommunicationException ex) {
logFatalError(LOGGER, result, "Error communicating with resource", ex);
// result.recordFatalError("Error communicating with resource",
throw ex;
}
} else {
result.recordSuccess();
return repositoryObject;
}
}
private void logFatalError(Trace logger, OperationResult opResult, String message, Exception ex) {
logger.error(message, ex);
opResult.recordFatalError(message, ex);
}
@Override
public <T extends ObjectType> String addObject(PrismObject<T> object, ScriptsType scripts,
OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException,
CommunicationException, ObjectNotFoundException, ConfigurationException, SecurityViolationException {
// TODO
Validate.notNull(object, "Object to add must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("**PROVISIONING: Start to add object {}", object);
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".addObject");
result.addParam("object", object);
result.addParam("scripts", scripts);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
String oid = null;
if (object.canRepresent(ResourceObjectShadowType.class)) {
try {
// calling shadow cache to add object
oid = getShadowCache().addShadow((ResourceObjectShadowType) object.asObjectable(), scripts,
null, result);
LOGGER.trace("**PROVISIONING: Added shadow object {}", oid);
result.recordSuccess();
} catch (GenericFrameworkException ex) {
logFatalError(LOGGER, result,
"Couldn't add object " + object + ". Reason: " + ex.getMessage(), ex);
// LOGGER.error("**PROVISIONING: Can't add object {}. Reason {}",
// object, ex);
// result.recordFatalError("Failed to add shadow object: " +
// ex.getMessage(), ex);
throw new CommunicationException(ex.getMessage(), ex);
} catch (SchemaException ex) {
logFatalError(LOGGER, result, "Couldn't add object. Reason: " + ex.getMessage(), ex);
// LOGGER.error("**PROVISIONING: Couldn't add object. Reason: {}",
// ex.getMessage(), ex);
// result.recordFatalError("Couldn't add object. Reason: " +
// ex.getMessage(), ex);
throw new SchemaException("Couldn't add object. Reason: " + ex.getMessage(), ex);
} catch (ObjectAlreadyExistsException ex) {
logFatalError(LOGGER, result,
"Couldn't add object. Object already exist, " + ex.getMessage(), ex);
// result.recordFatalError("Could't add object. Object already exist, "
// + ex.getMessage(), ex);
throw new ObjectAlreadyExistsException("Could't add object. Object already exist, "
+ ex.getMessage(), ex);
} catch (ConfigurationException ex) {
logFatalError(LOGGER, result, "Couldn't add object. Configuration error, " + ex.getMessage(),
ex);
// result.recordFatalError("Could't add object. Configuration error, "
// + ex.getMessage(), ex);
throw ex;
} catch (SecurityViolationException ex) {
logFatalError(LOGGER, result, "Couldn't add object. Security violation: " + ex.getMessage(),
ex);
throw ex;
}
} else {
oid = cacheRepositoryService.addObject(object, result);
}
LOGGER.trace("**PROVISIONING: Adding object finished.");
return oid;
}
@Override
public int synchronize(String resourceOid, Task task, OperationResult parentResult)
throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException {
Validate.notNull(resourceOid, "Resource oid must not be null.");
Validate.notNull(task, "Task must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".synchronize");
result.addParam(OperationResult.PARAM_OID, resourceOid);
result.addParam(OperationResult.PARAM_TASK, task);
int processedChanges = 0;
try {
// Resolve resource
PrismObject<ResourceType> resourceObject = getObject(ResourceType.class, resourceOid, result);
ResourceType resourceType = resourceObject.asObjectable();
LOGGER.trace("**PROVISIONING: Start synchronization of resource {} ",
SchemaDebugUtil.prettyPrint(resourceType));
// getting token form task
PrismProperty tokenProperty = null;
if (task.getExtension() != null) {
tokenProperty = task.getExtension(SchemaConstants.SYNC_TOKEN);
}
if (tokenProperty != null
&& (tokenProperty.getValue() == null || tokenProperty.getValue().getValue() == null)) {
LOGGER.warn("Sync token exists, but it is empty (null value). Ignoring it.");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Empty sync token property:\n{}", tokenProperty.dump());
}
tokenProperty = null;
}
// if the token is not specified in the task, get the latest token
if (tokenProperty == null) {
tokenProperty = getShadowCache().fetchCurrentToken(resourceType, parentResult);
if (tokenProperty == null || tokenProperty.getValue() == null
|| tokenProperty.getValue().getValue() == null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Empty current sync token property:\n{}", tokenProperty.dump());
}
throw new IllegalStateException("Current sync token null or empty: " + tokenProperty);
}
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("**PROVISIONING: Got token property: {} from the task extension.",
SchemaDebugUtil.prettyPrint(tokenProperty));
}
// Collection<PropertyDelta> taskModifications = new
// ArrayList<PropertyDelta>();
List<Change> changes = null;
LOGGER.trace("Calling shadow cache to fetch changes.");
changes = getShadowCache().fetchChanges(resourceType, tokenProperty, result);
LOGGER.trace("Changes returned to ProvisioningServiceImpl:\n{}", changes);
// for each change from the connector create change description
for (Change change : changes) {
// this is the case,when we want to skip processing of change,
// because the shadow was not created or found to the resource
// object
// it may be caused with the fact, that the object which was
// created in the resource was deleted before the sync run
// such a change should be skipped to process consistent changes
if (change.getOldShadow() == null) {
PrismProperty<?> newToken = change.getToken();
task.setExtensionProperty(newToken);
// PropertyDelta modificatedToken =
// getTokenModification(newToken);
// taskModifications.add(modificatedToken);
processedChanges++;
LOGGER.debug("Skipping processing change. Can't find appropriate shadow (e.g. the object was deleted on the resource meantime).");
continue;
}
ResourceObjectShadowChangeDescription shadowChangeDescription = createResourceShadowChangeDescription(
change, resourceType);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("**PROVISIONING: Created resource object shadow change description {}",
SchemaDebugUtil.prettyPrint(shadowChangeDescription));
}
OperationResult notifyChangeResult = new OperationResult(ProvisioningService.class.getName()
+ "notifyChange");
notifyChangeResult.addParam("resourceObjectShadowChangeDescription", shadowChangeDescription);
try {
notifyResourceObjectChangeListeners(shadowChangeDescription, task, notifyChangeResult);
notifyChangeResult.recordSuccess();
} catch (RuntimeException ex) {
logFatalError(LOGGER, notifyChangeResult, "Synchronization error: " + ex.getMessage(), ex);
// notifyChangeResult.recordFatalError("Runtime exception occur: "
// + ex.getMessage(), ex);
saveAccountResult(shadowChangeDescription, change, notifyChangeResult, parentResult);
// LOGGER.error("Synchronization error: "+ ex.getMessage(),
throw new SystemException("Synchronization error: " + ex.getMessage(), ex);
}
notifyChangeResult.computeStatus("Error by notify change operation.");
if (notifyChangeResult.isSuccess()) {
deleteShadowFromRepo(change, parentResult);
// get updated token from change,
// create property modification from new token
// and replace old token with the new one
PrismProperty<?> newToken = change.getToken();
task.setExtensionProperty(newToken);
// PropertyDelta modificatedToken =
// getTokenModification(newToken);
// taskModifications.add(modificatedToken);
processedChanges++;
} else {
saveAccountResult(shadowChangeDescription, change, notifyChangeResult, parentResult);
}
}
// also if no changes was detected, update token
if (changes.isEmpty()) {
LOGGER.trace("No changes to synchronize on " + ObjectTypeUtil.toShortString(resourceType));
task.setExtensionProperty(tokenProperty);
// PropertyDelta modificatedToken =
// getTokenModification(tokenProperty);
// taskModifications.add(modificatedToken);
}
// task.modify(taskModifications, result);
task.savePendingModifications(result);
// This happens in the (scheduled async) task. Recording of results
// in the task is still not
// ideal, therefore also log the errors with a full stack trace.
} catch (ObjectNotFoundException e) {
logFatalError(LOGGER, result, "Synchronization error: object not found: " + e.getMessage(), e);
// LOGGER.error("Synchronization error: object not found: {}",
// e.getMessage(), e);
// result.recordFatalError(e.getMessage(), e);
throw e;
} catch (CommunicationException e) {
logFatalError(LOGGER, result, "Synchronization error: communication problem: " + e.getMessage(),
e);
// LOGGER.error("Synchronization error: communication problem: {}",
// e.getMessage(), e);
// result.recordFatalError("Error communicating with connector: " +
// e.getMessage(), e);
throw e;
} catch (GenericFrameworkException e) {
logFatalError(LOGGER, result,
"Synchronization error: generic connector framework error: " + e.getMessage(), e);
// LOGGER.error("Synchronization error: generic connector framework error: {}",
// e.getMessage(), e);
// result.recordFatalError(e.getMessage(), e);
throw new GenericConnectorException(e.getMessage(), e);
} catch (SchemaException e) {
logFatalError(LOGGER, result, "Synchronization error: schema problem: " + e.getMessage(), e);
// LOGGER.error("Synchronization error: schema problem: {}",
// e.getMessage(), e);
// result.recordFatalError(e.getMessage(), e);
throw e;
} catch (SecurityViolationException e) {
logFatalError(LOGGER, result, "Synchronization error: security violation: " + e.getMessage(), e);
throw e;
} catch (ConfigurationException e) {
logFatalError(LOGGER, result, "Synchronization error: configuration problem: " + e.getMessage(),
e);
// LOGGER.error("Synchronization error: configuration problem: {}",
// e.getMessage(), e);
// result.recordFatalError(e.getMessage(), e);
throw e;
} catch (RuntimeException e) {
logFatalError(LOGGER, result, "Synchronization error: unexpected problem: " + e.getMessage(), e);
// LOGGER.error("Synchronization error: unexpected problem: {}",
// e.getMessage(), e);
// result.recordFatalError(e.getMessage(), e);
throw e;
}
result.recordSuccess();
return processedChanges;
}
@Override
public <T extends ObjectType> List<PrismObject<T>> listObjects(Class<T> objectType, PagingType paging,
OperationResult parentResult) {
Validate.notNull(objectType, "Object type to list must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("**PROVISIONING: Start listing objects of type {}", objectType);
// Result type for this operation
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".listObjects");
result.addParam("objectType", objectType);
result.addParam("paging", paging);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
List<PrismObject<T>> objListType = null;
// TODO: should listing connectors trigger rediscovery?
// if (ConnectorType.class.isAssignableFrom(objectType)) {
// Set<ConnectorType> connectors = getShadowCache()
// .getConnectorFactory().listConnectors();
// if (connectors == null) {
// result.recordFatalError("Can't list connectors.");
// if (connectors.isEmpty()) {
// LOGGER.debug("There are no connectors known to the system.");
// objListType = new ObjectListType();
// for (ConnectorType connector : connectors) {
// objListType.getObject().add(connector);
// result.recordSuccess();
// return objListType;
if (ResourceObjectShadowType.class.isAssignableFrom(objectType)) {
// Listing of shadows is not supported because this operation does
// not specify resource
// to search. Maybe we need another operation for this.
result.recordFatalError("Listing of shadows is not supported");
throw new NotImplementedException("Listing of shadows is not supported");
} else {
// TODO: delegate to repository
objListType = getCacheRepositoryService().listObjects(objectType, paging, parentResult);
}
if (ResourceType.class.equals(objectType)) {
List<PrismObject<T>> newObjListType = new ArrayList<PrismObject<T>>();
for (PrismObject<T> obj : objListType) {
OperationResult objResult = new OperationResult(ProvisioningService.class.getName()
+ ".listObjects.object");
PrismObject<ResourceType> resource = (PrismObject<ResourceType>) obj;
ResourceType completeResource;
try {
completeResource = getResourceTypeManager().completeResource(resource.asObjectable(),
null, objResult);
newObjListType.add(completeResource.asPrismObject());
// TODO: what do to with objResult??
} catch (ObjectNotFoundException e) {
LOGGER.error("Error while completing {}: {}. Using non-complete resource.", new Object[] {
resource, e.getMessage(), e });
objResult.recordFatalError(e);
obj.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(obj);
result.addSubresult(objResult);
result.recordPartialError(e);
} catch (SchemaException e) {
LOGGER.error("Error while completing {}: {}. Using non-complete resource.", new Object[] {
resource, e.getMessage(), e });
objResult.recordFatalError(e);
obj.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(obj);
result.addSubresult(objResult);
result.recordPartialError(e);
} catch (CommunicationException e) {
LOGGER.error("Error while completing {}: {}. Using non-complete resource.", new Object[] {
resource, e.getMessage(), e });
objResult.recordFatalError(e);
obj.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(obj);
result.addSubresult(objResult);
result.recordPartialError(e);
} catch (ConfigurationException e) {
LOGGER.error("Error while completing {}: {}. Using non-complete resource.", new Object[] {
resource, e.getMessage(), e });
objResult.recordFatalError(e);
obj.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(obj);
result.addSubresult(objResult);
result.recordPartialError(e);
} catch (RuntimeException e) {
// FIXME: Strictly speaking, the runtime exception should
// not be handled here.
// The runtime exceptions should be considered fatal anyway
// ... but some of the
// ICF exceptions are still translated to system exceptions.
// So this provides
// a better robustness now.
LOGGER.error("System error while completing {}: {}. Using non-complete resource.",
new Object[] { resource, e.getMessage(), e });
objResult.recordFatalError(e);
obj.asObjectable().setFetchResult(objResult.createOperationResultType());
newObjListType.add(obj);
result.addSubresult(objResult);
result.recordPartialError(e);
}
}
result.computeStatus();
result.recordSuccessIfUnknown();
return newObjListType;
}
result.recordSuccess();
return objListType;
}
@Override
public <T extends ObjectType> List<PrismObject<T>> searchObjects(Class<T> type, QueryType query,
PagingType paging, OperationResult parentResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, SecurityViolationException {
//TODO reimplement !!!!!!!!!!!
if (query == null) {
return listObjects(type, paging, parentResult);
}
final List<PrismObject<T>> objListType = new ArrayList<PrismObject<T>>();
final ResultHandler<T> handler = new ResultHandler<T>() {
@SuppressWarnings("unchecked")
@Override
public boolean handle(PrismObject<T> object, OperationResult parentResult) {
return objListType.add(object);
}
};
searchObjectsIterative(type, query, paging, handler, parentResult);
return objListType;
}
public <T extends ObjectType> int countObjects(Class<T> type, QueryType query,
OperationResult parentResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException {
// TODO: Implement !!!!!
OperationResult result = parentResult.createSubresult("REIMPLEMENT !!!!!!!!!!!!!!!");
int count = 0;
try {
count = cacheRepositoryService.countObjects(type, query, result);
} catch (Exception ex) {
throw new SystemException(ex.getMessage(), ex);
}
return count;
}
@Override
public <T extends ObjectType> void modifyObject(Class<T> type, String oid,
Collection<? extends ItemDelta> modifications, ScriptsType scripts, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
Validate.notNull(oid, "OID must not be null.");
Validate.notNull(modifications, "Modifications must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".modifyObject");
result.addParam("modifications", modifications);
result.addParam(OperationResult.PARAM_OID, oid);
result.addParam("scripts", scripts);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("*PROVISIONING: modifyObject: object modifications:\n{}",
DebugUtil.debugDump(modifications));
}
// getting object to modify
PrismObject<T> object = getCacheRepositoryService().getObject(type, oid, parentResult);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("**PROVISIONING: modifyObject: object to modify:\n{}.", object.dump());
}
try {
// calling shadow cache to modify object
getShadowCache().modifyShadow(object.asObjectable(), null, oid, modifications, scripts,
parentResult);
result.recordSuccess();
} catch (CommunicationException e) {
logFatalError(LOGGER, result, "Couldn't modify object: communication problem: " + e.getMessage(),
e);
// result.recordFatalError(e);
throw e;
} catch (GenericFrameworkException e) {
logFatalError(LOGGER, result,
"Couldn't modify object: generic error in the connector: " + e.getMessage(), e);
// result.recordFatalError(e);
throw new CommunicationException(e.getMessage(), e);
} catch (SchemaException e) {
logFatalError(LOGGER, result, "Couldn't modify object: schema problem: " + e.getMessage(), e);
// result.recordFatalError(e);
throw e;
} catch (ObjectNotFoundException e) {
logFatalError(LOGGER, result, "Couldn't modify object: object doesn't exist: " + e.getMessage(),
e);
// result.recordFatalError(e);
throw e;
} catch (RuntimeException e) {
logFatalError(LOGGER, result, "Couldn't modify object: unexpected problem: " + e.getMessage(), e);
// result.recordFatalError(e);
throw new SystemException("Internal error: " + e.getMessage(), e);
} catch (ConfigurationException e) {
logFatalError(LOGGER, result, "Couldn't modify object: configuration problem: " + e.getMessage(),
e);
// result.recordFatalError(e);
throw e;
} catch (SecurityViolationException e) {
logFatalError(LOGGER, result, "Couldn't modify object: security violation: " + e.getMessage(),
e);
throw e;
}
LOGGER.trace("Finished modifying of object with oid {}", oid);
}
@Override
public <T extends ObjectType> void deleteObject(Class<T> type, String oid, ScriptsType scripts,
OperationResult parentResult) throws ObjectNotFoundException, CommunicationException,
SchemaException, ConfigurationException, SecurityViolationException {
// TODO Auto-generated method stub
Validate.notNull(oid, "Oid of object to delete must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
LOGGER.trace("**PROVISIONING: Start to delete object with oid {}", oid);
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".deleteObject");
result.addParam("oid", oid);
result.addParam("scripts", scripts);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
PrismObject<T> object = null;
try {
object = getCacheRepositoryService().getObject(type, oid, parentResult);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("**PROVISIONING: Object from repository to delete:\n{}", object.dump());
}
} catch (SchemaException e) {
result.recordFatalError("Can't get object with oid " + oid + " from repository. Reason: "
+ e.getMessage() + " " + e);
throw new ObjectNotFoundException(e.getMessage());
}
// TODO:check also others shadow objects
if (object.canRepresent(ResourceObjectShadowType.class)) {
try {
getShadowCache().deleteShadow(object.asObjectable(), scripts, null, parentResult);
result.recordSuccess();
} catch (CommunicationException e) {
logFatalError(LOGGER, result,
"Couldn't delete object: communication problem: " + e.getMessage(), e);
// result.recordFatalError(e);
throw new CommunicationException(e.getMessage(), e);
} catch (GenericFrameworkException e) {
logFatalError(LOGGER, result,
"Couldn't delete object: generic error in the connector: " + e.getMessage(), e);
// result.recordFatalError(e);
throw new CommunicationException(e.getMessage(), e);
} catch (SchemaException e) {
logFatalError(LOGGER, result, "Couldn't delete object: schema problem: " + e.getMessage(), e);
// result.recordFatalError(e);
throw new SchemaException(e.getMessage(), e);
} catch (ConfigurationException e) {
logFatalError(LOGGER, result,
"Couldn't delete object: configuration problem: " + e.getMessage(), e);
// result.recordFatalError(e);
throw e;
}
} else {
try {
getCacheRepositoryService().deleteObject(type, oid, result);
} catch (ObjectNotFoundException ex) {
result.recordFatalError(ex);
throw ex;
}
}
LOGGER.trace("**PROVISIONING: Finished deleting object.");
result.recordSuccess();
}
@Override
public OperationResult testResource(String resourceOid) throws ObjectNotFoundException {
// We are not going to create parent result here. We don't want to
// pollute the result with
// implementation details, as this will be usually displayed in the
// table of "test resource" results.
Validate.notNull(resourceOid, "Resource OID to test is null.");
LOGGER.trace("Start testing resource with oid {} ", resourceOid);
OperationResult parentResult = new OperationResult(TEST_CONNECTION_OPERATION);
parentResult.addParam("resourceOid", resourceOid);
parentResult.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
ResourceType resourceType = null;
try {
PrismObject<ResourceType> resource = getCacheRepositoryService().getObject(ResourceType.class,
resourceOid, parentResult);
resourceType = resource.asObjectable();
resourceTypeManager.testConnection(resourceType, parentResult);
} catch (ObjectNotFoundException ex) {
throw new ObjectNotFoundException("Object with OID " + resourceOid + " not found");
} catch (SchemaException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
parentResult.computeStatus("Test resource has failed");
LOGGER.trace("Finished testing {}, result: {} ", ObjectTypeUtil.toShortString(resourceType),
parentResult.getStatus());
return parentResult;
}
@Override
public List<PrismObject<? extends ResourceObjectShadowType>> listResourceObjects(String resourceOid,
QName objectClass, PagingType paging, OperationResult parentResult) throws SchemaException,
ObjectNotFoundException, CommunicationException {
final OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".listResourceObjects");
result.addParam("resourceOid", resourceOid);
result.addParam("objectClass", objectClass);
result.addParam("paging", paging);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
if (resourceOid == null) {
throw new IllegalArgumentException("Resource not defined in a search query");
}
if (objectClass == null) {
throw new IllegalArgumentException("Objectclass not defined in a search query");
}
PrismObject<ResourceType> resource = null;
try {
resource = getCacheRepositoryService().getObject(ResourceType.class, resourceOid, result);
} catch (ObjectNotFoundException e) {
result.recordFatalError("Resource with oid " + resourceOid + "not found. Reason: " + e);
throw new ObjectNotFoundException(e.getMessage(), e);
}
final List<PrismObject<? extends ResourceObjectShadowType>> objectList = new ArrayList<PrismObject<? extends ResourceObjectShadowType>>();
final ShadowHandler shadowHandler = new ShadowHandler() {
@Override
public boolean handle(ResourceObjectShadowType shadow) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("listResourceObjects: processing shadow: {}",
SchemaDebugUtil.prettyPrint(shadow));
}
objectList.add(shadow.asPrismObject());
return true;
}
};
try {
resourceTypeManager.listShadows(resource.asObjectable(), objectClass, shadowHandler, false,
result);
} catch (ConfigurationException ex) {
parentResult.recordFatalError(ex.getMessage(), ex);
throw new CommunicationException("Error in the configuration: " + ex.getMessage(), ex);
}
return objectList;
}
@Override
public <T extends ObjectType> void searchObjectsIterative(Class<T> type, QueryType query,
PagingType paging, final ResultHandler<T> handler, final OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
Validate.notNull(query, "Search query must not be null.");
Validate.notNull(parentResult, "Operation result must not be null.");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Start to search object. Query {}", QueryUtil.dump(query));
}
final OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".searchObjectsIterative");
result.addParam("query", query);
result.addParam("paging", paging);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
Element filter = query.getFilter();
NodeList list = filter.getChildNodes();
String resourceOid = null;
QName objectClass = null;
List<NodeList> attributeFilter = new ArrayList<NodeList>();
if (QNameUtil.compareQName(SchemaConstantsGenerated.Q_AND, filter)) {
for (int i = 0; i < list.getLength(); i++) {
if (QNameUtil.compareQName(SchemaConstantsGenerated.Q_TYPE, list.item(i))) {
String filterType = list.item(i).getAttributes().getNamedItem("uri").getNodeValue();
if (filterType == null || "".equals(filterType)) {
result.recordFatalError("Object type is not defined.");
throw new IllegalArgumentException("Object type is not defined.");
}
} else if (QNameUtil.compareQName(SchemaConstantsGenerated.Q_EQUAL, list.item(i))) {
NodeList equealList = list.item(i).getChildNodes();
for (int j = 0; j < equealList.getLength(); j++) {
if (QNameUtil.compareQName(SchemaConstantsGenerated.Q_VALUE, equealList.item(j))) {
Node value = equealList.item(j).getFirstChild();
if (QNameUtil.compareQName(SchemaConstants.I_RESOURCE_REF, value)) {
resourceOid = value.getAttributes().getNamedItem("oid").getNodeValue();
LOGGER.trace("**PROVISIONING: Search objects on resource with oid {}",
resourceOid);
} else if (QNameUtil.compareQName(SchemaConstants.I_OBJECT_CLASS, value)) {
objectClass = DOMUtil.getQNameValue((Element) value);
LOGGER.trace("**PROVISIONING: Object class to search: {}", objectClass);
if (objectClass == null) {
result.recordFatalError("Object class was not defined.");
throw new IllegalArgumentException("Object class was not defined.");
}
}
} else if (QNameUtil.compareQName(SchemaConstantsGenerated.Q_PATH, equealList.item(j))){
attributeFilter.add(equealList);
continue;
}
}
}
}
}
if (resourceOid == null) {
throw new IllegalArgumentException("Resource not defined in a search query");
}
if (objectClass == null) {
throw new IllegalArgumentException("Objectclass not defined in a search query");
}
PrismObject<ResourceType> resource = null;
try {
// Don't use repository. Repository resource will not have properly
// set capabilities
resource = getObject(ResourceType.class, resourceOid, result);
} catch (ObjectNotFoundException e) {
result.recordFatalError("Resource with oid " + resourceOid + "not found. Reason: " + e);
throw new ObjectNotFoundException(e.getMessage(), e);
} catch (ConfigurationException e) {
result.recordFatalError("Configuration error regarding resource with oid " + resourceOid
+ ". Reason: " + e);
throw e;
} catch (SecurityViolationException e) {
result.recordFatalError("Security violation: " + e);
throw e;
}
List<ResourceAttribute> resourceAttributesFilter = new ArrayList<ResourceAttribute>();
if (!attributeFilter.isEmpty()) {
ResourceSchema schema = RefinedResourceSchema.getResourceSchema(resource, prismContext);
ObjectClassComplexTypeDefinition objectClassDef = schema.findObjectClassDefinition(objectClass);
for (NodeList attribute : attributeFilter) {
for (int j = 0; j < attribute.getLength(); j++) {
Node attrFilter = attribute.item(j);
if (!QNameUtil.compareQName(SchemaConstantsGenerated.Q_PATH, attrFilter)) {
QName attrName = QNameUtil.getNodeQName(attrFilter.getFirstChild());
ResourceAttributeDefinition resourceAttrDef = objectClassDef
.findAttributeDefinition(attrName);
ResourceAttribute resourceAttr = resourceAttrDef.instantiate();
resourceAttr.setRealValue(attrFilter.getFirstChild().getTextContent());
resourceAttributesFilter.add(resourceAttr);
}
}
}
}
final ShadowHandler shadowHandler = new ShadowHandler() {
@Override
public boolean handle(ResourceObjectShadowType shadowType) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("searchObjectsIterative: processing shadow: {}",
SchemaDebugUtil.prettyPrint(shadowType));
}
OperationResult accountResult = result.createSubresult(ProvisioningService.class.getName()
+ ".searchObjectsIterative.handle");
boolean doContinue = handler.handle(shadowType.asPrismObject(), accountResult);
accountResult.computeStatus();
if (!accountResult.isSuccess()) {
Collection<? extends ItemDelta> shadowModificationType = PropertyDelta
.createModificationReplacePropertyCollection(ResourceObjectShadowType.F_RESULT,
getResourceObjectShadowDefinition(),
accountResult.createOperationResultType());
try {
cacheRepositoryService.modifyObject(AccountShadowType.class, shadowType.getOid(),
shadowModificationType, result);
} catch (ObjectNotFoundException ex) {
result.recordFatalError(
"Saving of result to " + ObjectTypeUtil.toShortString(shadowType)
+ " shadow failed: Not found: " + ex.getMessage(), ex);
} catch (SchemaException ex) {
result.recordFatalError(
"Saving of result to " + ObjectTypeUtil.toShortString(shadowType)
+ " shadow failed: Schema error: " + ex.getMessage(), ex);
}
}
return doContinue;
}
};
getResourceTypeManager().searchObjectsIterative((Class<? extends ResourceObjectShadowType>) type,
objectClass, resource.asObjectable(), resourceAttributesFilter, shadowHandler, null, result);
result.recordSuccess();
}
private synchronized void notifyResourceObjectChangeListeners(
ResourceObjectShadowChangeDescription change, Task task, OperationResult parentResult) {
changeNotificationDispatcher.notifyChange(change, task, parentResult);
}
private ResourceObjectShadowChangeDescription createResourceShadowChangeDescription(Change change,
ResourceType resourceType) {
ResourceObjectShadowChangeDescription shadowChangeDescription = new ResourceObjectShadowChangeDescription();
shadowChangeDescription.setObjectDelta(change.getObjectDelta());
shadowChangeDescription.setResource(resourceType.asPrismObject());
shadowChangeDescription.setOldShadow(change.getOldShadow());
ResourceObjectShadowType currentShadowType = change.getCurrentShadow().asObjectable();
currentShadowType.setActivation(ShadowCacheUtil.completeActivation(currentShadowType, resourceType,
null));
shadowChangeDescription.setCurrentShadow(change.getCurrentShadow());
shadowChangeDescription.setSourceChannel(QNameUtil.qNameToUri(SchemaConstants.CHANGE_CHANNEL_SYNC));
return shadowChangeDescription;
}
private PropertyDelta getTokenModification(PrismProperty token) {
if (token == null) {
throw new IllegalArgumentException("Cannot create modification from a null live sync token");
}
if (token.getDefinition() == null) {
throw new IllegalArgumentException("Live sync token " + token
+ " has no definition. Cannot create modification.");
}
PropertyDelta tokenDelta = new PropertyDelta(new PropertyPath(ResourceObjectShadowType.F_EXTENSION,
token.getName()), token.getDefinition());
tokenDelta.setValuesToReplace((Collection) token.getValues());
return tokenDelta;
}
/*
* (non-Javadoc)
*
* @see
* com.evolveum.midpoint.provisioning.api.ProvisioningService#discoverConnectors
* (com.evolveum.midpoint.xml.ns._public.common.common_1.ConnectorHostType,
* com.evolveum.midpoint.common.result.OperationResult)
*/
@Override
public Set<ConnectorType> discoverConnectors(ConnectorHostType hostType, OperationResult parentResult)
throws CommunicationException {
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".discoverConnectors");
result.addParam("host", hostType);
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
Set<ConnectorType> discoverConnectors;
try {
discoverConnectors = connectorTypeManager.discoverConnectors(hostType, result);
} catch (CommunicationException ex) {
result.recordFatalError("Discovery failed", ex);
throw ex;
}
result.computeStatus("Connector discovery failed");
return discoverConnectors;
}
/*
* (non-Javadoc)
*
* @see
* com.evolveum.midpoint.provisioning.api.ProvisioningService#initialize()
*/
@Override
public void postInit(OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName()
+ ".initialize");
result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class);
// Discover local connectors
Set<ConnectorType> discoverLocalConnectors = connectorTypeManager.discoverLocalConnectors(result);
for (ConnectorType connector : discoverLocalConnectors) {
LOGGER.info("Discovered local connector {}" + ObjectTypeUtil.toShortString(connector));
}
result.computeStatus("Provisioning post-initialization failed");
}
private ObjectDelta<? extends ResourceObjectShadowType> createShadowResultModification(
ResourceObjectShadowChangeDescription shadowChangeDescription, Change change,
OperationResult shadowResult) {
String shadowOid = null;
if (change.getObjectDelta() != null && change.getObjectDelta().getOid() != null) {
shadowOid = change.getObjectDelta().getOid();
} else {
if (change.getCurrentShadow().getOid() != null) {
shadowOid = change.getCurrentShadow().getOid();
} else {
if (change.getOldShadow().getOid() != null) {
shadowOid = change.getOldShadow().getOid();
} else {
throw new IllegalArgumentException("No uid value defined for the object to synchronize.");
}
}
}
PrismObjectDefinition<ResourceObjectShadowType> shadowDefinition = ShadowCacheUtil
.getResourceObjectShadowDefinition(prismContext);
ObjectDelta<? extends ResourceObjectShadowType> shadowModification = ObjectDelta
.createModificationReplaceProperty(ResourceObjectShadowType.class, shadowOid,
SchemaConstants.C_RESULT, prismContext, shadowResult.createOperationResultType());
// ObjectDelta<? extends ResourceObjectShadowType> shadowModification =
// ObjectDelta
// .createModificationReplaceProperty(shadowOid,
// SchemaConstants.C_RESULT,
// shadowResult.createOperationResultType());
if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE) {
PrismPropertyDefinition failedOperationTypePropDef = shadowDefinition
.findPropertyDefinition(ResourceObjectShadowType.F_FAILED_OPERATION_TYPE);
PropertyDelta failedOperationTypeDelta = new PropertyDelta(
ResourceObjectShadowType.F_FAILED_OPERATION_TYPE, failedOperationTypePropDef);
failedOperationTypeDelta
.setValueToReplace(new PrismPropertyValue(FailedOperationTypeType.DELETE));
shadowModification.addModification(failedOperationTypeDelta);
}
return shadowModification;
}
private void saveAccountResult(ResourceObjectShadowChangeDescription shadowChangeDescription,
Change change, OperationResult notifyChangeResult, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
ObjectDelta<ResourceObjectShadowType> shadowModification = (ObjectDelta<ResourceObjectShadowType>) createShadowResultModification(
shadowChangeDescription, change, notifyChangeResult);
// maybe better error handling is needed
cacheRepositoryService.modifyObject(ResourceObjectShadowType.class, shadowModification.getOid(),
shadowModification.getModifications(), parentResult);
}
private void deleteShadowFromRepo(Change change, OperationResult parentResult)
throws ObjectNotFoundException {
if (change.getObjectDelta() != null && change.getObjectDelta().getChangeType() == ChangeType.DELETE
&& change.getOldShadow() != null) {
LOGGER.debug("Deleting detected shadow object form repository.");
try {
cacheRepositoryService.deleteObject(AccountShadowType.class, change.getOldShadow().getOid(),
parentResult);
} catch (ObjectNotFoundException ex) {
parentResult.recordFatalError("Can't find object " + change.getOldShadow()
+ " in repository.");
throw new ObjectNotFoundException("Can't find object " + change.getOldShadow()
+ " in repository.");
}
LOGGER.debug("Shadow object deleted successfully form repository.");
}
}
private PrismObjectDefinition<ResourceObjectShadowType> getResourceObjectShadowDefinition() {
if (resourceObjectShadowDefinition == null) {
resourceObjectShadowDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(ResourceObjectShadowType.class);
}
return resourceObjectShadowDefinition;
}
}
|
package com.ctrip.xpipe.redis.console.migration.model.impl;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.ctrip.xpipe.redis.console.migration.status.migration.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.xpipe.api.observer.Observable;
import com.ctrip.xpipe.observer.AbstractObservable;
import com.ctrip.xpipe.redis.console.migration.model.MigrationCluster;
import com.ctrip.xpipe.redis.console.migration.model.MigrationShard;
import com.ctrip.xpipe.redis.console.model.ClusterTbl;
import com.ctrip.xpipe.redis.console.model.DcTbl;
import com.ctrip.xpipe.redis.console.model.MigrationClusterTbl;
import com.ctrip.xpipe.redis.console.model.ShardTbl;
import com.ctrip.xpipe.redis.console.service.ClusterService;
import com.ctrip.xpipe.redis.console.service.DcService;
import com.ctrip.xpipe.redis.console.service.RedisService;
import com.ctrip.xpipe.redis.console.service.ShardService;
import com.ctrip.xpipe.redis.console.service.migration.MigrationService;
/**
* @author shyin
*
* Dec 8, 2016
*/
public class DefaultMigrationCluster extends AbstractObservable implements MigrationCluster {
private Logger logger = LoggerFactory.getLogger(getClass());
private MigrationStat currentStat;
private MigrationClusterTbl migrationCluster;
private List<MigrationShard> migrationShards = new LinkedList<>();
private ClusterTbl currentCluster;
private Map<Long, ShardTbl> shards;
private Map<Long, DcTbl> dcs;
private ClusterService clusterService;
private ShardService shardService;
private DcService dcService;
private RedisService redisService;
private MigrationService migrationService;
public DefaultMigrationCluster(MigrationClusterTbl migrationCluster, DcService dcService, ClusterService clusterService, ShardService shardService,
RedisService redisService,MigrationService migrationService) {
this.migrationCluster = migrationCluster;
setStatus();
this.clusterService = clusterService;
this.shardService = shardService;
this.dcService = dcService;
this.redisService = redisService;
this.migrationService = migrationService;
loadMetaInfo();
}
@Override
public MigrationStatus getStatus() {
return currentStat.getStat();
}
@Override
public MigrationClusterTbl getMigrationCluster() {
return migrationCluster;
}
@Override
public List<MigrationShard> getMigrationShards() {
return migrationShards;
}
@Override
public ClusterTbl getCurrentCluster() {
return currentCluster;
}
@Override
public Map<Long, ShardTbl> getClusterShards() {
return shards;
}
@Override
public Map<Long, DcTbl> getClusterDcs() {
return dcs;
}
@Override
public void addNewMigrationShard(MigrationShard migrationShard) {
migrationShards.add(migrationShard);
}
@Override
public void process() {
logger.info("[Process]{}-{}, {}", migrationCluster.getEventId(),getCurrentCluster().getClusterName(), this.currentStat.getStat());
this.currentStat.action();
}
@Override
public void updateStat(MigrationStat stat) {
logger.info("[UpdateStat]{}-{}, {} -> {}",
migrationCluster.getEventId(), getCurrentCluster().getClusterName(), this.currentStat.getStat(), stat.getStat());
this.currentStat = stat;
}
@Override
public void cancel() {
logger.info("[Cancel]{}-{}, {} -> Cancelled", migrationCluster.getEventId(), getCurrentCluster().getClusterName(), this.currentStat.getStat());
if(!currentStat.getStat().equals(MigrationStatus.Initiated)
&& !currentStat.getStat().equals(MigrationStatus.Checking)) {
throw new IllegalStateException(String.format("Cannot cancel while %s", this.currentStat.getStat()));
}
updateStat(new MigrationCancelledStat(this));
process();
}
@Override
public void rollback() {
logger.info("[Rollback]{}-{}, {} -> Rollback", migrationCluster.getEventId(), getCurrentCluster().getClusterName(), this.currentStat.getStat());
if(!currentStat.getStat().equals(MigrationStatus.PartialSuccess)) {
throw new IllegalStateException(String.format("Cannot rollback while %s", this.currentStat.getStat()));
}
updateStat(new MigrationRollBackStat(this));
process();
}
@Override
public void forcePublish() {
logger.info("[ForcePublish]{}-{}, {} -> ForcePublish", migrationCluster.getEventId(), getCurrentCluster().getClusterName(), this.currentStat.getStat());
if(!currentStat.getStat().equals(MigrationStatus.PartialSuccess)) {
throw new IllegalStateException(String.format("cannot cancel while %s", this.currentStat.getStat()));
}
updateStat(new MigrationForcePublishStat(this));
process();
}
@Override
public void forceEnd() {
logger.info("[ForceEnd]{}-{}, {} -> ForceEnd", migrationCluster.getEventId(), getCurrentCluster().getClusterName(), this.currentStat.getStat());
if(!currentStat.getStat().equals(MigrationStatus.ForcePublish)
&& !currentStat.getStat().equals(MigrationStatus.Publish)) {
throw new IllegalStateException(String.format("Cannot force end while %s", this.currentStat.getStat()));
}
updateStat(new MigrationForceEndStat(this));
process();
}
@Override
public void update(Object args, Observable observable) {
this.currentStat.refresh();
notifyObservers(this);
}
@Override
public ClusterService getClusterService() {
return clusterService;
}
@Override
public ShardService getShardService() {
return shardService;
}
@Override
public DcService getDcService() {
return dcService;
}
@Override
public RedisService getRedisService() {
return redisService;
}
@Override
public MigrationService getMigrationService() {
return migrationService;
}
private void setStatus() {
MigrationStatus status = MigrationStatus.valueOf(migrationCluster.getStatus());
switch(status) {
case Initiated :
currentStat = new MigrationInitiatedStat(this);
break;
case Cancelled:
currentStat = new MigrationCancelledStat(this);
break;
case Checking:
currentStat = new MigrationCheckingStat(this);
break;
case ForceFail:
currentStat = new MigrationForceFailStat(this);
break;
case ForcePublish:
currentStat = new MigrationForcePublishStat(this);
break;
case Migrating:
currentStat = new MigrationMigratingStat(this);
break;
case PartialSuccess:
currentStat = new MigrationPartialSuccessStat(this);
break;
case Publish:
currentStat = new MigrationPublishStat(this);
break;
case RollBack:
currentStat = new MigrationRollBackStat(this);
break;
case ForceEnd:
currentStat = new MigrationForceEndStat(this);
break;
case Success:
currentStat = new MigrationSuccessStat(this);
break;
default:
currentStat = new MigrationInitiatedStat(this);
break;
}
}
private void loadMetaInfo() {
this.currentCluster = getClusterService().find(migrationCluster.getClusterId());
this.shards = generateShardMap(getShardService().findAllByClusterName(currentCluster.getClusterName()));
this.dcs = generateDcMap(getDcService().findClusterRelatedDc(currentCluster.getClusterName()));
}
private Map<Long, ShardTbl> generateShardMap(List<ShardTbl> shards) {
Map<Long, ShardTbl> result = new HashMap<>();
for(ShardTbl shard : shards) {
result.put(shard.getId(), shard);
}
return result;
}
private Map<Long, DcTbl> generateDcMap(List<DcTbl> dcs) {
Map<Long, DcTbl> result = new HashMap<>();
for(DcTbl dc : dcs) {
result.put(dc.getId(), dc);
}
return result;
}
}
|
// If you edit this file, you must also edit its tests.
// For tests of this and the entire plume package, see class TestPlume.
package org.plumelib.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/*>>>
import org.checkerframework.checker.index.qual.*;
import org.checkerframework.checker.lock.qual.*;
import org.checkerframework.checker.nullness.qual.*;
import org.checkerframework.checker.regex.qual.*;
import org.checkerframework.checker.signature.qual.*;
import org.checkerframework.common.value.qual.*;
import org.checkerframework.dataflow.qual.*;
*/
/** Utility functions for Collections, ArrayList, Iterator, and Map. */
public final class CollectionsPlume {
/** This class is a collection of methods; it does not represent anything. */
private CollectionsPlume() {
throw new Error("do not instantiate");
}
/** The system-specific line separator string. */
private static final String lineSep = System.getProperty("line.separator");
/// Collections
/**
* Return the sorted version of the list. Does not alter the list. Simply calls {@code
* Collections.sort(List<T>, Comparator<? super T>)}.
*
* @return a sorted version of the list
* @param <T> type of elements of the list
* @param l a list to sort
* @param c a sorted version of the list
*/
public static <T> List<T> sortList(List<T> l, Comparator<? super T> c) {
List<T> result = new ArrayList<T>(l);
Collections.sort(result, c);
return result;
}
// This should perhaps be named withoutDuplicates to emphasize that
// it does not side-effect its argument.
/**
* Return a copy of the list with duplicates removed. Retains the original order.
*
* @param <T> type of elements of the list
* @param l a list to remove duplicates from
* @return a copy of the list with duplicates removed
*/
public static <T> List<T> removeDuplicates(List<T> l) {
HashSet<T> hs = new LinkedHashSet<T>(l);
List<T> result = new ArrayList<T>(hs);
return result;
}
/** All calls to deepEquals that are currently underway. */
private static HashSet<WeakIdentityPair<Object, Object>> deepEqualsUnderway =
new HashSet<WeakIdentityPair<Object, Object>>();
/**
* Determines deep equality for the elements.
*
* <ul>
* <li>If both are primitive arrays, uses java.util.Arrays.equals.
* <li>If both are Object[], uses java.util.Arrays.deepEquals and does not recursively call this
* method.
* <li>If both are lists, uses deepEquals recursively on each element.
* <li>For other types, just uses equals() and does not recursively call this method.
* </ul>
*
* @param o1 first value to compare
* @param o2 second value to comare
* @return true iff o1 and o2 are deeply equal
*/
@SuppressWarnings({"purity", "lock"}) // side effect to static field deepEqualsUnderway
/*@Pure*/
public static boolean deepEquals(/*@Nullable*/ Object o1, /*@Nullable*/ Object o2) {
@SuppressWarnings("interning")
boolean sameObject = (o1 == o2);
if (sameObject) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
@SuppressWarnings({"purity", "lock"}) // creates local state
WeakIdentityPair<Object, Object> mypair = new WeakIdentityPair<Object, Object>(o1, o2);
if (deepEqualsUnderway.contains(mypair)) {
return true;
}
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.deepEquals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof List<?> && o2 instanceof List<?>) {
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
if (l1.size() != l2.size()) {
return false;
}
try {
deepEqualsUnderway.add(mypair);
for (int i = 0; i < l1.size(); i++) {
Object e1 = l1.get(i);
Object e2 = l2.get(i);
if (!deepEquals(e1, e2)) {
return false;
}
}
} finally {
deepEqualsUnderway.remove(mypair);
}
return true;
}
return o1.equals(o2);
}
/// ArrayList
/**
* Returns a vector containing the elements of the enumeration.
*
* @param <T> type of the enumeration and vector elements
* @param e an enumeration to convert to a ArrayList
* @return a vector containing the elements of the enumeration
*/
public static <T> ArrayList<T> makeArrayList(Enumeration<T> e) {
ArrayList<T> result = new ArrayList<T>();
while (e.hasMoreElements()) {
result.add(e.nextElement());
}
return result;
}
// Rather than writing something like ArrayListToStringArray, use
// v.toArray(new String[0])
// Helper method
/**
* Compute (n choose k), which is (n! / (k!(n-k)!)).
*
* @param n number of elements from which to choose
* @param k number of elements to choose
* @return n choose k, or Long.MAX_VALUE if the value would overflow
*/
private static long choose(int n, int k) {
if (n < k) {
return 0;
}
if (k == 0 || k == n) {
return 1;
}
long a = choose(n - 1, k - 1);
long b = choose(n - 1, k);
if (a < 0 || a == Long.MAX_VALUE || b < 0 || b == Long.MAX_VALUE || a + b < 0) {
return Long.MAX_VALUE;
} else {
return a + b;
}
}
/**
* Returns a list of lists of each combination (with repetition, but not permutations) of the
* specified objects starting at index {@code start} over {@code dims} dimensions, for {@code dims
* > 0}.
*
* <p>For example, createCombinations(1, 0, {a, b, c}) returns a 3-element list of singleton
* lists:
*
* <pre>
* {a}, {b}, {c}
* </pre>
*
* And createCombinations(2, 0, {a, b, c}) returns a 6-element list of 2-element lists:
*
* <pre>
* {a, a}, {a, b}, {a, c}
* {b, b}, {b, c},
* {c, c}
* </pre>
*
* @param <T> type of the input list elements, and type of the innermost output list elements
* @param dims number of dimensions: that is, size of each innermost list
* @param start initial index
* @param objs list of elements to create combinations of
* @return list of lists of length dims, each of which combines elements from objs
*/
public static <T> List<List<T>> createCombinations(
/*@Positive*/ int dims, /*@NonNegative*/ int start, List<T> objs) {
if (dims < 1) {
throw new IllegalArgumentException();
}
long numResults = choose(objs.size() + dims - 1, dims);
if (numResults > 100000000) {
throw new Error("Do you really want to create more than 100 million lists?");
}
List<List<T>> results = new ArrayList<List<T>>();
for (int i = start; i < objs.size(); i++) {
if (dims == 1) {
List<T> simple = new ArrayList<T>();
simple.add(objs.get(i));
results.add(simple);
} else {
List<List<T>> combos = createCombinations(dims - 1, i, objs);
for (List<T> lt : combos) {
List<T> simple = new ArrayList<T>();
simple.add(objs.get(i));
simple.addAll(lt);
results.add(simple);
}
}
}
return (results);
}
/**
* Returns a list of lists of each combination (with repetition, but not permutations) of integers
* from start to cnt (inclusive) over arity dimensions.
*
* <p>For example, createCombinations(1, 0, 2) returns a 3-element list of singleton lists:
*
* <pre>
* {0}, {1}, {2}
* </pre>
*
* And createCombinations(2, 10, 2) returns a 6-element list of 2-element lists:
*
* <pre>
* {10, 10}, {10, 11}, {10, 12}, {11, 11}, {11, 12}, {12, 12}
* </pre>
*
* The length of the list is (cnt multichoose arity), which is ((cnt + arity - 1) choose arity).
*
* @param arity size of each innermost list
* @param start initial value
* @param cnt maximum element value
* @return list of lists of length arity, each of which combines integers from start to cnt
*/
public static ArrayList<ArrayList<Integer>> createCombinations(
int arity, /*@NonNegative*/ int start, int cnt) {
long numResults = choose(cnt + arity - 1, arity);
if (numResults > 100000000) {
throw new Error("Do you really want to create more than 100 million lists?");
}
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
// Return a list with one zero length element if arity is zero
if (arity == 0) {
results.add(new ArrayList<Integer>());
return (results);
}
for (int i = start; i <= cnt; i++) {
ArrayList<ArrayList<Integer>> combos = createCombinations(arity - 1, i, cnt);
for (ArrayList<Integer> li : combos) {
ArrayList<Integer> simple = new ArrayList<Integer>();
simple.add(i);
simple.addAll(li);
results.add(simple);
}
}
return (results);
}
/// Iterator
/**
* Converts an Iterator to an Iterable. The resulting Iterable can be used to produce a single,
* working Iterator (the one that was passed in). Subsequent calls to its iterator() method will
* fail, because otherwise they would return the same Iterator instance, which may have been
* exhausted, or otherwise be in some indeterminate state. Calling iteratorToIterable twice on the
* same argument can have similar problems, so don't do that.
*
* @param source the Iterator to be converted to Iterable
* @param <T> the element type
* @return source, converted to Iterable
*/
public static <T> Iterable<T> iteratorToIterable(final Iterator<T> source) {
if (source == null) {
throw new NullPointerException();
}
return new Iterable<T>() {
private AtomicBoolean used = new AtomicBoolean();
@Override
public Iterator<T> iterator() {
if (used.getAndSet(true)) {
throw new Error("Call iterator() just once");
}
return source;
}
};
}
// Making these classes into functions didn't work because I couldn't get
// their arguments into a scope that Java was happy with.
/** Converts an Enumeration into an Iterator. */
public static final class EnumerationIterator<T> implements Iterator<T> {
/** The enumeration that this object wraps. */
Enumeration<T> e;
/**
* Create an Iterator that yields the elements of the given Enumeration.
*
* @param e the Enumeration to make into an Iterator
*/
public EnumerationIterator(Enumeration<T> e) {
this.e = e;
}
@Override
public boolean hasNext(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) {
return e.hasMoreElements();
}
@Override
public T next(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) {
return e.nextElement();
}
@Override
public void remove(/*>>>@GuardSatisfied EnumerationIterator<T> this*/) {
throw new UnsupportedOperationException();
}
}
/** Converts an Iterator into an Enumeration. */
@SuppressWarnings("JdkObsolete")
public static final class IteratorEnumeration<T> implements Enumeration<T> {
/** The iterator that this object wraps. */
Iterator<T> itor;
/**
* Create an Enumeration that contains the elements returned by the given Iterator.
*
* @param itor the Iterator to make an Enumeration from
*/
public IteratorEnumeration(Iterator<T> itor) {
this.itor = itor;
}
@Override
public boolean hasMoreElements() {
return itor.hasNext();
}
@Override
public T nextElement() {
return itor.next();
}
}
// This must already be implemented someplace else. Right??
/**
* An Iterator that returns first the elements returned by its first argument, then the elements
* returned by its second argument. Like {@link MergedIterator}, but specialized for the case of
* two arguments.
*/
public static final class MergedIterator2<T> implements Iterator<T> {
/** The first of the two iterators that this object merges. */
Iterator<T> itor1;
/** The second of the two iterators that this object merges. */
Iterator<T> itor2;
/**
* Create an iterator that returns the elements of {@code itor1} then those of {@code itor2}.
*
* @param itor1 an Iterator
* @param itor2 another Iterator
*/
public MergedIterator2(Iterator<T> itor1, Iterator<T> itor2) {
this.itor1 = itor1;
this.itor2 = itor2;
}
@Override
public boolean hasNext(/*>>>@GuardSatisfied MergedIterator2<T> this*/) {
return (itor1.hasNext() || itor2.hasNext());
}
@Override
public T next(/*>>>@GuardSatisfied MergedIterator2<T> this*/) {
if (itor1.hasNext()) {
return itor1.next();
} else if (itor2.hasNext()) {
return itor2.next();
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove(/*>>>@GuardSatisfied MergedIterator2<T> this*/) {
throw new UnsupportedOperationException();
}
}
// This must already be implemented someplace else. Right??
/**
* An Iterator that returns the elements in each of its argument Iterators, in turn. The argument
* is an Iterator of Iterators. Like {@link MergedIterator2}, but generalized to arbitrary number
* of iterators.
*/
public static final class MergedIterator<T> implements Iterator<T> {
/** The iterators that this object merges. */
Iterator<Iterator<T>> itorOfItors;
/**
* Create an iterator that returns the elements of the given iterators, in turn.
*
* @param itorOfItors an iterator whose elements are iterators; this MergedIterator will merge
* them all
*/
public MergedIterator(Iterator<Iterator<T>> itorOfItors) {
this.itorOfItors = itorOfItors;
}
/** The current iterator (from {@link #itorOfItors}) that is being iterated over. */
// Initialize to an empty iterator to prime the pump.
Iterator<T> current = new ArrayList<T>().iterator();
@Override
public boolean hasNext(/*>>>@GuardSatisfied MergedIterator<T> this*/) {
while ((!current.hasNext()) && (itorOfItors.hasNext())) {
current = itorOfItors.next();
}
return current.hasNext();
}
@Override
public T next(/*>>>@GuardSatisfied MergedIterator<T> this*/) {
hasNext(); // for side effect
return current.next();
}
@Override
public void remove(/*>>>@GuardSatisfied MergedIterator<T> this*/) {
throw new UnsupportedOperationException();
}
}
/** An iterator that only returns elements that match the given Filter. */
@SuppressWarnings("assignment.type.incompatible") // problems in DFF branch
public static final class FilteredIterator<T> implements Iterator<T> {
/** The iterator that this object is filtering. */
Iterator<T> itor;
/** The predicate that determines which elements to retain. */
Filter<T> filter;
/**
* Create an iterator that only returns elements of {@code itor} that match the given Filter.
*
* @param itor the Iterator to filter
* @param filter the predicate that determines which elements to retain
*/
public FilteredIterator(Iterator<T> itor, Filter<T> filter) {
this.itor = itor;
this.filter = filter;
}
/** A marker object, distinct from any object that the iterator can return. */
@SuppressWarnings("unchecked")
T invalidT = (T) new Object();
/**
* The next object that this iterator will yield, or {@link #invalidT} if {@link #currentValid}
* is false.
*/
T current = invalidT;
/** True iff {@link #current} is an object from the wrapped iterator. */
boolean currentValid = false;
@Override
public boolean hasNext(/*>>>@GuardSatisfied FilteredIterator<T> this*/) {
while ((!currentValid) && itor.hasNext()) {
current = itor.next();
currentValid = filter.accept(current);
}
return currentValid;
}
@Override
public T next(/*>>>@GuardSatisfied FilteredIterator<T> this*/) {
if (hasNext()) {
currentValid = false;
@SuppressWarnings("interning")
boolean ok = (current != invalidT);
assert ok;
return current;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove(/*>>>@GuardSatisfied FilteredIterator<T> this*/) {
throw new UnsupportedOperationException();
}
}
/**
* Returns an iterator just like its argument, except that the first and last elements are
* removed. They can be accessed via the getFirst and getLast methods.
*/
@SuppressWarnings("assignment.type.incompatible") // problems in DFF branch
public static final class RemoveFirstAndLastIterator<T> implements Iterator<T> {
/** The wrapped iterator. */
Iterator<T> itor;
/** A marker object, distinct from any object that the iterator can return. */
@SuppressWarnings("unchecked")
T nothing = (T) new Object();
// I don't think this works, because the iterator might itself return null
// /*@Nullable*/ T nothing = (/*@Nullable*/ T) null;
/** The first object yielded by the wrapped iterator. */
T first = nothing;
/** The next object that this iterator will return. */
T current = nothing;
/**
* Create an iterator just like {@code itor}, except without its first and last elements.
*
* @param itor an itorator whose first and last elements to discard
*/
public RemoveFirstAndLastIterator(Iterator<T> itor) {
this.itor = itor;
if (itor.hasNext()) {
first = itor.next();
}
if (itor.hasNext()) {
current = itor.next();
}
}
@Override
public boolean hasNext(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) {
return itor.hasNext();
}
@Override
public T next(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) {
if (!itor.hasNext()) {
throw new NoSuchElementException();
}
T tmp = current;
current = itor.next();
return tmp;
}
/**
* Return the first element of the iterator that was used to construct this. This value is not
* part of this iterator (unless the original iterator would have returned it multiple times).
*
* @return the first element of the iterator that was used to construct this
*/
public T getFirst() {
@SuppressWarnings("interning") // check for equality to a special value
boolean invalid = (first == nothing);
if (invalid) {
throw new NoSuchElementException();
}
return first;
}
/**
* Return the last element of the iterator that was used to construct this. This value is not
* part of this iterator (unless the original iterator would have returned it multiple times).
*
* <p>Throws an error unless the RemoveFirstAndLastIterator has already been iterated all the
* way to its end (so the delegate is pointing to the last element).
*
* @return the last element of the iterator that was used to construct this.
*/
// TODO: This is buggy when the delegate is empty.
public T getLast() {
if (itor.hasNext()) {
throw new Error();
}
return current;
}
@Override
public void remove(/*>>>@GuardSatisfied RemoveFirstAndLastIterator<T> this*/) {
throw new UnsupportedOperationException();
}
}
/**
* Return a List containing numElts randomly chosen elements from the iterator, or all the
* elements of the iterator if there are fewer. It examines every element of the iterator, but
* does not keep them all in memory.
*
* @param <T> type of the iterator elements
* @param itor elements to be randomly selected from
* @param numElts number of elements to select
* @return list of numElts elements from itor
*/
public static <T> List<T> randomElements(Iterator<T> itor, int numElts) {
return randomElements(itor, numElts, r);
}
/** The random generator. */
private static Random r = new Random();
/**
* Return a List containing numElts randomly chosen elements from the iterator, or all the
* elements of the iterator if there are fewer. It examines every element of the iterator, but
* does not keep them all in memory.
*
* @param <T> type of the iterator elements
* @param itor elements to be randomly selected from
* @param numElts number of elements to select
* @param random the Random instance to use to make selections
* @return list of numElts elements from itor
*/
public static <T> List<T> randomElements(Iterator<T> itor, int numElts, Random random) {
// The elements are chosen with the following probabilities,
// where n == numElts:
// n n/2 n/3 n/4 n/5 ...
RandomSelector<T> rs = new RandomSelector<T>(numElts, random);
while (itor.hasNext()) {
rs.accept(itor.next());
}
return rs.getValues();
/*
ArrayList<T> result = new ArrayList<T>(numElts);
int i=1;
for (int n=0; n<numElts && itor.hasNext(); n++, i++) {
result.add(itor.next());
}
for (; itor.hasNext(); i++) {
T o = itor.next();
// test random < numElts/i
if (random.nextDouble() * i < numElts) {
// This element will replace one of the existing elements.
result.set(random.nextInt(numElts), o);
}
}
return result;
*/
}
/// Map
// In Python, inlining this gave a 10x speed improvement.
// Will the same be true for Java?
/**
* Increment the Integer which is indexed by key in the Map. If the key isn't in the Map, its old
* value is treated as 0.
*
* @param <K> type of keys in the map
* @param m map from K to Integer
* @param key the key whose value will be incremented
* @return the old value, before it was incremented
* @throws Error if the key is in the Map but maps to a non-Integer
*/
public static <K> /*@Nullable*/ Integer incrementMap(Map<K, Integer> m, T key) {
return incrementMap(m, key, 1);
}
/**
* Increment the Integer which is indexed by key in the Map. If the key isn't in the Map, its old
* value is treated as 0.
*
* @param <K> type of keys in the map
* @param m map from K to Integer
* @param key the key whose value will be incremented
* @param count how much to increment the value by
* @return the old value, before it was incremented
* @throws Error if the key is in the Map but maps to a non-Integer
*/
public static <K> /*@Nullable*/ Integer incrementMap(Map<K, Integer> m, T key, int count) {
Integer old = m.get(key);
Integer newTotal;
if (old == null) {
newTotal = count;
} else {
newTotal = old.intValue() + count;
}
return m.put(key, newTotal);
}
/**
* Returns a multi-line string representation of a map.
*
* @param <K> type of map keys
* @param <V> type of map values
* @param m map to be converted to a string
* @return a multi-line string representation of m
*/
public static <K, V> String mapToString(Map<K, V> m) {
StringBuilder sb = new StringBuilder();
mapToString(sb, m, "");
return sb.toString();
}
/**
* Write a multi-line representation of the map into the given Appendable (e.g., a StringBuilder).
*
* @param <K> type of map keys
* @param <V> type of map values
* @param sb an Appendable (such as StringBuilder) to which to write a multi-line string
* representation of m
* @param m map to be converted to a string
* @param linePrefix prefix to write at the beginning of each line
*/
public static <K, V> void mapToString(Appendable sb, Map<K, V> m, String linePrefix) {
try {
for (Map.Entry<K, V> entry : m.entrySet()) {
sb.append(linePrefix);
sb.append(Objects.toString(entry.getKey()));
sb.append(" => ");
sb.append(Objects.toString(entry.getValue()));
sb.append(lineSep);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns a sorted version of m.keySet().
*
* @param <K> type of the map keys
* @param <V> type of the map values
* @param m a map whose keyset will be sorted
* @return a sorted version of m.keySet()
*/
public static <K extends Comparable<? super K>, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet(
Map<K, V> m) {
ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet());
Collections.sort(theKeys);
return theKeys;
}
/**
* Returns a sorted version of m.keySet().
*
* @param <K> type of the map keys
* @param <V> type of the map values
* @param m a map whose keyset will be sorted
* @param comparator the Comparator to use for sorting
* @return a sorted version of m.keySet()
*/
public static <K, V> Collection</*@KeyFor("#1")*/ K> sortedKeySet(
Map<K, V> m, Comparator<K> comparator) {
ArrayList</*@KeyFor("#1")*/ K> theKeys = new ArrayList</*@KeyFor("#1")*/ K>(m.keySet());
Collections.sort(theKeys, comparator);
return theKeys;
}
/// Set
/**
* Return the object in this set that is equal to key. The Set abstraction doesn't provide this;
* it only provides "contains". Returns null if the argument is null, or if it isn't in the set.
*
* @param set a set in which to look up the value
* @param key the value to look up in the set
* @return the object in this set that is equal to key, or null
*/
public static /*@Nullable*/ Object getFromSet(Set<?> set, Object key) {
if (key == null) {
return null;
}
for (Object elt : set) {
if (key.equals(elt)) {
return elt;
}
}
return null;
}
}
|
package com.github.earchitecture.reuse.view.spring.controller;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class ListController<E, I extends Serializable> extends BasicController<E, I> implements Controller {
protected static final String ELEMENTOS = "elementos";
private final Log logger = LogFactory.getLog(getClass());
private E searchObject;
private E entity;
private Boolean autosearch = false;
private Boolean paged = true;
protected static final String SEARCH_STRING = "ss";
protected static final String SEARCH_STRING_ENCODED = "ssEncoded";
protected static final String OBJECT = "object";
protected static final String SEARCH_OBJECT = "searchobject";
protected static final String MSGS = "msgs";
protected static final String ERRORS = "errors";
}
|
package org.shypl.common.concurrent;
import org.shypl.common.util.Cancelable;
import org.shypl.common.util.LinkedQueue;
import org.slf4j.LoggerFactory;
import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class Worker {
private final Object lock = new Object();
private final Queue<Runnable> executorTasks = new LinkedQueue<>();
private final Queue<Runnable> executingThreadTasks = new LinkedQueue<>();
private final ScheduledExecutorService executor;
private boolean executing;
private long executingThreadId;
public Worker(ScheduledExecutorService executor) {
this.executor = executor;
}
public void addTask(Runnable task) {
long currentThreadId = getCurrentThreadId();
synchronized (lock) {
if (executing) {
if (currentThreadId == executingThreadId) {
executingThreadTasks.add(task);
}
else {
executorTasks.add(task);
}
return;
}
executing = true;
executingThreadId = currentThreadId;
}
new TaskRunner(task).run();
}
public Cancelable scheduleTask(Runnable task, long delay, TimeUnit unit) {
ScheduledTaskHolder holder = new ScheduledTaskHolder(task);
holder.setFuture(executor.schedule(holder, delay, unit));
return holder;
}
public Cancelable scheduleTaskPeriodic(Runnable task, long period, TimeUnit unit) {
return scheduleTaskPeriodic(task, period, period, unit);
}
public Cancelable scheduleTaskPeriodic(Runnable task, long initialDelay, long period, TimeUnit unit) {
ScheduledTaskHolder scheduledTask = new ScheduledTaskHolder(task);
scheduledTask.setFuture(executor.scheduleAtFixedRate(scheduledTask, initialDelay, period, unit));
return scheduledTask;
}
private long getCurrentThreadId() {
return Thread.currentThread().getId();
}
private class TaskRunner implements Runnable {
private Runnable task;
public TaskRunner(Runnable task) {
this.task = task;
}
@Override
public void run() {
synchronized (lock) {
executingThreadId = getCurrentThreadId();
}
runTask();
while (true) {
synchronized (lock) {
task = executingThreadTasks.poll();
if (task == null) {
executingThreadId = 0;
break;
}
}
runTask();
}
synchronized (lock) {
task = executorTasks.poll();
if (task == null) {
executing = false;
return;
}
}
executor.execute(this);
}
private void runTask() {
try {
task.run();
}
catch (Throwable e) {
LoggerFactory.getLogger(TaskRunner.class).error("Error on run task " + task.getClass().getName(), e);
}
}
}
private class ScheduledTaskHolder implements Cancelable, Runnable {
private final Runnable task;
private ScheduledFuture<?> future;
private volatile boolean actual = true;
public ScheduledTaskHolder(Runnable task) {
this.task = task;
}
@Override
public void run() {
if (actual) {
addTask(task);
}
}
@Override
public void cancel() {
ScheduledFuture<?> f = future;
if (actual) {
actual = false;
f.cancel(false);
future = null;
}
}
public void setFuture(ScheduledFuture<?> future) {
this.future = future;
}
}
}
|
package org.takes.facets.auth.codecs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.EqualsAndHashCode;
import org.takes.facets.auth.Identity;
/**
* AES codec which supports 128 bits key.
*
* <p>The class is immutable and thread-safe.
*
* @author Jason Wong (super132j@yahoo.com)
* @version $Id$
* @since 0.13.8
*/
@EqualsAndHashCode(of = { "origin", "secret", "enc", "dec" })
public final class CcAES implements Codec {
/**
* The block size constant
*/
private final static int BLOCK = 16;
/**
* Original codec.
*/
private final transient Codec origin;
/**
* The encryption key
*/
private final String key;
/**
* Constructor for the class.
* @param codec Original codec
* @param key The encryption key
* @since 0.22
*/
public CcAES(final Codec codec, final String key){
this.origin = codec;
this.key = key;
}
/**
* Constructor for the class.
* @param codec Original codec
* @param key The encryption key
*/
public CcAES(final Codec codec, final byte[] key) {
this(codec, new String(key, StandardCharsets.UTF_8));
}
@Override
public byte[] encode(final Identity identity) throws IOException {
return this.encrypt(this.origin.encode(identity));
}
@Override
public Identity decode(final byte[] bytes) throws IOException {
return this.origin.decode(this.decrypt(bytes));
}
/**
* Encrypt the given bytes using AES.
*
* @param bytes Bytes to encrypt
* @return Encrypted byte using AES algorithm
* @throws IOException for all unexpected exceptions
*/
private byte[] encrypt(final byte[] bytes) throws IOException {
this.checkBlockSize();
try {
final AlgorithmParameterSpec spec =
CcAES.createAlgorithmParameterSpec();
return this.create(Cipher.ENCRYPT_MODE, spec).doFinal(bytes);
} catch (final BadPaddingException ex) {
throw new IOException(ex);
} catch (final IllegalBlockSizeException ex) {
throw new IOException(ex);
}
}
private static AlgorithmParameterSpec createAlgorithmParameterSpec() {
final SecureRandom random = new SecureRandom();
final byte[] bytes = new byte[CcAES.BLOCK];
random.nextBytes(bytes);
return new IvParameterSpec(bytes);
}
/**
* A private method to check the block size of the key.
*/
private void checkBlockSize() {
if (this.key.length() != CcAES.BLOCK) {
throw new IllegalArgumentException(
String.format(
"the length of the AES key must be exactly %d bytes",
CcAES.BLOCK
)
);
}
}
/**
* Decrypt the given bytes using AES.
*
* @param bytes Bytes to decrypt
* @return Decrypted bytes
* @throws IOException for all unexpected exceptions
*/
private byte[] decrypt(final byte[] bytes) throws IOException {
this.checkBlockSize();
try {
final AlgorithmParameterSpec spec =
CcAES.createAlgorithmParameterSpec();
return this.create(Cipher.DECRYPT_MODE, spec).doFinal(bytes);
} catch (final BadPaddingException ex) {
throw new IOException(ex);
} catch (final IllegalBlockSizeException ex) {
throw new IOException(ex);
}
}
/**
* Create new cipher based on the valid mode from {@link Cipher} class.
* @param mode Either Cipher.ENRYPT_MODE or Cipher.DECRYPT_MODE
* @param spec The algorithm parameter spec for cipher creation
* @return The cipher
* @throws IOException For any unexpected exceptions
*/
private Cipher create(final int mode, final AlgorithmParameterSpec spec)
throws IOException {
try {
final SecretKeySpec secret = new SecretKeySpec(
this.key.getBytes(StandardCharsets.UTF_8), "AES"
);
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(mode, secret, spec);
return cipher;
} catch (final InvalidKeyException ex) {
throw new IOException(ex);
} catch (final NoSuchAlgorithmException ex) {
throw new IOException(ex);
} catch (final NoSuchPaddingException ex) {
throw new IOException(ex);
} catch (final InvalidAlgorithmParameterException ex) {
throw new IOException(ex);
}
}
}
|
package main.java.org.usfirst.frc.team4215.robot;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Victor;
public class Arm {
private Victor arm;
private Encoder enc;
private DoubleSolenoid ds;
public Arm() {
arm = new Victor(1);
enc = new Encoder(1, 2, false);
//change the ports to whichever are the correct ones
//reversed may need to be 'true', depending on how encoder is set up
ds = new DoubleSolenoid(1, 2);
//These are sample port numbers. Change them to the correct ones.
//might need to include moduleNumber in parameters
}
public void setArm(double power) {
if (power > 1) power = 1;
else if (power < -1) power = -1;
arm.set(power);
}
public double getArmPosition() {
return enc.get();
//return enc.get() / 90;
//max rotation for arm will be 90 degrees
//total CPR is 360
//therefore, this will get a number between 0 and 1
}
public double getArmPower() {
return arm.get();
}
public void armCompress() {
ds.set(DoubleSolenoid.Value.kForward);
}
public void armDecompress() {
ds.set(DoubleSolenoid.Value.kReverse);
}
public void armOff() {
ds.set(DoubleSolenoid.Value.kOff);
}
}
|
package org.workdocx.cryptolite;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class KeyWrapper {
/** The algorithm for the wrapping key: {@value #WRAP_KEY_ALGORITHM}. */
private static final String WRAP_KEY_ALGORITHM = "AES";
/** The algorithm to use for wrapping secret keys: {@value #WRAP_ALGORITHM_SYMMETRIC}. */
private static final String WRAP_ALGORITHM_SYMMETRIC = "AESWrap";
/** The algorithm to use for wrapping private keys: {@value #WRAP_ALGORITHM_ASYMMETRIC}. */
private static final String WRAP_ALGORITHM_ASYMMETRIC = "AES/ECB/PKCS7Padding";
/** The key size for the wrapping key: {@value #WRAP_KEY_SIZE}. */
private static final int WRAP_KEY_SIZE = Keys.SYMMETRIC_KEY_SIZE;
/**
* The algorithm to use for password-based key derivation, which is used to generate the
* wrapping key: {@value #PBKD_ALGORITHM}.
*/
private static final String PBKD_ALGORITHM = "PBKDF2WithHmacSHA1";
/**
* The number of iterations to perform when doing the password-based key derivation to generate
* the wrapping key: {@value #PBKD_ITERATIONS}.
*/
public static final int PBKD_ITERATIONS = 1024;
private SecretKey wrapKey;
/**
* This is the constructor you should typically use. It initialises the instance with a wrap key
* based on the given password and salt values.
*
* @param password
* The password to use as the basis for wrapping keys.
* @param salt
* A value for this can be obtained from {@link Random#generateSalt()}. You need to
* store a salt value for each password and ensure the matching one is passed in each
* time this constructor is invoked.
*/
public KeyWrapper(String password, String salt) {
wrapKey = generateKey(password, salt);
}
/**
* This constructor should only be used if you have a secure way of storing the wrap key and
* cannot generate it from a password and salt value.
* <p>
* This sets the given wrap key directly, rather than generating it.
*
* @param wrapKey
* The wrap key, base64-encoded, as returned by {@link #getWrapKey()}.
*/
public KeyWrapper(String wrapKey) {
setWrapKey(wrapKey);
}
/**
* Wraps the given {@link SecretKey} using {@value #WRAP_ALGORITHM_SYMMETRIC}.
*
* @param key
* The {@link SecretKey} to be wrapped. This method internally just calls
* {@link #wrap(Key)}, but this provides a clear naming match with
* {@link #unwrapSecretKey(String)}.
* @return A String representation (base64-encoded) of the wrapped {@link SecretKey}, for ease
* of storage.
*/
public String wrapSecretKey(SecretKey key) {
return wrap(key, WRAP_ALGORITHM_SYMMETRIC);
}
/**
* Wraps the given {@link SecretKey} using {@value #WRAP_ALGORITHM_ASYMMETRIC}.
*
* @param key
* The {@link PrivateKey} to be wrapped. This method internally just calls
* {@link #wrap(Key)}, but this provides a clear naming match with
* {@link #unwrapPrivateKey(String)}.
* @return A String representation (base64-encoded) of the wrapped {@link PrivateKey}, for ease
* of storage.
*/
public String wrapPrivateKey(PrivateKey key) {
return wrap(key, WRAP_ALGORITHM_ASYMMETRIC);
}
/**
* Encodes the given {@link PublicKey} <em>without wrapping</em>. Since a public key is public,
* this is a convenience method provided to convert it to a String for unprotected storage.
* <p>
* This method internally calls {@link Codec#toBase64String(byte[])}, passing the value of
* {@link PublicKey#getEncoded()}.
*
* @param key
* The {@link PublicKey} to be encoded.
* @return A String representation (base64-encoded) of the raw {@link PublicKey}, for ease of
* storage.
*/
public String encodePublicKey(PublicKey key) {
byte[] bytes = key.getEncoded();
return Codec.toBase64String(bytes);
}
/**
* Unwraps the given encoded {@link SecretKey}, using WRAP_ALGORITHM_SYMMETRIC.
*
* @param wrappedKey
* The wrapped key, base-64 encoded, as returned by {@link #wrapSecretKey(SecretKey)}
* .
* @return The unwrapped {@link SecretKey}.
*/
public SecretKey unwrapSecretKey(String wrappedKey) {
return (SecretKey) unwrap(wrappedKey, Keys.SYMMETRIC_ALGORITHM, Cipher.SECRET_KEY, WRAP_ALGORITHM_SYMMETRIC);
}
/**
* Unwraps the given encoded {@link PrivateKey}, using WRAP_ALGORITHM_ASYMMETRIC.
*
* @param wrappedKey
* The wrapped key, base-64 encoded, as returned by
* {@link #wrapPrivateKey(PrivateKey)} .
* @return The unwrapped {@link PrivateKey}.
*/
public PrivateKey unwrapPrivateKey(String wrappedKey) {
return (PrivateKey) unwrap(wrappedKey, Keys.ASYMMETRIC_ALGORITHM, Cipher.PRIVATE_KEY, WRAP_ALGORITHM_ASYMMETRIC);
}
public PublicKey decodePublicKey(String encodedKey) {
byte[] bytes = Codec.fromBase64String(encodedKey);
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance(Keys.ASYMMETRIC_ALGORITHM, SecurityProvider.getProviderName());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to locate algorithm " + Keys.SYMMETRIC_ALGORITHM, e);
} catch (NoSuchProviderException e) {
throw new RuntimeException("Unable to locate JCE provider. Are the BouncyCastle libraries installed?", e);
}
try {
return keyFactory.generatePublic(new X509EncodedKeySpec(bytes));
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Unable to convert key '" + encodedKey + "' to a valid public key.", e);
}
}
/**
* @return the raw wrapKey bytes, as returned by {@link SecretKey#getEncoded()} as a
* base64-encoded String. This is only useful if you want to store the key, rather than
* regenerate it from a password and salt.
*/
public String getWrapKey() {
return Codec.toBase64String(wrapKey.getEncoded());
}
/**
* @param wrapKey
* the base64-encoded wrapKey to set. This value can be obtained from
* {@link #getWrapKey()} and {@link #generateWrapKey(String, String)}. This is only
* useful if you want to initialise an instance with a previously stored key, rather
* than recomputing a key from a password and salt.
*/
public void setWrapKey(String wrapKey) {
byte[] wrapKeyBytes = Codec.fromBase64String(wrapKey);
this.wrapKey = new SecretKeySpec(wrapKeyBytes, WRAP_KEY_ALGORITHM);
}
/**
* This method generates a new key for the {@value #WRAP_KEY_ALGORITHM} algorithm, with a key
* size of {@value #WRAP_KEY_SIZE}. This method uses Password-Based Key Derivation - that is,
* for the same starting password and salt value, it will always produce the same key. This
* avoids the question of how to securely store a key-wrapping key.
*
* @param password
* The starting point to use in generating the key. This can be a password, or any
* suitably secret string. It's worth noting that, if a user's plaintext password is
* used, this makes key derivation secure, but means the key can never be recovered
* if a user forgets their password. If a different value, such as a password hash is
* used, this is not really secure, but does mean the key can be recovered if a user
* forgets their password. It's a trade-off, right?
* @param salt
* A value for this parameter can be generated by calling
* {@link Random#generateSalt()}. You'll need to store the salt value (this is ok to
* do because salt isn't particularly sensitive) and use the same salt each time in
* order to always generate the right key. Using salt is good practice as it ensures
* that keys generated from the same token will be different - i.e. if two users use
* the password "password", having a salt value avoids the generated keys being
* identical which, for example, might give away someone's password.
* @return A new key-wrapping key, based on the given password, as a base64-encoded String. This
* value is suitable for passing to {@link #setWrapKey(String)}.
*/
private SecretKey generateKey(String password, String salt) {
byte[] saltBytes = Codec.fromBase64String(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), saltBytes, PBKD_ITERATIONS, WRAP_KEY_SIZE);
SecretKeyFactory factory;
try {
// TODO: BouncyCastle only provides PBKDF2 in their JDK 1.6 releases, so try to use it, if available:
factory = SecretKeyFactory.getInstance(PBKD_ALGORITHM, SecurityProvider.getProviderName());
} catch (NoSuchAlgorithmException e) {
try {
// TODO: If PBKDF2 is not available from BouncyCastle, try to use a default provider (Sun provides PBKDF2 in JDK 1.5):
factory = SecretKeyFactory.getInstance(PBKD_ALGORITHM);
} catch (NoSuchAlgorithmException e1) {
throw new RuntimeException("Unable to locate algorithm " + PBKD_ALGORITHM, e1);
}
} catch (NoSuchProviderException e) {
throw new RuntimeException("Unable to locate JCE provider. Are the BouncyCastle libraries installed?", e);
}
Key key;
try {
key = factory.generateSecret(pbeKeySpec);
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Error generating password-based key.", e);
}
// NB: key.getAlgorithm() returns PBKDF_ALGORITHM, rather than WRAP_KEY_ALGORITHM
// but if the result of getEncoded() is used to generate a new WRAP_KEY_ALGORITHM Key,
// the WRAP_KEY_ALGORITHM key returns the same value for getEncoded().
// It is therefore safe to do this:
SecretKey wrapKey = new SecretKeySpec(key.getEncoded(), WRAP_KEY_ALGORITHM);
return wrapKey;
// If you're curious about the above comment, try the following to confirm it:
// System.out.println("PBEKey algorithm: " + key.getAlgorithm());
// System.out.println("wrapKey algorithm: " + wrapKey.getAlgorithm());
// System.out.println("PBEKey encoded: " + Codec.toBase64String(key.getEncoded()));
// System.out.println("wrapKey encoded: " + Codec.toBase64String(wrapKey.getEncoded()));
}
/**
* Wraps the given {@link Key} using the given wrap algorithm.
*
* @param key
* The {@link Key} to be wrapped. This can be a secret (symmetric) key or a private
* (asymmetric) key.
* @param wrapAlgorithm
* The algorithm to use to wrap the key. This has to be different for a
* {@link SecretKey} than for a {@link PrivateKey}.
* @return A String representation (base64-encoded) of the wrapped {@link Key}.
*/
private String wrap(Key key, String wrapAlgorithm) {
try {
Cipher cipher = Cipher.getInstance(wrapAlgorithm, SecurityProvider.getProviderName());
cipher.init(Cipher.WRAP_MODE, wrapKey, Random.getInstance());
byte[] wrappedKey = cipher.wrap(key);
return Codec.toBase64String(wrappedKey);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not locate algorithm " + wrapAlgorithm, e);
} catch (NoSuchProviderException e) {
throw new RuntimeException("Could not locate provider. Are the BouncyCastle libraries installed?", e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException("Error setting up padding for AESWrap", e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Error in key for algorithm " + wrapAlgorithm, e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException("Error in block size for algorithm " + wrapAlgorithm, e);
}
}
/**
* Unwraps the given encoded {@link PrivateKey}.
*
* @param wrappedKey
* The wrapped key, base-64 encoded, as returned by
* {@link #wrapPrivateKey(PrivateKey)} .
* @param keyAlgorithm
* The algorithm that the reconstituted key will be for.
* @param keyType
* The type of key. This should be a constant from the {@link Cipher} class.
* @param wrapAlgorithm
* The algorithm to use to unwrap the key. This has to be different for a
* {@link SecretKey} than for a {@link PrivateKey}.
* @return The unwrapped {@link PrivateKey}.
*/
private Key unwrap(String wrappedKey, String keyAlgorithm, int keyType, String wrapAlgorithm) {
try {
byte[] wrapped = Codec.fromBase64String(wrappedKey);
Cipher cipher = Cipher.getInstance(wrapAlgorithm, SecurityProvider.getProviderName());
cipher.init(Cipher.UNWRAP_MODE, wrapKey, Random.getInstance());
Key result = cipher.unwrap(wrapped, keyAlgorithm, keyType);
return result;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not locate algorithm algorithm " + wrapAlgorithm, e);
} catch (NoSuchProviderException e) {
throw new RuntimeException("Could not locate JCE provider. Are the BouncyCastle libraries installed?", e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException("Error setting up padding for algorithm " + wrapAlgorithm, e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid key for algorithm " + wrapAlgorithm, e);
}
}
}
|
package de.adorsys.android.securemobilepushtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import de.adorsys.android.securemobilepush.KeyValues;
import de.adorsys.android.securemobilepush.SmsTool;
public class MainActivity extends AppCompatActivity {
private TextView smsSenderTextView;
private TextView smsMessageTextView;
private LocalBroadcastManager localBroadcastManager;
/**
* Set Data received from Broadcast receiver to specific views
*/
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(KeyValues.INTENT_FILTER_SMS)) {
String receivedTitle = intent.getStringExtra(KeyValues.KEY_SMS_SENDER);
String receivedMessage = intent.getStringExtra(KeyValues.KEY_SMS_MESSAGE);
smsSenderTextView.setText(receivedTitle);
smsMessageTextView.setText(receivedMessage);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmsTool smsTool = new SmsTool(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
smsTool.requestSMSPermission();
}
initViews();
registerReceiver();
}
/**
* UnRegister BroadcastReceiver from Activity to prevent potential memory leaks
* and not keep receiving sms when app is in background
*/
@Override
protected void onPause() {
localBroadcastManager.unregisterReceiver(broadcastReceiver);
super.onPause();
}
/**
* Initialize Views
*/
private void initViews() {
smsSenderTextView = (TextView) findViewById(R.id.sms_sender_text_view);
smsMessageTextView = (TextView) findViewById(R.id.sms_message_text_view);
}
/**
* Register BroadcastReceiver to Activity to get data from Notification in foreground
*/
private void registerReceiver() {
localBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(KeyValues.INTENT_FILTER_SMS);
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}
}
|
package permafrost.tundra.lang;
import permafrost.tundra.io.StreamHelper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
/**
* A collection of convenience methods for working with byte[] objects.
*/
public class BytesHelper {
/**
* Disallow instantiation of this class.
*/
private BytesHelper() {}
/**
* Converts the given String to an byte[].
* @param string A String to be converted to a byte[].
* @return A byte[] representation of the given String.
*/
public static byte[] normalize(String string) {
return normalize(string, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Converts the given String to an byte[] using the given character encoding set.
* @param string A string to be converted to a byte[].
* @param charsetName The character encoding set to use.
* @return A byte[] representation of the given String.
*/
public static byte[] normalize(String string, String charsetName) {
return normalize(string, CharsetHelper.normalize(charsetName));
}
/**
* Converts the given String to an byte[] using the given character encoding set.
* @param string A string to be converted to a byte[].
* @param charset The character encoding set to use.
* @return A byte[] representation of the given String.
*/
public static byte[] normalize(String string, Charset charset) {
return string == null ? null : string.getBytes(CharsetHelper.normalize(charset));
}
/**
* Converts the given java.io.InputStream to a byte[] by reading all
* data from the stream and then closing the stream.
* @param inputStream A java.io.InputStream to be converted to a byte[]
* @return A byte[] representation of the given java.io.InputStream.
* @throws IOException If there is a problem reading from the java.io.InputStream.
*/
public static byte[] normalize(InputStream inputStream) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamHelper.copy(inputStream, out);
return out.toByteArray();
}
/**
* Normalizes the given String, byte[], or java.io.InputStream object to a byte[].
* @param object The object to be normalized to a byte[].
* @return A byte[] representation of the given object.
* @throws IOException If there is a problem reading from the java.io.InputStream.
*/
public static byte[] normalize(Object object) throws IOException {
return normalize(object, CharsetHelper.DEFAULT_CHARSET);
}
/**
* Normalizes the given String, byte[], or java.io.InputStream object to a byte[].
* @param object The object to be normalized to a string.
* @param charsetName The character set to use.
* @return A byte[] representation of the given object.
* @throws IOException If there is a problem reading from the java.io.InputStream.
*/
public static byte[] normalize(Object object, String charsetName) throws IOException {
return normalize(object, CharsetHelper.normalize(charsetName));
}
/**
* Normalizes the given String, byte[], or java.io.InputStream object to a byte[].
* @param object The object to be normalized to a string.
* @param charset The character set to use.
* @return A byte[] representation of the given object.
* @throws IOException If there is a problem reading from the java.io.InputStream.
*/
public static byte[] normalize(Object object, Charset charset) throws IOException {
if (object == null) return null;
charset = CharsetHelper.normalize(charset);
byte[] output;
if (object instanceof byte[]) {
output = (byte[])object;
} else if (object instanceof String) {
output = normalize((String)object, charset);
} else if (object instanceof InputStream) {
output = normalize((InputStream)object);
} else {
throw new IllegalArgumentException("object must be a String, byte[], or java.io.InputStream");
}
return output;
}
/**
* Encodes binary data as a base64-encoded string.
*
* @param input Binary data to be base64-encoded.
* @return The given data as a base64-encoded string.
*/
public static String base64Encode(byte[] input) {
return input == null ? null : javax.xml.bind.DatatypeConverter.printBase64Binary(input);
}
/**
* Decodes a base64-encoded string to binary data.
*
* @param input A base64-encoded string.
* @return The base64-encoded string decoded to binary data.
*/
public static byte[] base64Decode(String input) {
return input == null ? null : javax.xml.bind.DatatypeConverter.parseBase64Binary(input);
}
}
|
package prm4j.api;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.realtime.DefaultParametricMonitor;
import prm4j.indexing.realtime.UnaryParametricMonitor;
import prm4j.indexing.staticdata.StaticDataConverter;
import prm4j.spec.FiniteParametricProperty;
import prm4j.spec.FiniteSpec;
public class ParametricMonitorFactory {
public static ParametricMonitor createParametricMonitor(FiniteSpec finiteSpec) {
StaticDataConverter converter = new StaticDataConverter(new FiniteParametricProperty(finiteSpec));
BaseMonitor.reset();
// TODO Unary-Optimization deactivated for the moment
// int fullParameterCount = finiteSpec.getFullParameterSet().size();
// if (fullParameterCount == 1) {
// return new UnaryParametricMonitor(finiteSpec);
return new DefaultParametricMonitor(converter.getMetaTree(), converter.getEventContext(), finiteSpec);
}
}
|
package prospector.traverse;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import prospector.traverse.init.TraverseBlocks;
import prospector.traverse.world.TraverseWorld;
public class TraverseCommon {
static void registerShaped(ItemStack output, Object... inputs) {
GameRegistry.addRecipe(new ShapedOreRecipe(output, inputs));
}
static void registerShapeless(ItemStack output, Object... inputs) {
GameRegistry.addRecipe(new ShapelessOreRecipe(output, inputs));
}
public void preInit(FMLPreInitializationEvent event) {
TraverseBlocks.initialize();
}
public void init(FMLInitializationEvent event) {
TraverseWorld.init();
for (String name : TraverseBlocks.oreDictNames.keySet()) {
OreDictionary.registerOre(name, TraverseBlocks.oreDictNames.get(name));
}
registerShapeless(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks")), 4), new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_log"))));
registerShaped(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_slab")), 6), "ppp", 'p', new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks"))));
registerShaped(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_stairs")), 4), "p ", "pp ", "ppp", 'p', new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks"))));
registerShaped(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_door")), 3), "pp", "pp", "pp", 'p', new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks"))));
registerShaped(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_fence")), 3), "psp", "psp", 's', "stickWood", 'p', new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks"))));
registerShaped(new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_fence_gate"))), "sps", "sps", 's', "stickWood", 'p', new ItemStack(Item.getItemFromBlock(TraverseBlocks.blocks.get("fir_planks"))));
}
public void postInit(FMLPostInitializationEvent event) {
}
}
|
package redis.clients.jedis;
import java.net.URI;
import redis.clients.util.ShardInfo;
import redis.clients.util.Sharded;
/**
* "Redis"( ShardInfo<Jedis>)
*
* @author huagang.li 2014122 7:32:23
*/
public class JedisShardInfo extends ShardInfo<Jedis> {
private String host;
private int port;
private String name;
private String password;
private int timeout;
/**
* "Redis"
*
* @param host
*/
public JedisShardInfo(String host) {
super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) { // Redis
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
} else {
this.host = host;
this.port = Protocol.DEFAULT_PORT;
}
}
public JedisShardInfo(String host, String name) {
this(host, Protocol.DEFAULT_PORT, name);
}
public JedisShardInfo(String host, int port) {
this(host, port, 2000);
}
public JedisShardInfo(String host, int port, String name) {
this(host, port, 2000, name);
}
public JedisShardInfo(String host, int port, int timeout) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
}
public JedisShardInfo(String host, int port, int timeout, String name) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name;
}
public JedisShardInfo(String host, int port, int timeout, int weight) {
super(weight);
this.host = host;
this.port = port;
this.timeout = timeout;
}
public JedisShardInfo(URI uri) {
super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
}
/**
* <pre>
*
* IP::
* </pre>
*/
@Override
public String toString() {
return host + ":" + port + "*" + this.getWeight();
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getPassword() {
return password;
}
public void setPassword(String auth) {
this.password = auth;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getName() {
return name;
}
@Override
public Jedis createResource() {
return new Jedis(this);
}
}
|
package seedu.jimi.logic.parser;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_DATE;
import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.String;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
import seedu.jimi.commons.core.Config;
import seedu.jimi.commons.exceptions.DateNotParsableException;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.commons.util.StringUtil;
import seedu.jimi.logic.commands.AddCommand;
import seedu.jimi.logic.commands.ClearCommand;
import seedu.jimi.logic.commands.Command;
import seedu.jimi.logic.commands.CompleteCommand;
import seedu.jimi.logic.commands.DeleteCommand;
import seedu.jimi.logic.commands.EditCommand;
import seedu.jimi.logic.commands.ExitCommand;
import seedu.jimi.logic.commands.FindCommand;
import seedu.jimi.logic.commands.HelpCommand;
import seedu.jimi.logic.commands.IncorrectCommand;
import seedu.jimi.logic.commands.ListCommand;
import seedu.jimi.logic.commands.SaveAsCommand;
import seedu.jimi.logic.commands.SelectCommand;
import seedu.jimi.logic.commands.ShowCommand;
/**
* Parses user input.
*/
public class JimiParser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("[te](?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TAGGABLE_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<ArgsDetails>[^/]+)(?<tagArguments>(?: t/[^/]+)?)"); // zero or one tag only
private static final Pattern PRIORITY_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<otherDetails>[^/]+)(?<priorityArguments>(?: p/[^/]+)?)"); // zero or one tag only
private static final Pattern EDIT_DATA_ARGS_FORMAT = // accepts index at beginning, follows task/event patterns after
Pattern.compile("(?<targetIndex>[^\\s]+) (?<editDetails>.+)");
// acccepts in the format of a deadline task or event
private static final Pattern EDIT_DETAILS_FORMAT = Pattern.compile(
"(\"(?<taskDetails>.+)\"\\s?)?(((due (?<deadline>.+))?)|((on (?<startDateTime>((?!to ).)*))?(to (?<endDateTime>.+))?))");
private static final Pattern ADD_TASK_DATA_ARGS_FORMAT =
Pattern.compile("(\"(?<taskDetails>.+)\")( due (?<dateTime>.+))?");
private static final Pattern ADD_EVENT_DATA_ARGS_FORMAT =
Pattern.compile("(\"(?<taskDetails>.+)\") on (?<startDateTime>((?! to ).)*)( to (?<endDateTime>.+))?");
private static final Pattern SHOW_COMMAND_ARGS_FORMAT = Pattern.compile("(?<sectionToShow>.+)");
private static final Pattern SAVE_DIRECTORY_ARGS_FORMAT = Pattern.compile("(?<filePath>.+).xml");
private static final Pattern SAVE_RESET_DIRECTORY_ARGS_FORMAT = Pattern.compile(SaveAsCommand.COMMAND_WORD_RESET);
private static final List<Command> COMMAND_STUB_LIST =
Arrays.asList(
new AddCommand(),
new EditCommand(),
new CompleteCommand(),
new SelectCommand(),
new DeleteCommand(),
new ClearCommand(),
new FindCommand(),
new ListCommand(),
new ShowCommand(),
new ExitCommand(),
new HelpCommand(),
new SaveAsCommand()
);
private static final String XML_FILE_EXTENSION = ".xml";
public JimiParser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments").trim();
return prepareCommand(commandWord, arguments);
}
/**
* Identifies which command to prepare according to raw command word.
*
* @param commandWord command word from raw input
* @param arguments arguments from raw input
* @return correct Command corresponding to the command word if valid, else returns incorrect command.
*/
private Command prepareCommand(String commandWord, String arguments) {
for (Command command : COMMAND_STUB_LIST) {
// if validation checks implemented by the respective commands are passed
if (command.isValidCommandWord(commandWord)) {
// identify which command this is
if (command instanceof AddCommand) {
return prepareAdd(arguments);
} else if (command instanceof EditCommand) {
return prepareEdit(arguments);
} else if (command instanceof CompleteCommand) {
return prepareComplete(arguments);
} else if (command instanceof SelectCommand) {
return prepareSelect(arguments);
} else if (command instanceof DeleteCommand) {
return prepareDelete(arguments);
} else if (command instanceof FindCommand) {
return prepareFind(arguments);
} else if (command instanceof ShowCommand) {
return prepareShow(arguments);
} else if (command instanceof SaveAsCommand) {
return prepareSaveAs(arguments);
} else { // commands that do not require arguments e.g. exit
return command;
}
}
}
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args) {
final Matcher otherDetailsAndPriorityMatcher = PRIORITY_DATA_ARGS_FORMAT.matcher(args.trim());
final Matcher detailsAndTagsMatcher = TAGGABLE_DATA_ARGS_FORMAT.matcher(otherDetailsAndPriorityMatcher.group("otherDetails").trim());
// Validate entire args string format
if (!detailsAndTagsMatcher.matches() || !otherDetailsAndPriorityMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
final Matcher taskDetailsMatcher =
ADD_TASK_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim());
final Matcher eventDetailsMatcher =
ADD_EVENT_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim());
if (taskDetailsMatcher.matches()) { // if user trying to add task
return generateAddCommandForTask(detailsAndTagsMatcher, taskDetailsMatcher, otherDetailsAndPriorityMatcher);
} else if (eventDetailsMatcher.matches()) { // if user trying to add event
return generateAddCommandForEvent(detailsAndTagsMatcher, eventDetailsMatcher, otherDetailsAndPriorityMatcher);
}
/* default return IncorrectCommand */
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
/**
* Creates an AddCommand in the context of adding an event.
*
* @return an AddCommand if raw args is valid, else IncorrectCommand
*/
private Command generateAddCommandForEvent(final Matcher detailsAndTagsMatcher, final Matcher eventDetailsMatcher, final Matcher otherDetailsAndPriorityMatcher) {
try {
List<Date> startDates = parseStringToDate(eventDetailsMatcher.group("startDateTime"));
List<Date> endDates = parseStringToDate(eventDetailsMatcher.group("endDateTime"));
return new AddCommand(
eventDetailsMatcher.group("taskDetails"),
startDates,
endDates,
getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")),
getPriorityFromArgs(otherDetailsAndPriorityMatcher.group("priorityArguments"))
);
} catch (DateNotParsableException e) {
return new IncorrectCommand(e.getMessage());
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Creates an AddCommand in the context of adding an task.
*
* @return an AddCommand if raw args is valid, else IncorrectCommand
*/
private Command generateAddCommandForTask(final Matcher detailsAndTagsMatcher, final Matcher taskDetailsMatcher, final Matcher otherDetailsAndPriorityMatcher) {
try {
List<Date> dates = parseStringToDate(taskDetailsMatcher.group("dateTime"));
return new AddCommand(
taskDetailsMatcher.group("taskDetails"),
dates,
getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")),
getPriorityFromArgs(otherDetailsAndPriorityMatcher.group("priorityArguments"))
);
} catch (DateNotParsableException e) {
return new IncorrectCommand(e.getMessage());
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
private static List<Date> parseStringToDate(final String str) throws DateNotParsableException {
if (str == null) {
return new ArrayList<Date>();
}
final Parser dateParser = new Parser();
final List<DateGroup> groups = dateParser.parse(str);
if (!groups.isEmpty()) {
return groups.get(0).getDates();
} else {
throw new DateNotParsableException(MESSAGE_INVALID_DATE);
}
}
/**
* Parses arguments in context of the edit task command.
*
* @param args Full user command input args
* @return the prepared edit command
*/
private Command prepareEdit(String args) {
final Matcher otherDetailsAndPriorityMatcher = PRIORITY_DATA_ARGS_FORMAT.matcher(args.trim());
final Matcher detailsAndTagsMatcher = TAGGABLE_DATA_ARGS_FORMAT.matcher(otherDetailsAndPriorityMatcher.group("ArgsDetails").trim());
// Validate full raw args string format
if (!detailsAndTagsMatcher.matches() || !otherDetailsAndPriorityMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
// Validate args in terms of <idx><details>
final Matcher editArgsMatcher =
EDIT_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim());
if (!editArgsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
// User wishes to remove dates
if (editArgsMatcher.group("editDetails").trim().equals(EditCommand.COMMAND_REMOVE_DATES)) {
return new EditCommand(editArgsMatcher.group("targetIndex"));
}
// Validate details in terms of <name><due X> or <name><on X><to X>
final Matcher editDetailsMatcher =
EDIT_DETAILS_FORMAT.matcher(editArgsMatcher.group("editDetails").trim());
if (!editDetailsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
try {
return generateEditCommand(detailsAndTagsMatcher, editArgsMatcher, editDetailsMatcher, otherDetailsAndPriorityMatcher);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/** Generates an edit command */
private Command generateEditCommand(Matcher detailsAndTagsMatcher, Matcher editArgsMatcher,
Matcher editDetailsMatcher, Matcher otherDetailsAndPriorityMatcher) throws IllegalValueException {
List<Date> deadline = parseStringToDate(editDetailsMatcher.group("deadline"));
List<Date> eventStart = parseStringToDate(editDetailsMatcher.group("startDateTime"));
List<Date> eventEnd = parseStringToDate(editDetailsMatcher.group("endDateTime"));
/* validating integer index */
Optional<Integer> index = parseIndex(editArgsMatcher.group("targetIndex"));
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
return new EditCommand(
editDetailsMatcher.group("taskDetails"),
getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")),
deadline,
eventStart,
eventEnd,
editArgsMatcher.group("targetIndex"),
otherDetailsAndPriorityMatcher.group("priorityArguments")
);
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static String getPriorityFromArgs(String priorityArguments) throws IllegalValueException {
// no tags
if (priorityArguments.isEmpty()) {
return "MED";
}
// replace first delimiter prefix, then split
final String priorityStrings = priorityArguments.replaceFirst(" p/", "");
return priorityStrings;
}
/**
* Parses arguments in the context of the complete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareComplete(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE));
}
return new CompleteCommand(index.get());
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(args.trim());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Parses arguments to filter section of task panel to be displayed to user.
* @param args full command args string
* @return the prepared command
*/
private Command prepareShow(String args) {
final Matcher matcher = SHOW_COMMAND_ARGS_FORMAT.matcher(args.trim());
boolean keywordFound = false;
//goes through list of keywords to check if user input is valid
for (String validKey : ShowCommand.VALID_KEYWORDS) {
if (validKey.contains(args)) {
keywordFound = true;
break;
}
}
if (!keywordFound || !matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
ShowCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String sectionToShow = matcher.group("sectionToShow");
return new ShowCommand(sectionToShow);
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
/**
* Parses arguments in the context of the save as command.
*
* @param full command args string
* @return the prepared command
*/
private Command prepareSaveAs(String args) {
final Matcher resetMatcher = SAVE_RESET_DIRECTORY_ARGS_FORMAT.matcher(args.trim());
if (resetMatcher.matches()) {
return new SaveAsCommand(Config.DEFAULT_XML_FILE_PATH);
}
final Matcher matcher = SAVE_DIRECTORY_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveAsCommand.MESSAGE_USAGE));
}
return new SaveAsCommand(matcher.group("filePath") + XML_FILE_EXTENSION);
}
}
|
package seedu.task.commons.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Helper functions for handling strings.
*/
public class StringUtil {
/**
* Returns true if the {@code sentence} contains the {@code word}.
* Ignores case, but a full word match is required.
* <br>examples:<pre>
* containsWordIgnoreCase("ABc def", "abc") == true
* containsWordIgnoreCase("ABc def", "DEF") == true
* containsWordIgnoreCase("ABc def", "AB") == false //not a full word match
* </pre>
* @param sentence cannot be null
* @param word cannot be null, cannot be empty, must be a single word
*/
public static boolean containsWordIgnoreCase(String sentence, String word) {
assert word != null : "Word parameter cannot be null";
assert sentence != null : "Sentence parameter cannot be null";
String preppedWord = word.trim();
assert !preppedWord.isEmpty() : "Word parameter cannot be empty";
assert preppedWord.split("\\s+").length == 1 : "Word parameter should be a single word";
String preppedSentence = sentence;
String[] wordsInPreppedSentence = preppedSentence.split("\\s+");
for (String wordInSentence: wordsInPreppedSentence) {
if (wordInSentence.equalsIgnoreCase(preppedWord)) return true;
}
return false;
}
/**
*
* Returns true if the {@code sentence} contains the {@code word}
* Ignores cases, does not have to be full word match
* @param sentence
* @param word
* @return
*/
public static boolean containsSubstringIgnoreCase(String sentence, String word) {
assert word != null : "Word parameter cannot be null";
assert sentence != null : "Sentence parameter cannot be null";
String preppedWord = word.trim();
assert !preppedWord.isEmpty() : "Word parameter cannot be empty";
assert preppedWord.split("\\s+").length == 1 : "Word parameter should be a single word";
return sentence.toLowerCase().contains(word.toLowerCase());
}
/**
* Returns true if the {@code sentence} contains the {@code keywords}.
* Ignores case, but a full word match is required for each keyword.
* @param sentence cannot be null
* @param keywords cannot be null, cannot be empty, must a set of words
*/
public static boolean containsExactWordsIgnoreCase(String sentence, Set<String> keywords) {
assert keywords != null : "Word parameter cannot be null";
assert sentence != null : "Sentence parameter cannot be null";
String lowerCaseSentence = sentence.toLowerCase();
Set<String> lowerCaseKeywords = new HashSet<>(keywords.size());
for (String s : keywords) {
String a = s.toLowerCase();
lowerCaseKeywords.add(a);
}
String[] tokenizedTaskName = lowerCaseSentence.split(" ");
Set<String> tokenizedTaskNameInSet = new HashSet<>(Arrays.asList(tokenizedTaskName));
return tokenizedTaskNameInSet.containsAll(keywords);
}
/**
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t) {
assert t != null;
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
}
/**
* Returns true if s represents an unsigned integer e.g. 1, 2, 3, ... <br>
* Will return false if the string is:
* null, empty string, "-1", "0", "+1", and " 2 " (untrimmed) "3 0" (contains whitespace).
* @param s Should be trimmed.
*/
public static boolean isUnsignedInteger(String s) {
return s != null && s.matches("^0*[1-9]\\d*$");
}
}
|
//@@author A0141052Y
package seedu.task.logic.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
import java.util.StringJoiner;
import seedu.task.commons.util.StringUtil;
import seedu.task.logic.commands.Command;
public abstract class BaseParser {
protected final HashMap<String, ArrayList<String>> argumentsTable = new HashMap<>();
/**
* Extracts out arguments from the user's input into a HashMap.
* The value mapped to the empty string ("") is the non-keyword argument.
*
* @param args full (or partial) user input arguments
*/
protected void extractArguments(String args) {
argumentsTable.clear();
String[] segments = args.trim().split(" ");
String currentKey = "";
StringJoiner joiner = new StringJoiner(" ");
for (String segment : segments) {
joiner.add(segment);
}
addToArgumentsTable(currentKey, joiner.toString());
}
/**
* Assigns a value to a keyword argument. Does not replace any existing
* values associated with the keyword.
* @param keyword
* @param value
*/
protected void addToArgumentsTable(String keyword, String value) {
ArrayList<String> arrayItems;
if (argumentsTable.containsKey(keyword)) {
arrayItems = argumentsTable.get(keyword);
} else {
arrayItems = new ArrayList<String>();
}
arrayItems.add(value);
argumentsTable.put(keyword, arrayItems);
}
/***
* Checks if the required keyword arguments were supplied by the user
* @param requiredArgs list of keyword arguments
* @param optionalArgs list of arguments that may appear
* @param isStrictSet does not allow for other keyword arguments
* @return true if required arguments were supplied, else false
*/
protected boolean checkForRequiredArguments(String[] requiredArgs, String[] optionalArgs, boolean isStrictSet) {
for (String arg : requiredArgs) {
if (!argumentsTable.containsKey(arg)) {
return false;
} else {
if (argumentsTable.get(arg).get(0).isEmpty()) {
return false;
}
}
}
int numOptional = 0;
for (String arg : optionalArgs) {
if (argumentsTable.containsKey(arg)) {
numOptional++;
}
}
if (isStrictSet) {
return argumentsTable.size() == numOptional + requiredArgs.length;
} else {
return argumentsTable.size() >= numOptional + requiredArgs.length;
}
}
/**
* Retrieves the value for the keyword argument
* @param keyword the keyword of the argument
* @return the current value of the keyword argument
*/
protected String getSingleKeywordArgValue(String keyword) {
if (argumentsTable.containsKey(keyword)) {
return argumentsTable.get(keyword).get(0);
} else {
return null;
}
}
/**
* Returns a positive integer, if the user supplied unnamed keyword argument is a positive integer.
* Returns an {@code Optional.empty()} otherwise.
*/
protected Optional<Integer> parseIndex() {
String index = getSingleKeywordArgValue("");
return parseIndex(index);
}
protected Optional<Integer> parseIndex(String index) {
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses the user's input and determines the appropriate command
* @param userInput full user input string
* @return the command based on the user input
*/
public abstract Command parse(String command, String arguments);
}
|
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalAnalysis;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.psi.elements.Method;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection;
import org.jetbrains.annotations.NotNull;
public class DeprecatedConstructorStyleInspector extends BasePhpInspection {
private static final String strProblemDescription = "%s% has a deprecated constructor";
@NotNull
public String getShortName() {
return "DeprecatedConstructorStyleInspection";
}
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
public void visitPhpMethod(Method method) {
PhpClass objClass = method.getContainingClass();
String strMethodName = method.getName();
if (
null == objClass || objClass.isTrait() || objClass.isInterface() ||
StringUtil.isEmpty(strMethodName) || null == method.getNameIdentifier()) {
return;
}
String strClassName = objClass.getName();
if (strMethodName.equals(strClassName)) {
String strMessage = strProblemDescription.replace("%s%", strClassName);
holder.registerProblem(method.getNameIdentifier(), strMessage, ProblemHighlightType.LIKE_DEPRECATED);
}
}
};
}
}
|
package tars.logic.commands;
import static tars.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.HashSet;
import java.util.Set;
import tars.commons.core.Messages;
import tars.commons.core.UnmodifiableObservableList;
import tars.commons.exceptions.DuplicateTaskException;
import tars.commons.exceptions.IllegalValueException;
import tars.model.tag.Tag;
import tars.model.tag.UniqueTagList;
import tars.model.task.Priority;
import tars.model.task.Status;
import tars.model.task.Task;
import tars.model.task.rsv.RsvTask;
import tars.model.task.rsv.UniqueRsvTaskList.RsvTaskNotFoundException;
/**
* Confirms a specified datetime for a reserved task and add it into the task list
*
* @@author A0124333U
*/
public class ConfirmCommand extends UndoableCommand {
public static final String COMMAND_WORD = "confirm";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Confirms a datetime for a reserved task"
+ " and adds the task into the task list.\n"
+ "Parameters: <RESERVED_TASK_INDEX> <DATETIME_INDEX> -p <PRIORITY> -t <TAG>\n"
+ "Example: " + COMMAND_WORD + " 1 3 -p h -t tag1";
public static final String MESSAGE_CONFIRM_SUCCESS = "Task Confirmation Success! New task added: %1$s";
private final int taskIndex;
private final int dateTimeIndex;
private final String priority;
final Set<Tag> tagSet = new HashSet<>();
public ConfirmCommand(int taskIndex, int dateTimeIndex, String priority, Set<String> tags) throws IllegalValueException {
this.taskIndex = taskIndex;
this.dateTimeIndex = dateTimeIndex;
this.priority = priority;
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
}
@Override
public CommandResult undo() {
// TODO Auto-generated method stub
return null;
}
@Override
public CommandResult redo() {
// TODO Auto-generated method stub
return null;
}
@Override
public CommandResult execute() {
assert model != null;
UnmodifiableObservableList<RsvTask> lastShownList = model.getFilteredRsvTaskList();
if (lastShownList.size() < taskIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_RSV_TASK_DISPLAYED_INDEX);
}
RsvTask rsvTask = lastShownList.get(taskIndex - 1);
if (rsvTask.getDateTimeList().size() < dateTimeIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_DATETIME_DISPLAYED_INDEX);
}
Task toConfirm;
try {
toConfirm = new Task(rsvTask.getName(), rsvTask.getDateTimeList().get((dateTimeIndex - 1)), new Priority(priority), new Status(),
new UniqueTagList(tagSet));
} catch (IllegalValueException ive) {
return new CommandResult(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE));
};
try {
model.addTask(toConfirm);
} catch (DuplicateTaskException e) {
return new CommandResult(Messages.MESSAGE_DUPLICATE_TASK);
}
try {
model.deleteRsvTask(rsvTask);
} catch (RsvTaskNotFoundException rtnfe) {
return new CommandResult(Messages.MESSAGE_RSV_TASK_CANNOT_BE_FOUND);
}
return new CommandResult(String.format(MESSAGE_CONFIRM_SUCCESS, toConfirm));
}
}
|
package org.wyona.yanel.impl.resources.boost;
import java.io.InputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.wyona.yanel.servlet.AccessLog;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.commons.xml.XMLHelper;
import org.apache.log4j.Logger;
import com.wyona.boost.client.BoostService;
import com.wyona.boost.client.ServiceException;
import com.wyona.boost.client.BoostServiceConfig;
import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.search.Searcher;
/**
* Retrieve the user profile of the current user, given his cookie id, from
* the Boost service using the Boost client library.
*/
public class PersonalizedContentResource extends BasicXMLResource {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(PersonalizedContentResource.class);
private static final String NAMESPACE = "http:
private static final String BOOST_SERVICE_URL_PARAM = "boost-service-url";
/**
* Get the XML content of this resource.
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
Document doc = XMLHelper.createDocument(NAMESPACE, "personalized-content");
Element root = doc.getDocumentElement();
String service = getResourceConfigProperty(BOOST_SERVICE_URL_PARAM);
String api_key = getResourceConfigProperty("boost-api-key");
if(service != null && !"".equals(service)) {
log.warn("DEBUG: Boost service URL: " + service);
} else {
log.error("No boost service URL '" + BOOST_SERVICE_URL_PARAM + "' configured!");
}
// INFO: Check whether the user is logged into Yanel?
String username = getEnvironment().getIdentity().getUsername();
if(username != null) {
Element uid = doc.createElement("yanel-user-id");
uid.appendChild(doc.createTextNode(username));
}
String realm = getRealm().getID();
String boost_domain = getRealm().getUserTrackingDomain();
if (getResourceConfigProperty("domain") != null) {
log.warn("Try to get user profile for third party domain: " + getResourceConfigProperty("domain"));
boost_domain = getResourceConfigProperty("domain");
}
Element realmEl = doc.createElementNS(NAMESPACE, "yanel-realm-id");
realmEl.appendChild(doc.createTextNode(realm));
root.appendChild(realmEl);
Element domainEl = doc.createElementNS(NAMESPACE, "boost-domain-id");
domainEl.appendChild(doc.createTextNode(boost_domain));
root.appendChild(domainEl);
// INFO: Get the cookie
HttpServletRequest req = getEnvironment().getRequest();
Cookie cookie = AccessLog.getYanelAnalyticsCookie(req);
if(cookie == null) {
root.appendChild(doc.createElementNS(NAMESPACE, "no-cookie"));
root.appendChild(doc.createElementNS(NAMESPACE, "no-profile"));
return XMLHelper.getInputStream(doc, false, false, null);
}
String cookieVal = cookie.getValue();
if (getResourceConfigProperty("cookie") != null) {
log.warn("Try to get user profile for third party cookie from resource configuration: " + getResourceConfigProperty("cookie"));
cookieVal = getResourceConfigProperty("cookie");
}
if (getEnvironment().getRequest().getParameter("cookie-id") != null) {
log.warn("Try to get user profile for third party cookie from query string: " + getEnvironment().getRequest().getParameter("cookie-id"));
cookieVal = getEnvironment().getRequest().getParameter("cookie-id");
}
Element cookieEl = doc.createElementNS(NAMESPACE, "yanel-cookie-id");
cookieEl.appendChild(doc.createTextNode(cookieVal));
root.appendChild(cookieEl);
// INFO: Get user interests and clickstream
Iterable<String> userInterests;
Iterable<String> clickStream;
try {
userInterests = getUserInterests(service, cookieVal, boost_domain, api_key);
clickStream = getClickstream(service, cookieVal, boost_domain, api_key);
} catch(ServiceException e) {
// No interests or clickstream
log.error(e, e);
Element exceptionEl = doc.createElementNS(NAMESPACE, "exception");
exceptionEl.appendChild(doc.createTextNode(e.getMessage()));
root.appendChild(exceptionEl);
Element errEl = doc.createElementNS(NAMESPACE, "no-profile");
root.appendChild(errEl);
return XMLHelper.getInputStream(doc, false, false, null);
}
// INFO: Add all interests to user profile
Element interestsEl = doc.createElementNS(NAMESPACE, "interests");
for(String interest : userInterests) {
Element interestEl = doc.createElementNS(NAMESPACE, "interest");
interestEl.appendChild(doc.createTextNode(interest));
interestsEl.appendChild(interestEl);
}
root.appendChild(interestsEl);
// INFO: Search for related content in data repository of this realm
Element resultsEl = doc.createElementNS(NAMESPACE, "search-results");
Searcher search = getRealm().getRepository().getSearcher();
for(String interest : userInterests) {
Node[] nodes;
try {
nodes = search.search(interest);
} catch(Exception e) {
break;
}
//for(int i = 0; i < nodes.length; i++) {
for(int i = nodes.length - 1; i >= 0; i
Node node = nodes[i];
Element res_node = doc.createElementNS(NAMESPACE, "result");
res_node.setAttribute("interest", interest);
resultsEl.appendChild(res_node);
Element res_path = doc.createElementNS(NAMESPACE, "path");
res_path.appendChild(doc.createTextNode(node.getPath()));
res_node.appendChild(res_path);
Element res_name = doc.createElementNS(NAMESPACE, "name");
res_name.appendChild(doc.createTextNode(node.getName()));
res_node.appendChild(res_name);
Element res_time = doc.createElementNS(NAMESPACE, "last-modified");
res_time.setAttribute("epoch", Long.toString(node.getLastModified()));
res_time.appendChild(doc.createTextNode(new java.util.Date(node.getLastModified()).toString()));
res_node.appendChild(res_time);
}
}
root.appendChild(resultsEl);
// INFO: Add clickstream to user profile
Element clickstreamEl = doc.createElementNS(NAMESPACE, "clickstream");
for(String url : clickStream) {
Element urlEl = doc.createElementNS(NAMESPACE, "url");
urlEl.appendChild(doc.createTextNode(url));
if (clickstreamEl.hasChildNodes()) {
clickstreamEl.insertBefore(urlEl, clickstreamEl.getFirstChild());
} else {
clickstreamEl.appendChild(urlEl);
}
}
root.appendChild(clickstreamEl);
return XMLHelper.getInputStream(doc, false, false, null);
}
private Iterable<String> getClickstream(String boostServiceUrl, String cookie, String realm, String apiKey) throws Exception {
BoostServiceConfig bsc = new BoostServiceConfig(boostServiceUrl, realm, apiKey);
BoostService boost = new BoostService(bsc);
return boost.getClickStream(cookie);
}
/**
* Get the user profile given a cookie.
* @param boostServiceUrl Boost service URL
* @param cookie Unique cookie id
* @param realm Domain name
* @param apiKey Key to access Boost API
* @return list of interests
*/
private Iterable<String> getUserInterests(String boostServiceUrl, String cookie, String realm, String apiKey) throws Exception {
BoostServiceConfig bsc = new BoostServiceConfig(boostServiceUrl, realm, apiKey);
BoostService boost = new BoostService(bsc);
return boost.getUserProfile(cookie);
}
/**
* Do we exist? Returns 404 if we answer no.
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
}
|
package tigase.server.ssender;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.conf.Configurable;
import tigase.server.AbstractMessageReceiver;
import tigase.server.Packet;
import tigase.server.ServerComponent;
import tigase.xml.DomBuilderHandler;
import tigase.xml.Element;
import tigase.xml.SimpleParser;
import tigase.xml.SingletonFactory;
/**
* <code>StanzaSender</code> class implements simple cyclic tasks management
* mechanism. You can specify as many tasks in configuration as you need.
* <p>
* These tasks are designed to pull XMPP stanzas from specific data source like
* SQL database, directory in the filesystem and so on. Each of these tasks must
* extend <code>tigase.server.ssende.SenderTask</code> abstract class.
* Look in specific tasks implementation for more detailed description how
* to use them.
* <p>
* Created: Fri Apr 20 11:11:25 2007
* </p>
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class StanzaSender extends AbstractMessageReceiver
implements Configurable, StanzaHandler {
public static final String INTERVAL_PROP_KEY = "default-interval";
public static final long INTERVAL_PROP_VAL = 10;
public static final String STANZA_LISTENERS_PROP_KEY = "stanza-listeners";
public static final String TASK_CLASS_PROP_KEY = "class-name";
public static final String TASK_INIT_PROP_KEY = "init-string";
public static final String TASK_INTERVAL_PROP_KEY = "interval";
public static final String JDBC_TASK_NAME = "jdbc";
public static final String JDBC_TASK_CLASS = "tigase.server.ssender.JDBCTask";
public static final String JDBC_TASK_INIT =
"jdbc:mysql://localhost/tigase?user=root&password=mypass&table=xmpp_stanza";
public static final long JDBC_INTERVAL = 10;
public static final String FILE_TASK_NAME = "file";
public static final String FILE_TASK_CLASS = "tigase.server.ssender.FileTask";
public static final String FILE_TASK_INIT =
File.separator + "var" + File.separator + "spool" + File.separator +
"jabber" + File.separator + "*.stanza";
public static final long FILE_INTERVAL = 10;
public static final String[] STANZA_LISTENERS_PROP_VAL =
{JDBC_TASK_NAME, FILE_TASK_NAME};
public static final String TASK_ACTIVE_PROP_KEY = "active";
public static final boolean TASK_ACTIVE_PROP_VAL = false;
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger("tigase.server.ssender.StanzaSender");
private static final SimpleParser parser =
SingletonFactory.getParserInstance();
private long interval = INTERVAL_PROP_VAL;
private Map<String, SenderTask> tasks_list = new HashMap<String, SenderTask>();
private Timer tasks = new Timer("StanzaSender", true);
// Implementation of tigase.server.ServerComponent
/**
* Describe <code>release</code> method here.
*
*/
public void release() {
super.release();
}
private String myDomain() {
return getName() + "." + getDefHostName();
}
/**
* Describe <code>processPacket</code> method here.
*
* @param packet a <code>Packet</code> value
*/
public void processPacket(final Packet packet) {
// do nothing, this component is to send packets not to receive
// (for now)
}
// Implementation of tigase.conf.Configurable
/**
* Describe <code>setProperties</code> method here.
*
* @param props a <code>Map</code> value
*/
public void setProperties(final Map<String, Object> props) {
super.setProperties(props);
interval = (Long)props.get(INTERVAL_PROP_KEY);
String[] config_tasks = (String[])props.get(STANZA_LISTENERS_PROP_KEY);
for (String task_name: config_tasks) {
// Reconfiguration code. Turn-off old task with that name.
SenderTask old_task = tasks_list.get(task_name);
if (old_task != null) {
old_task.cancel();
}
if ((Boolean)props.get(task_name + "/" + TASK_ACTIVE_PROP_KEY)) {
String task_class =
(String)props.get(task_name + "/" + TASK_CLASS_PROP_KEY);
String task_init =
(String)props.get(task_name + "/" + TASK_INIT_PROP_KEY);
long task_interval =
(Long)props.get(task_name + "/" + TASK_INTERVAL_PROP_KEY);
try {
SenderTask task = (SenderTask)Class.forName(task_class).newInstance();
task.setName(task_name + "@" + myDomain());
task.init(this, task_init);
// Install new task
tasks_list.put(task_name, task);
tasks.scheduleAtFixedRate(task, task_interval*SECOND,
task_interval*SECOND);
} catch (Exception e) {
log.log(Level.SEVERE, "Can not initialize stanza listener: ", e);
}
}
}
}
/**
* Describe <code>getDefaults</code> method here.
*
* @param params a <code>Map</code> value
* @return a <code>Map</code> value
*/
public Map<String, Object> getDefaults(final Map<String, Object> params) {
Map<String, Object> defs = super.getDefaults(params);
defs.put(INTERVAL_PROP_KEY, INTERVAL_PROP_VAL);
defs.put(STANZA_LISTENERS_PROP_KEY, STANZA_LISTENERS_PROP_VAL);
if ((Boolean)params.get(GEN_TEST)) {
defs.put(FILE_TASK_NAME + "/" + TASK_ACTIVE_PROP_KEY, true);
} else {
defs.put(FILE_TASK_NAME + "/" + TASK_ACTIVE_PROP_KEY, TASK_ACTIVE_PROP_VAL);
}
defs.put(FILE_TASK_NAME + "/" + TASK_CLASS_PROP_KEY, FILE_TASK_CLASS);
defs.put(FILE_TASK_NAME + "/" + TASK_INIT_PROP_KEY, FILE_TASK_INIT);
defs.put(FILE_TASK_NAME + "/" + TASK_INTERVAL_PROP_KEY, FILE_INTERVAL);
if ((Boolean)params.get(GEN_TEST)) {
defs.put(JDBC_TASK_NAME + "/" + TASK_ACTIVE_PROP_KEY, true);
} else {
defs.put(JDBC_TASK_NAME + "/" + TASK_ACTIVE_PROP_KEY, TASK_ACTIVE_PROP_VAL);
}
defs.put(JDBC_TASK_NAME + "/" + TASK_CLASS_PROP_KEY, JDBC_TASK_CLASS);
defs.put(JDBC_TASK_NAME + "/" + TASK_INIT_PROP_KEY, JDBC_TASK_INIT);
defs.put(JDBC_TASK_NAME + "/" + TASK_INTERVAL_PROP_KEY, JDBC_INTERVAL);
return defs;
}
public void handleStanza(String stanza) {
parseXMLData(stanza);
}
public void handleStanzas(Queue<Packet> results) {
addOutPackets(results);
}
private void parseXMLData(String data) {
DomBuilderHandler domHandler = new DomBuilderHandler();
parser.parse(domHandler, data.toCharArray(), 0, data.length());
Queue<Element> elems = domHandler.getParsedElements();
while (elems != null && elems.size() > 0) {
Packet result = new Packet(elems.poll());
addOutPacket(result);
}
}
}
|
package ca.corefacility.bioinformatics.irida.config.workflow;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowException;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisType;
import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow;
import ca.corefacility.bioinformatics.irida.model.workflow.description.IridaWorkflowToolRepository;
import ca.corefacility.bioinformatics.irida.pipeline.upload.galaxy.integration.LocalGalaxy;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowLoaderService;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService;
import com.github.jmchilton.blend4j.galaxy.GalaxyInstance;
import com.github.jmchilton.blend4j.galaxy.ToolShedRepositoriesClient;
import com.github.jmchilton.blend4j.galaxy.beans.InstalledRepository;
import com.github.jmchilton.blend4j.galaxy.beans.InstalledRepository.InstallationStatus;
import com.github.jmchilton.blend4j.galaxy.beans.RepositoryInstall;
/**
* Class used configure workflows in Galaxy for integration testing.
*
* @author Aaron Petkau <aaron.petkau@phac-aspc.gc.ca>
*
*/
@Configuration
@Profile("test")
public class IridaWorkflowsGalaxyIntegrationTestConfig {
private static final Logger logger = LoggerFactory.getLogger(IridaWorkflowsGalaxyIntegrationTestConfig.class);
@Autowired
private LocalGalaxy localGalaxy;
@Autowired
private IridaWorkflowLoaderService iridaWorkflowLoaderService;
@Autowired
private IridaWorkflowsService iridaWorkflowsService;
private UUID snvPhylWorkflowId = UUID.fromString("ccca532d-b0be-4f2c-bd6d-9886aa722571");
/**
* Registers a production SNVPhyl workflow for testing.
*
* @return A production {@link IridaWorkflow} for testing.
* @throws IOException
* @throws URISyntaxException
* @throws IridaWorkflowException
*/
@Lazy
@Bean
public IridaWorkflow snvPhylWorkflow() throws IOException, URISyntaxException, IridaWorkflowException {
Path snvPhylProductionPath = Paths.get(AnalysisType.class.getResource("workflows/SNVPhyl").toURI());
Set<IridaWorkflow> snvPhylWorkflows = iridaWorkflowLoaderService
.loadAllWorkflowImplementations(snvPhylProductionPath);
iridaWorkflowsService.registerWorkflows(snvPhylWorkflows);
IridaWorkflow snvPhylWorkflow = iridaWorkflowsService.getIridaWorkflow(snvPhylWorkflowId);
importAllTools(localGalaxy.getGalaxyInstanceAdmin(), snvPhylWorkflow);
return snvPhylWorkflow;
}
/**
* Imports all tools to Galaxy for the passed workflow.
*
* @param galaxyInstance
* The instance of Galaxy to import tools into.
* @param iridaWorkflow
* The workflow to import all tools for.
*/
private void importAllTools(GalaxyInstance galaxyInstance, IridaWorkflow iridaWorkflow) {
for (IridaWorkflowToolRepository workflowTool : iridaWorkflow.getWorkflowDescription().getToolRepositories()) {
ToolShedRepositoriesClient toolRepositoriesClient = galaxyInstance.getRepositoriesClient();
RepositoryInstall toolInstall = new RepositoryInstall();
toolInstall.setName(workflowTool.getName());
toolInstall.setOwner(workflowTool.getOwner());
toolInstall.setToolShedUrl(workflowTool.getUrl().toString());
toolInstall.setChangsetRevision(workflowTool.getRevision());
toolInstall.setInstallRepositoryDependencies(true);
toolInstall.setInstallToolDependencies(true);
logger.debug("Installing tool " + workflowTool);
List<InstalledRepository> installedRepositories = toolRepositoriesClient.installRepository(toolInstall);
for (InstalledRepository installedRepository : installedRepositories) {
InstallationStatus status = installedRepository.getInstallationStatus();
logger.debug("Installation status=" + status + " for tool " + workflowTool);
if (status.equals(InstallationStatus.ERROR)) {
// don't even try to proceed with tests if you can't install the required tools.
throw new IridaWorkflowException("Failed to install tool [" + workflowTool + "]");
}
}
}
}
}
|
package wasdev.sample.servlet;
//package com.mcademo;
import okhttp3.*;
import org.json.JSONObject;
//import net.iharder.Base64;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.logging.Logger;
public class OAuthServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Define properties required for OAuth flows
private static final Logger logger = Logger.getLogger(OAuthServlet.class.getName());
private static final OkHttpClient client = new OkHttpClient();
private static final String clientId = "4b07cfe1-3875-419c-a0a2-8fb0a7b43dff";
private static final String clientSecret = "MDlkYjZkYjAtOGVkOS00MjcxLWE5ZTMtMWNlODVhMDQ0MDUy";
private static final String callbackUri = "http://mca-java.mybluemix.net/oauth/callback";
private static final String authzEndpoint = "https://mobileclientaccess.ng.bluemix.net/oauth/v2/authorization";
private static final String tokenEndpoint = "https://mobileclientaccess.ng.bluemix.net/oauth/v2/token";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Incoming request :: " + request.getRequestURL() + "/" + request.getQueryString());
logger.info("Redirecting to MCA for authorization");
if (request.getRequestURI().contains("/login")){
onLogin(request, response);
} else if (request.getRequestURI().contains("/callback")){
onCallback(request, response);
} else if (request.getRequestURI().contains("/logout")){
onLogout(request, response);
} else {
response.sendError(404, "Not Found");
}
}
private void onLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("onLogin");
String authzUrl = authzEndpoint + "?response_type=code";
authzUrl += "&client_id=" + clientId;
authzUrl += "&redirect_uri=" + callbackUri;
response.sendRedirect(authzUrl);
}
private void onCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("onCallback");
String grantCode = request.getQueryString().split("=")[1];
JSONObject body = new JSONObject();
try {
body.put("grant_type", "authorization_code");
body.put("client_id", clientId);
body.put("redirect_uri", callbackUri);
body.put("code", grantCode);
} catch (Throwable t){}
String credentials = Credentials.basic(clientId, clientSecret);
Request req = new Request.Builder()
.url(tokenEndpoint)
.header("Authorization", credentials)
.post(RequestBody.create(MediaType.parse("application/json"), body.toString()))
.build();
Response res = client.newCall(req).execute();
JSONObject parsedBody = new JSONObject(res.body().string());
String accessToken = parsedBody.getString("access_token");
String idToken = parsedBody.getString("id_token");
byte[] decodedIdTokenPayload = Base64.getUrlDecoder().decode(idToken.split("\\.")[1]);
//byte[] decodedIdTokenPayload = Base64.decode(idToken.split("\\.")[1], Base64.URL_SAFE);
JSONObject decodedIdentityToken = new JSONObject(new String(decodedIdTokenPayload));
JSONObject userIdentity = decodedIdentityToken.getJSONObject("imf.user");
JSONObject authData = new JSONObject();
authData.put("accessToken", accessToken);
authData.put("idToken", idToken);
authData.put("userIdentity", userIdentity);
request.getSession().setAttribute("mca", authData);
response.sendRedirect("/");
}
private void onLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("onLogout");
request.getSession().setAttribute("mca", null);
response.sendRedirect("/");
}
}
|
package org.ow2.choreos.deployment.nodes.cloudprovider;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.jclouds.Constants;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
import org.ow2.choreos.deployment.DeploymentManagerConfiguration;
import org.ow2.choreos.nodes.NodeNotFoundException;
import org.ow2.choreos.nodes.datamodel.Node;
import org.ow2.choreos.nodes.datamodel.NodeSpec;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Module;
public class OpenStackKeystoneCloudProvider implements CloudProvider {
Logger logger = Logger.getLogger(OpenStackKeystoneCloudProvider.class);
public String getProviderName() {
return "OpenStack Keystone Provider";
}
private static String OP_AUTHURL = DeploymentManagerConfiguration.get("OPENSTACK_IP");
private static String OP_TENANT = DeploymentManagerConfiguration.get("OPENSTACK_TENANT");
private static String OP_USER = DeploymentManagerConfiguration.get("OPENSTACK_USER");
private static String OP_PASS = DeploymentManagerConfiguration.get("OPENSTACK_PASSWORD");
private ComputeService getClient(String imageId) {
logger.info("Obtaining Client");
String provider = "openstack-nova";
String identity = OP_TENANT + ":" + OP_USER;
String credential = OP_PASS;
Properties properties = new Properties();
properties.setProperty(Constants.PROPERTY_ENDPOINT, OP_AUTHURL);
// example of injecting a ssh implementation
Iterable<Module> modules = ImmutableSet.<Module> of(new SLF4JLoggingModule());
ContextBuilder builder = ContextBuilder.newBuilder(provider).credentials(identity, credential).modules(modules)
.overrides(properties);
logger.info("Initializing Client With Data: " + builder.getApiMetadata());
ComputeService srv = builder.buildView(ComputeServiceContext.class).getComputeService();
logger.info("Client obtained successfully.");
return srv;
}
@Override
public Node createNode(NodeSpec nodeSpec) {
System.out.println(">OpenStack: Create new Node.");
Node node = new Node();
// TODO: resource impact changes
ComputeService client = getClient("");
Set<? extends NodeMetadata> createdNodes = null;
try {
try {
createdNodes = client.createNodesInGroup("default", 1, getTemplate(client, getImages().get(0).getId()));
} catch (RunNodesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (org.jclouds.rest.AuthorizationException e) {
logger.error("Authorization failed. Provided user doesn't have authorization to create a new node.");
throw e;
}
NodeMetadata cloudNode = Iterables.get(createdNodes, 0);
setNodeProperties(node, cloudNode);
client.getContext().close();
logger.info("Node created successfully.");
return node;
}
@Override
public Node getNode(String nodeId) throws NodeNotFoundException {
ComputeService client = getClient("");
Node node = new Node();
try {
NodeMetadata cloudNode = client.getNodeMetadata(nodeId);
setNodeProperties(node, cloudNode);
} catch (Exception e) {
throw new NodeNotFoundException(nodeId);
}
return node;
}
@Override
public List<Node> getNodes() {
List<Node> nodeList = new ArrayList<Node>();
Node node;
ComputeService client = getClient("");
logger.info("Getting list of nodes");
Set<? extends ComputeMetadata> cloudNodes = client.listNodes();
logger.debug("Got: " + cloudNodes);
for (ComputeMetadata computeMetadata : cloudNodes) {
NodeMetadata cloudNode = client.getNodeMetadata(computeMetadata.getId());
node = new Node();
setNodeProperties(node, cloudNode);
if (node.getState() != 1) {
nodeList.add(node);
}
}
client.getContext().close();
logger.info("Node List obtained successfully.");
return nodeList;
}
public List<Image> getImages() {
logger.info("Getting image info...");
ComputeService client = getClient("");
Set<? extends Image> images = client.listImages();
List<Image> imageList = new ArrayList<Image>();
for (Image image : images) {
imageList.add(image);
}
logger.info("Images: " + imageList.toString());
return imageList;
}
public List<Hardware> getHardwareProfiles() {
logger.info("getting hardware profile info...");
ComputeService client = getClient("");
Set<? extends Hardware> profiles = client.listHardwareProfiles();
List<Hardware> hardwareList = new ArrayList<Hardware>();
for (Hardware profile : profiles) {
hardwareList.add(profile);
}
logger.info(hardwareList.toString());
return hardwareList;
}
@Override
public void destroyNode(String id) {
logger.info("Destroy Node.");
ComputeService client = getClient("");
client.destroyNode(id);
client.getContext().close();
logger.info("Node destroyed successfully.");
}
@Override
public Node createOrUseExistingNode(NodeSpec nodeSpec) {
for (Node n : getNodes()) {
if (n.getImage().equals(nodeSpec.getImage()) && NodeMetadata.Status.RUNNING.ordinal() == n.getState()) {
return n;
}
}
Node i = null;
i = createNode(nodeSpec);
return i;
}
private Template getTemplate(ComputeService client, String imageId) {
if (imageId.isEmpty()) {
imageId = getImages().get(0).getId();
}
String hardwareId = getHardwareProfiles().get(2).getId();
logger.info("Creating Template with image ID: " + imageId + "; hardware ID: " + hardwareId);
TemplateBuilder builder = client.templateBuilder().imageId(imageId);
builder.hardwareId(hardwareId);
logger.info("Building Template...");
Template template = builder.build();
NovaTemplateOptions options = template.getOptions().as(NovaTemplateOptions.class);
options.keyPairName(DeploymentManagerConfiguration.get("OPENSTACK_KEY_PAIR"));
options.securityGroupNames("default");
logger.info(" Template built successfully!");
return template;
}
private void setNodeProperties(Node node, NodeMetadata cloudNode) {
setNodeIp(node, cloudNode);
node.setHostname(cloudNode.getName());
node.setSo(cloudNode.getOperatingSystem().getName());
node.setId(cloudNode.getId());
node.setImage(cloudNode.getImageId());
node.setState(cloudNode.getStatus().ordinal());
node.setUser("ubuntu");
node.setPrivateKeyFile(DeploymentManagerConfiguration.get("OPENSTACK_PRIVATE_SSH_KEY"));
}
private void setNodeIp(Node node, NodeMetadata cloudNode) {
Iterator<String> publicAddresses = cloudNode.getPrivateAddresses().iterator();
if (publicAddresses != null && publicAddresses.hasNext()) {
node.setIp(publicAddresses.next());
}
}
}
|
package org.eclipse.birt.report.designer.internal.ui.util.bidi;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Widget;
/**
* Bidi API used by design GUI.
*
* @author bidi_hcg
*
*/
public class BidiUIUtils
{
public static final char LRE = '\u202a';
public static final char RLE = '\u202b';
public static final char PDF = '\u202c';
private final static String QUERYTEXT = "queryText"; //$NON-NLS-1$
private static int OS_STYLE_INDEX = 0;
private static int WS_EX_LAYOUTRTL = 0;
private static int WS_EX_NOINHERITLAYOUT = 0;
private static Class osWinClass = null;
private static Method GET_WINDOW_LONG = null;
private static Method SET_WINDOW_LONG = null;
private static Method INVALIDATE_RECT = null;
private static Field STYLE_FIELD = null;
private static Field HANDLE = null;
private TextLayout layout;
private boolean isInitialized = false;
public static final BidiUIUtils INSTANCE = new BidiUIUtils( );
private BidiUIUtils( )
{
}
private void init( )
{
if ( isInitialized )
return;
isInitialized = true;
try
{
osWinClass = Class.forName( "org.eclipse.swt.internal.win32.OS" ); //$NON-NLS-1$
if ( osWinClass != null )
{
GET_WINDOW_LONG = osWinClass.getMethod( "GetWindowLong", //$NON-NLS-1$
new Class[] { Integer.TYPE, Integer.TYPE } );
SET_WINDOW_LONG = osWinClass.getMethod( "SetWindowLongW", //$NON-NLS-1$
new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE } );
INVALIDATE_RECT = osWinClass.getMethod("InvalidateRect", //$NON-NLS-1$
new Class[] { Integer.TYPE, Class.forName(
"org.eclipse.swt.internal.win32.RECT"), //$NON-NLS-1$
Boolean.TYPE } );
Field field = osWinClass.getField( "GWL_EXSTYLE" ); //$NON-NLS-1$
OS_STYLE_INDEX = field.getInt( null );
field = osWinClass.getField( "WS_EX_LAYOUTRTL" ); //$NON-NLS-1$
WS_EX_LAYOUTRTL = field.getInt( null );
field = osWinClass.getField( "WS_EX_NOINHERITLAYOUT" ); //$NON-NLS-1$
WS_EX_NOINHERITLAYOUT = field.getInt( null );
STYLE_FIELD = Widget.class.getDeclaredField( "style" ); //$NON-NLS-1$
STYLE_FIELD.setAccessible( true );
HANDLE = Control.class.getDeclaredField( "handle" ); //$NON-NLS-1$
HANDLE.setAccessible( true );
}
}
catch ( ClassNotFoundException e )
{
osWinClass = null;
//Don't need handle the exception
//ExceptionHandler.handle( e, true );
}
catch ( NoSuchMethodException e )
{
osWinClass = null;
ExceptionHandler.handle( e, true );
}
catch ( SecurityException e )
{
osWinClass = null;
ExceptionHandler.handle( e, true );
}
catch ( NoSuchFieldException e )
{
osWinClass = null;
ExceptionHandler.handle( e, true );
}
catch ( IllegalArgumentException e )
{
osWinClass = null;
ExceptionHandler.handle( e, true );
}
catch ( IllegalAccessException e )
{
osWinClass = null;
ExceptionHandler.handle( e, true );
}
}
public void applyOrientation( Control control, boolean mirrored )
{
if ( control == null )
return;
if ( !isInitialized )
init( );
if ( osWinClass == null )
return;
int swtStyle = control.getStyle() & ~(SWT.RIGHT_TO_LEFT
| SWT.LEFT_TO_RIGHT | SWT.MIRRORED );
try
{
int osStyle = ( (Integer) GET_WINDOW_LONG.invoke( null,
new Object[] { Integer.valueOf( getControHandle( control ) ),
Integer.valueOf( OS_STYLE_INDEX ) } ) ).intValue( );
if ( mirrored )
{
SET_WINDOW_LONG.invoke( null, new Object[] { Integer.valueOf( getControHandle( control ) ),
Integer.valueOf( OS_STYLE_INDEX ), Integer.valueOf( osStyle
| WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT ) } );
swtStyle |= SWT.RIGHT_TO_LEFT | SWT.MIRRORED;
STYLE_FIELD.setInt( control, swtStyle );
}
else
{
SET_WINDOW_LONG.invoke( null, new Object[] { Integer.valueOf( getControHandle( control ) ),
Integer.valueOf( OS_STYLE_INDEX ), Integer.valueOf( osStyle
& ~WS_EX_LAYOUTRTL ) } );
swtStyle |= SWT.LEFT_TO_RIGHT;
STYLE_FIELD.setInt( control, swtStyle );
}
INVALIDATE_RECT.invoke( null, new Object[] { Integer.valueOf( getControHandle( control ) ),
null, Boolean.TRUE } );
}
catch ( SecurityException e )
{
ExceptionHandler.handle( e, true );
}
catch ( IllegalArgumentException e )
{
ExceptionHandler.handle( e, true );
}
catch ( IllegalAccessException e )
{
ExceptionHandler.handle( e, true );
}
catch ( InvocationTargetException e )
{
ExceptionHandler.handle( e, true );
}
if ( control instanceof Composite )
{
Control[] children = ( ( Composite )control ).getChildren( );
if ( children != null )
{
for ( int i = children.length; i
{
applyOrientation( children[i], mirrored );
}
}
}
}
public boolean isDirectionRTL( Object model )
{
return model instanceof DesignElementHandle
&& ( ( DesignElementHandle )model ).isDirectionRTL( );
}
public boolean isMirrored( Control control )
{
return control != null
&& ( control.getStyle( ) & SWT.RIGHT_TO_LEFT ) != 0;
}
private int getControHandle(Control control)
{
if (HANDLE != null)
{
try
{
return HANDLE.getInt( control );
}
catch ( IllegalArgumentException e )
{
//do notjing now
}
catch ( IllegalAccessException e )
{
//do notjing now
}
}
return -1;
}
/**
* Provides a TextLayout that can be used for Bidi purposes. This
* TextLayout should not be disposed by clients.
*
* @return an SWT TextLayout instance
*/
public synchronized TextLayout getTextLayout( int orientation )
{
if ( layout == null || layout.isDisposed( ) )
layout = new TextLayout( Display.getDefault( ) );
layout.setOrientation( orientation );
return layout;
}
protected void finalize( ) throws Throwable
{
System.out.println( "layout finalized" ); //$NON-NLS-1$
if ( layout != null && !layout.isDisposed( ) )
{
layout.dispose( );
}
layout = null;
super.finalize( );
}
}
|
package my.learning_java.addressbook.tests.tests_for_contacts;
import my.learning_java.addressbook.model.ContactData;
import my.learning_java.addressbook.tests.TestBase;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactInfoPageTest extends TestBase{
@BeforeMethod
public void ensurePrecondition() {
app.goTo().HomePage();
if (app.contact().all().size() == 0) {
app.contact().createContact(new ContactData().withName("Иван").withMiddleName("Иванович").withLastName("Иванов")
.withHomePhone("89651231123").withEmail("test@test.test").withAddress("ул. Мира, д.123"));
}
}
// (enable = false)
@Test
public void testContactPage(){
app.goTo().HomePage();
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
ContactData contactInfoFromInfoForm = app.contact().infoFromInfoForm(contact);
assertThat(cleaned(mergeAllContactInfoFromEditForm(contactInfoFromEditForm)),
equalTo(cleaned(mergeAllContactInfoFromInfoForm(contactInfoFromInfoForm))));
}
private String mergeAllContactInfoFromEditForm(ContactData contact) {
String homePhone = contact.getHomePhone();
if (homePhone != null && !homePhone.isEmpty()){
homePhone = "H: " + homePhone;
}
String mobilePhone = contact.getMobilePhone();
if (mobilePhone != null && !mobilePhone.isEmpty() ){
mobilePhone = "M: " + mobilePhone;
}
String workPhone = contact.getWorkPhone();
if (workPhone != null && !workPhone.isEmpty()){
workPhone = "W: " + workPhone;
}
String email = contact.getEmail();
if (email != null && !email.isEmpty()){
email = email + " (www."+ email.substring(email.indexOf("@")+1) +")";
}
String email2 = contact.getEmail2();
if (email2 != null && !email2.isEmpty()){
email2 = email2 + " (www."+ email2.substring(email2.indexOf("@")+1) +")";
}
String email3 = contact.getEmail3();
if (email3 != null && !email3.isEmpty()){
email3 = email3 + " (www."+ email3.substring(email3.indexOf("@")+1) +")";
}
return Arrays.asList(contact.getName(), contact.getMiddleName(), contact.getLastName()
, contact.getAddress(), homePhone, mobilePhone, workPhone,
email, email2, email3)
.stream().filter((s) -> s != null && !s.equals(""))
.collect(Collectors.joining("\n"));
}
private String mergeAllContactInfoFromInfoForm(ContactData contact) {
return Arrays.asList(contact.getAllInfo())
.stream().filter((s) -> s != null && !s.equals(""))
.collect(Collectors.joining("\n"));
}
public static String cleaned(String phone){
return phone.replaceAll("\\s"," ").replaceAll(" "," ");
}
}
|
package versioned.host.exp.exponent.modules.api.components.svg;
import android.graphics.Bitmap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.BaseViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaNodeAPI;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* ViewManager for RNSVGSvgView React views. Renders as a {@link RNSVGSvgView} and handles
* invalidating the native view on shadow view updates happening in the underlying tree.
*/
public class RNSVGSvgViewManager extends BaseViewManager<RNSVGSvgView, RNSVGSvgViewShadowNode> {
private static final String REACT_CLASS = "RNSVGSvgView";
private static final int COMMAND_TO_DATA_URL = 100;
private static final YogaMeasureFunction MEASURE_FUNCTION = new YogaMeasureFunction() {
@Override
public long measure(
YogaNodeAPI node,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode) {
throw new IllegalStateException("SurfaceView should have explicit width and height set");
}
};
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public Class<RNSVGSvgViewShadowNode> getShadowNodeClass() {
return RNSVGSvgViewShadowNode.class;
}
@Override
public RNSVGSvgViewShadowNode createShadowNodeInstance() {
RNSVGSvgViewShadowNode node = new RNSVGSvgViewShadowNode();
node.setMeasureFunction(MEASURE_FUNCTION);
return node;
}
@Override
protected RNSVGSvgView createViewInstance(ThemedReactContext reactContext) {
return new RNSVGSvgView(reactContext);
}
@Override
public void updateExtraData(RNSVGSvgView root, Object extraData) {
root.setBitmap((Bitmap) extraData);
}
@Override
public @Nullable Map<String, Integer> getCommandsMap() {
Map<String, Integer> commandsMap = super.getCommandsMap();
if (commandsMap == null) {
commandsMap = new HashMap<>();
}
commandsMap.put("toDataURL", COMMAND_TO_DATA_URL);
return commandsMap;
}
@Override
@Nullable
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
MapBuilder.Builder<String, Object> builder = MapBuilder.builder();
for (RNSVGSvgView.Events event : RNSVGSvgView.Events.values()) {
builder.put(event.toString(), MapBuilder.of("registrationName", event.toString()));
}
return builder.build();
}
@Override
public void receiveCommand(RNSVGSvgView root, int commandId, @Nullable ReadableArray args) {
super.receiveCommand(root, commandId, args);
switch (commandId) {
case COMMAND_TO_DATA_URL:
root.onDataURL();
break;
}
}
}
|
package org.ovirt.engine.core.bll.memory;
import java.util.List;
import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.vdscommands.DeleteImageGroupVDSCommandParameters;
import org.ovirt.engine.core.compat.Guid;
public class MemoryImageRemoverFromExportDomain extends MemoryImageRemover {
private Guid storagePoolId;
private Guid storageDomainId;
protected Boolean cachedPostZero;
private VM vm;
public MemoryImageRemoverFromExportDomain(VM vm, TaskHandlerCommand<?> enclosingCommand,
Guid storagePoolId, Guid storageDomainId) {
super(enclosingCommand);
this.vm = vm;
this.storagePoolId = storagePoolId;
this.storageDomainId = storageDomainId;
}
public void remove() {
removeMemoryVolumes(MemoryUtils.getMemoryVolumesFromSnapshots(vm.getSnapshots()));
}
@Override
protected boolean removeMemoryVolume(String memoryVolumes) {
return super.removeMemoryVolume(
MemoryUtils.changeStorageDomainAndPoolInMemoryState(
memoryVolumes, storageDomainId, storagePoolId));
}
@Override
protected DeleteImageGroupVDSCommandParameters buildDeleteMemoryImageParams(List<Guid> guids) {
return new DeleteImageGroupVDSCommandParameters(
guids.get(1), guids.get(0), guids.get(2), isPostZero(), false);
}
@Override
protected DeleteImageGroupVDSCommandParameters buildDeleteMemoryConfParams(List<Guid> guids) {
return new DeleteImageGroupVDSCommandParameters(
guids.get(1), guids.get(0), guids.get(4), isPostZero(), false);
}
/**
* We set the post zero field on memory image deletion from export domain as we do
* when it is deleted from data domain even though the export domain is NFS and NFS
* storage do the wipe on its own, in order to be compliance with the rest of the
* code that do the same, and to be prepared for supporting export domains which
* are not NFS.
*/
protected boolean isPostZero() {
if (cachedPostZero == null) {
cachedPostZero = isVmContainsWipeAfterDeleteDisk();
}
return cachedPostZero;
}
/**
* @return true IFF one of the disks is marked with wipe_after_delete
*/
private boolean isVmContainsWipeAfterDeleteDisk() {
for (Disk disk : vm.getDiskMap().values()) {
if (disk.isWipeAfterDelete()) {
return true;
}
}
return false;
}
}
|
package org.openhab.binding.netatmo.internal;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.openhab.binding.netatmo.internal.messages.MeasurementRequest.createKey;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openhab.binding.netatmo.NetatmoBindingProvider;
import org.openhab.binding.netatmo.internal.messages.DeviceListRequest;
import org.openhab.binding.netatmo.internal.messages.DeviceListResponse;
import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Device;
import org.openhab.binding.netatmo.internal.messages.DeviceListResponse.Module;
import org.openhab.binding.netatmo.internal.messages.MeasurementRequest;
import org.openhab.binding.netatmo.internal.messages.MeasurementResponse;
import org.openhab.binding.netatmo.internal.messages.NetatmoError;
import org.openhab.binding.netatmo.internal.messages.RefreshTokenRequest;
import org.openhab.binding.netatmo.internal.messages.RefreshTokenResponse;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.PointType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NetatmoBinding extends
AbstractActiveBinding<NetatmoBindingProvider> implements ManagedService {
private static final String DEFAULT_USER_ID = "DEFAULT_USER";
private static final Logger logger = LoggerFactory
.getLogger(NetatmoBinding.class);
protected static final String CONFIG_CLIENT_ID = "clientid";
protected static final String CONFIG_CLIENT_SECRET = "clientsecret";
protected static final String CONFIG_REFRESH = "refresh";
protected static final String CONFIG_REFRESH_TOKEN = "refreshtoken";
/**
* The refresh interval which is used to poll values from the Netatmo server
* (optional, defaults to 300000ms)
*/
private long refreshInterval = 300000;
private PointType stationPosition = null;
private Map<String, OAuthCredentials> credentialsCache = new HashMap<String, OAuthCredentials>();
/**
* {@inheritDoc}
*/
@Override
protected String getName() {
return "Netatmo Refresh Service";
}
/**
* {@inheritDoc}
*/
@Override
protected long getRefreshInterval() {
return this.refreshInterval;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("incomplete-switch")
@Override
protected void execute() {
logger.debug("Querying Netatmo API");
for (String userid : credentialsCache.keySet()) {
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
if (oauthCredentials.noAccessToken()) {
// initial run after a restart, so get an access token first
oauthCredentials.refreshAccessToken();
}
try {
if (oauthCredentials.firstExecution) {
processDeviceList(oauthCredentials);
}
DeviceMeasureValueMap deviceMeasureValueMap = processMeasurements(oauthCredentials);
if (deviceMeasureValueMap == null) {
return;
}
for (final NetatmoBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
final String deviceId = provider.getDeviceId(itemName);
final String moduleId = provider.getModuleId(itemName);
final NetatmoMeasureType measureType = provider
.getMeasureType(itemName);
State state = null;
switch (measureType) {
case MODULENAME:
if (moduleId == null) // we're on the main device
for (Device device : oauthCredentials.deviceListResponse
.getDevices()) {
if (device.getId().equals(deviceId)) {
state = new StringType(
device.getModuleName());
break;
}
}
else {
for (Module module : oauthCredentials.deviceListResponse
.getModules()) {
if (module.getId().equals(moduleId)) {
state = new StringType(
module.getModuleName());
break;
}
}
}
break;
case TIMESTAMP:
state = deviceMeasureValueMap.timeStamp;
break;
case TEMPERATURE:
case CO2:
case HUMIDITY:
case NOISE:
case PRESSURE:
case RAIN:
final String requestKey = createKey(deviceId,
moduleId);
final Map<String, BigDecimal> map = deviceMeasureValueMap
.get(requestKey);
final BigDecimal value = map != null ? map
.get(measureType.getMeasure()) : null;
// Protect that sometimes Netatmo returns null where
// numeric value is awaited (issue #1848)
if (value != null) {
state = new DecimalType(value);
}
break;
case BATTERYVP:
case RFSTATUS:
for (Module module : oauthCredentials.deviceListResponse
.getModules()) {
if (module.getId().equals(moduleId)) {
switch (measureType) {
case BATTERYVP:
state = new DecimalType(
module.getBatteryLevel());
break;
case RFSTATUS:
state = new DecimalType(
module.getRfLevel());
break;
case MODULENAME:
state = new StringType(
module.getModuleName());
break;
}
}
}
break;
case ALTITUDE:
case LATITUDE:
case LONGITUDE:
case WIFISTATUS:
case COORDINATE:
case STATIONNAME:
for (Device device : oauthCredentials.deviceListResponse
.getDevices()) {
if (stationPosition == null) {
stationPosition = new PointType(
new DecimalType(
device.getLatitude()),
new DecimalType(device
.getLongitude()),
new DecimalType(device
.getAltitude()));
}
if (device.getId().equals(deviceId)) {
switch (measureType) {
case LATITUDE:
state = stationPosition.getLatitude();
break;
case LONGITUDE:
state = stationPosition.getLongitude();
break;
case ALTITUDE:
state = stationPosition.getAltitude();
break;
case WIFISTATUS:
state = new DecimalType(
device.getWifiLevel());
break;
case COORDINATE:
state = stationPosition;
break;
case STATIONNAME:
state = new StringType(
device.getStationName());
break;
}
}
}
break;
}
if (state != null) {
this.eventPublisher.postUpdate(itemName, state);
}
}
}
} catch (NetatmoException ne) {
logger.error(ne.getMessage());
}
}
}
static class DeviceMeasureValueMap extends
HashMap<String, Map<String, BigDecimal>> {
private static final long serialVersionUID = 1L;
DateTimeType timeStamp = null;
}
private DeviceMeasureValueMap processMeasurements(
OAuthCredentials oauthCredentials) {
DeviceMeasureValueMap deviceMeasureValueMap = new DeviceMeasureValueMap();
for (final MeasurementRequest request : createMeasurementRequests()) {
final MeasurementResponse response = request.execute();
logger.debug("Request: {}", request);
logger.debug("Response: {}", response);
if (response.isError()) {
final NetatmoError error = response.getError();
if (error.isAccessTokenExpired()) {
oauthCredentials.refreshAccessToken();
execute();
return null;
} else {
throw new NetatmoException(error.getMessage());
}
} else {
processMeasurementResponse(request, response,
deviceMeasureValueMap);
}
}
return deviceMeasureValueMap;
}
private void processDeviceList(OAuthCredentials oauthCredentials) {
logger.debug("Request: {}", oauthCredentials.deviceListRequest);
logger.debug("Response: {}", oauthCredentials.deviceListResponse);
if (oauthCredentials.deviceListResponse.isError()) {
final NetatmoError error = oauthCredentials.deviceListResponse
.getError();
if (error.isAccessTokenExpired()) {
oauthCredentials.refreshAccessToken();
execute();
} else {
throw new NetatmoException(error.getMessage());
}
return; // abort processing
} else {
processDeviceListResponse(oauthCredentials.deviceListResponse);
oauthCredentials.firstExecution = false;
}
}
/**
* Processes an incoming {@link DeviceListResponse}.
* <p>
*/
private void processDeviceListResponse(final DeviceListResponse response) {
// Prepare a map of all known device measurements
final Map<String, Device> deviceMap = new HashMap<String, Device>();
final Map<String, Set<String>> deviceMeasurements = new HashMap<String, Set<String>>();
for (final Device device : response.getDevices()) {
final String deviceId = device.getId();
deviceMap.put(deviceId, device);
for (final String measurement : device.getMeasurements()) {
if (!deviceMeasurements.containsKey(deviceId)) {
deviceMeasurements.put(deviceId, new HashSet<String>());
}
deviceMeasurements.get(deviceId).add(measurement);
}
}
// Prepare a map of all known module measurements
final Map<String, Module> moduleMap = new HashMap<String, Module>();
final Map<String, Set<String>> moduleMeasurements = new HashMap<String, Set<String>>();
for (final Module module : response.getModules()) {
final String moduleId = module.getId();
moduleMap.put(moduleId, module);
for (final String measurement : module.getMeasurements()) {
if (!moduleMeasurements.containsKey(moduleId)) {
moduleMeasurements.put(moduleId, new HashSet<String>());
}
moduleMeasurements.get(moduleId).add(measurement);
}
}
// Remove all configured items from the maps
for (final NetatmoBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
final String deviceId = provider.getDeviceId(itemName);
final String moduleId = provider.getModuleId(itemName);
final NetatmoMeasureType measureType = provider
.getMeasureType(itemName);
final Set<String> measurements;
if (moduleId != null) {
measurements = moduleMeasurements.get(moduleId);
} else {
measurements = deviceMeasurements.get(deviceId);
}
if (measurements != null) {
measurements.remove(measureType.getMeasure());
}
}
}
// Log all unconfigured measurements
final StringBuilder message = new StringBuilder();
for (Entry<String, Set<String>> entry : deviceMeasurements.entrySet()) {
final String deviceId = entry.getKey();
final Device device = deviceMap.get(deviceId);
for (String measurement : entry.getValue()) {
message.append("\t" + deviceId + "#" + measurement + " ("
+ device.getModuleName() + ")\n");
}
}
for (Entry<String, Set<String>> entry : moduleMeasurements.entrySet()) {
final String moduleId = entry.getKey();
final Module module = moduleMap.get(moduleId);
for (String measurement : entry.getValue()) {
message.append("\t" + module.getMainDevice() + "#" + moduleId
+ "#" + measurement + " (" + module.getModuleName()
+ ")\n");
}
}
if (message.length() > 0) {
message.insert(0,
"The following Netatmo measurements are not yet configured:\n");
logger.info(message.toString());
}
}
/**
* Creates the necessary requests to query the Netatmo API for all measures
* that have a binding. One request can query all measures of a single
* device or module.
*/
private Collection<MeasurementRequest> createMeasurementRequests() {
final Map<String, MeasurementRequest> requests = new HashMap<String, MeasurementRequest>();
for (final NetatmoBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
final String userid = provider.getUserid(itemName);
final String deviceId = provider.getDeviceId(itemName);
final String moduleId = provider.getModuleId(itemName);
final NetatmoMeasureType measureType = provider
.getMeasureType(itemName);
final String requestKey = createKey(deviceId, moduleId);
switch (measureType) {
case TEMPERATURE:
case CO2:
case HUMIDITY:
case NOISE:
case PRESSURE:
case RAIN:
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
if (oauthCredentials != null) {
if (!requests.containsKey(requestKey)) {
requests.put(requestKey, new MeasurementRequest(
oauthCredentials.accessToken, deviceId,
moduleId));
}
requests.get(requestKey).addMeasure(measureType);
break;
}
default:
break;
}
}
}
return requests.values();
}
private void processMeasurementResponse(final MeasurementRequest request,
final MeasurementResponse response,
DeviceMeasureValueMap deviceMeasureValueMap) {
final List<BigDecimal> values = response.getBody().get(0).getValues()
.get(0);
final Map<String, BigDecimal> valueMap = new HashMap<String, BigDecimal>();
int index = 0;
for (final String measure : request.getMeasures()) {
final BigDecimal value = values.get(index);
valueMap.put(measure, value);
index++;
}
deviceMeasureValueMap.put(request.getKey(), valueMap);
deviceMeasureValueMap.timeStamp = new DateTimeType(
response.getTimeStamp());
}
/**
* Returns the cached {@link OAuthCredentials} for the given {@code userid}.
* If their is no such cached {@link OAuthCredentials} element, the cache is
* searched with the {@code DEFAULT_USER}. If there is still no cached
* element found {@code NULL} is returned.
*
* @param userid
* the userid to find the {@link OAuthCredentials}
* @return the cached {@link OAuthCredentials} or {@code NULL}
*/
private OAuthCredentials getOAuthCredentials(String userid) {
if (credentialsCache.containsKey(userid)) {
return credentialsCache.get(userid);
} else {
return credentialsCache.get(DEFAULT_USER_ID);
}
}
/**
* {@inheritDoc}
*/
@Override
public void updated(final Dictionary<String, ?> config)
throws ConfigurationException {
if (config != null) {
final String refreshIntervalString = (String) config
.get(CONFIG_REFRESH);
if (isNotBlank(refreshIntervalString)) {
this.refreshInterval = Long.parseLong(refreshIntervalString);
}
Enumeration<String> configKeys = config.keys();
while (configKeys.hasMoreElements()) {
String configKey = configKeys.nextElement();
// the config-key enumeration contains additional keys that we
// don't want to process here ...
if (CONFIG_REFRESH.equals(configKey)
|| "service.pid".equals(configKey)) {
continue;
}
String userid;
String configKeyTail;
if (configKey.contains(".")) {
String[] keyElements = configKey.split("\\.");
userid = keyElements[0];
configKeyTail = keyElements[1];
} else {
userid = DEFAULT_USER_ID;
configKeyTail = configKey;
}
OAuthCredentials credentials = credentialsCache.get(userid);
if (credentials == null) {
credentials = new OAuthCredentials();
credentialsCache.put(userid, credentials);
}
String value = (String) config.get(configKeyTail);
if (CONFIG_CLIENT_ID.equals(configKeyTail)) {
credentials.clientId = value;
} else if (CONFIG_CLIENT_SECRET.equals(configKeyTail)) {
credentials.clientSecret = value;
} else if (CONFIG_REFRESH_TOKEN.equals(configKeyTail)) {
credentials.refreshToken = value;
} else {
throw new ConfigurationException(configKey,
"the given configKey '" + configKey
+ "' is unknown");
}
}
setProperlyConfigured(true);
}
}
/**
* This internal class holds the different crendentials necessary for the
* OAuth2 flow to work. It also provides basic methods to refresh the access
* token.
*
* @author Thomas.Eichstaedt-Engelen
* @since 1.6.0
*/
static class OAuthCredentials {
String clientId;
String clientSecret;
String refreshToken;
String accessToken;
DeviceListResponse deviceListResponse = null;
DeviceListRequest deviceListRequest = null;
boolean firstExecution = true;
public boolean noAccessToken() {
return this.accessToken == null;
}
public void refreshAccessToken() {
logger.debug("Refreshing access token.");
final RefreshTokenRequest request = new RefreshTokenRequest(
this.clientId, this.clientSecret, this.refreshToken);
logger.debug("Request: {}", request);
final RefreshTokenResponse response = request.execute();
logger.debug("Response: {}", response);
this.accessToken = response.getAccessToken();
deviceListRequest = new DeviceListRequest(this.accessToken);
deviceListResponse = deviceListRequest.execute();
}
}
}
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.common.util.UML2Util;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationship;
import org.openhealthtools.mdht.uml.cda.core.profile.EntryRelationshipKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Inline;
import org.openhealthtools.mdht.uml.cda.core.profile.LogicalConstraint;
import org.openhealthtools.mdht.uml.cda.core.profile.SeverityKind;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.common.util.NamedElementUtil;
import org.openhealthtools.mdht.uml.common.util.PropertyList;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
public static final String DATATYPES_NS_URI = "http:
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
private static final String EPACKAGE = "Ecore::EPackage";
private static final String EREFERENCE = "Ecore::EReference";
public static final String XMLNAMESPACE = "xmlNamespace";
private static final String NSPREFIX = "nsPrefix";
private static final String NSURI = "nsURI";
// This message may change in the future to specify certain nullFlavor Types (such as the implementation, NI)
private static final String NULLFLAVOR_SECTION_MESSAGE = "If section/@nullFlavor is not present, ";
public static boolean cardinalityAfterElement = false;
public static Class getCDAClass(Classifier templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass) && templateClass instanceof Class) {
return (Class) templateClass;
}
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class/datatype and not a template
if (isCDAModel(templateProperty) || isDatatypeModel(templateProperty)) {
return templateProperty;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName() != null && inherited.getName().equals(templateProperty.getName()) &&
(isCDAModel(inherited) || isDatatypeModel(inherited))) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*
* @deprecated Use the {@link UMLUtil#getInheritedProperty(Property)} API, instead.
*/
@Deprecated
public static Property getInheritedProperty(Property templateProperty) {
// for CDA, we restrict to Classes, not other classifiers
if (templateProperty.getClass_() == null) {
return null;
}
return UMLUtil.getInheritedProperty(templateProperty);
}
public static boolean isDatatypeModel(Element element) {
if (element != null && element.getNearestPackage() != null) {
Stereotype ePackage = element.getNearestPackage().getAppliedStereotype("Ecore::EPackage");
if (ePackage != null) {
return DATATYPES_NS_URI.equals(element.getNearestPackage().getValue(ePackage, "nsURI"));
}
}
return false;
}
/**
* isCDAModel - use get top package to support nested uml packages within CDA model
* primarily used for extensions
*
*/
public static boolean isCDAModel(Element element) {
if (element != null) {
Package neareastPackage = element.getNearestPackage();
if (neareastPackage != null) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(neareastPackage);
return CDA_PACKAGE_NAME.equals((topPackage != null)
? topPackage.getName()
: "");
}
}
return false;
}
public static Class getCDADatatype(Classifier datatype) {
Class result = null;
// if the provided class is from CDA datatypes
if (isDatatypeModel(datatype) && (datatype instanceof Class)) {
result = (Class) datatype;
} else {
for (Classifier parent : datatype.allParents()) {
// nearest package may be null if CDA datatypes model is not available
if (parent.getNearestPackage() != null) {
if (isDatatypeModel(parent) && (parent instanceof Class)) {
result = (Class) parent;
break;
}
}
}
}
return result;
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class) templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName())) {
return true;
}
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class) templateClass);
String cdaName = cdaClass == null
? null
: cdaClass.getName();
if (cdaClass != null &&
("Act".equals(cdaName) || "Encounter".equals(cdaName) || "Observation".equals(cdaName) ||
"ObservationMedia".equals(cdaName) || "Organizer".equals(cdaName) ||
"Procedure".equals(cdaName) || "RegionOfInterest".equals(cdaName) ||
"SubstanceAdministration".equals(cdaName) || "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
@Override
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
@Override
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
@Override
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
@Override
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String getValidationMessage(Element element) {
return getValidationMessage(element, ICDAProfileConstants.VALIDATION);
}
/**
* Obtains the user-specified validation message recorded in the given stereotype, or else
* {@linkplain #computeConformanceMessage(Element, boolean) computes} a suitable conformance message if none.
*
* @param element
* an element on which a validation constraint stereotype is defined
* @param validationStereotypeName
* the stereotype name (may be the abstract {@linkplain ICDAProfileConstants#VALIDATION Validation} stereotype)
*
* @return the most appropriate validation/conformance message
*
* @see #computeConformanceMessage(Element, boolean)
*/
public static String getValidationMessage(Element element, String validationStereotypeName) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
@Override
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
@Override
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
@Override
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
@Override
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
@Override
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, final boolean markup) {
String templateId = getTemplateId(template);
String templateVersion = getTemplateVersion(template);
String ruleIds = getConformanceRuleIds(template);
if (templateId == null) {
templateId = "";
}
String templateMultiplicity = CDATemplateComputeBuilder.getMultiplicityRange(getMultiplicityRange(template));
final String templateIdAsBusinessName = "=\"" + templateId + "\"";
final String templateVersionAsBusinessName = "=\"" + templateVersion + "\"";
final String multiplicityRange = templateMultiplicity.isEmpty()
? ""
: " [" + templateMultiplicity + "]";
CDATemplateComputeBuilder cdaTemplater = new CDATemplateComputeBuilder() {
@Override
public String addTemplateIdMultiplicity() {
return multiplicityElementToggle(markup, "templateId", multiplicityRange, "");
}
@Override
public String addRootMultiplicity() {
return multiplicityElementToggle(markup, "@root", " [1..1]", templateIdAsBusinessName);
}
@Override
public String addTemplateVersion() {
return multiplicityElementToggle(markup, "@extension", " [1..1]", templateVersionAsBusinessName);
}
};
return cdaTemplater.setRequireMarkup(markup).setRuleIds(ruleIds).setTemplateVersion(templateVersion).setMultiplicity(
multiplicityRange).compute().toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));
appendConformanceRuleIds(generalization, message, markup);
return message.toString();
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !UMLUtil.isSameModel(xrefSource, general)
? getModelPrefix(general) + " "
: "";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
Class cdaGeneral = getCDAClass(general);
if (cdaGeneral != null) {
message.append(markup
? "<b>"
: "");
message.append("SHALL");
message.append(markup
? "</b>"
: "");
message.append(" conform to ");
} else {
message.append("Extends ");
}
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(general);
String templateVersion = getTemplateVersion(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String getBusinessName(NamedElement property) {
String businessName = NamedElementUtil.getBusinessName(property);
if (!property.getName().equals(businessName)) {
return (" (" + businessName + ")");
}
return "";
}
private static StringBuffer multiplicityElementToggle(Property property, boolean markup, String elementName) {
StringBuffer message = new StringBuffer();
message.append(multiplicityElementToggle(
markup, elementName, getMultiplicityRange(property), getBusinessName(property)));
return message;
}
private static String multiplicityElementToggle(boolean markup, String elementName, String multiplicityRange,
String businessName) {
StringBuffer message = new StringBuffer();
if (!cardinalityAfterElement) {
message.append(multiplicityRange);
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
message.append(elementName);
message.append(markup
? "</b>"
: "");
message.append(businessName);
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(multiplicityRange);
}
return message.toString();
}
public static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (!isInlineClass(endType) && getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(
property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(association, property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
String elementName = getCDAElementName(property);
message.append(getMultiplicityText(property));
message.append(multiplicityElementToggle(property, markup, elementName));
// appendSubsetsNotation(property, message, markup, xrefSource);
if (appendNestedConformanceRules && endType != null) {
if (markup && isInlineClass(endType) && !isPublishSeperately(endType)) {
StringBuilder sb = new StringBuilder();
appendConformanceRuleIds(association, message, markup);
appendPropertyComments(sb, property, markup);
appendConformanceRules(sb, endType, (property.getUpper() == 1
? "This "
: "Such ") + (property.getUpper() == 1
? elementName
: NameUtilities.pluralize(elementName)) + " ", markup);
message.append(" " + sb + " ");
} else {
message.append(", where its type is ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
appendConformanceRuleIds(association, message, markup);
}
} else {
appendConformanceRuleIds(association, message, markup);
}
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup,
Package xrefSource, boolean appendNestedConformanceRules) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String elementName = getCDAElementName(property);
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
// errata 384 message support: if the class owner is a section, and it has an association
// to either a clinical statement or an Entry (Act, Observation, etc.), append the message
for (Property p : association.getMemberEnds()) {
if ((p.getName() != null && !p.getName().isEmpty()) && (p.getOwner() != null && p.getType() != null) &&
(isSection((Class) p.getOwner()) && isClinicalStatement(p.getType()) || isEntry(p.getType()))) {
message.append(NULLFLAVOR_SECTION_MESSAGE);
}
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
message.append(multiplicityElementToggle(property, markup, elementName));
appendConformanceRuleIds(association, message, markup);
if (appendNestedConformanceRules && property.getType() instanceof Class) {
Class inlinedClass = (Class) property.getType();
if (markup && isInlineClass(inlinedClass)) {
StringBuilder sb = new StringBuilder();
appendPropertyComments(sb, property, markup);
appendConformanceRules(sb, inlinedClass, (property.getUpper() == 1
? "This "
: "Such ") + (property.getUpper() == 1
? elementName
: NameUtilities.pluralize(elementName)) + " ", markup);
message.append(" " + sb);
}
}
if (!markup) {
String assocConstraints = computeAssociationConstraints(property, markup);
if (assocConstraints.length() > 0) {
message.append(assocConstraints);
}
}
return message.toString();
}
public static String computeAssociationConstraints(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Package xrefSource = UMLUtil.getTopPackage(property);
EntryRelationship entryRelationship = CDAProfileUtil.getEntryRelationship(association);
EntryRelationshipKind typeCode = entryRelationship != null
? entryRelationship.getTypeCode()
: null;
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
if (typeCode != null) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains ");
message.append(markup
? "<tt><b>"
: "").append("@typeCode=\"").append(markup
? "</b>"
: "");
message.append(typeCode).append("\" ");
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<i>"
: "");
message.append(typeCode.getLiteral());
message.append(markup
? "</i>"
: "");
message.append(markup
? "</li>"
: ", and");
}
// TODO: what I should really do is test for an *implied* ActRelationship or Participation association
if (endType != null && getCDAClass(endType) != null && !(isInlineClass(endType)) &&
!isInlineClass(property.getClass_())) {
message.append(markup
? "\n<li>"
: " ");
message.append("Contains exactly one [1..1] ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType)
? getModelPrefix(endType) + " "
: "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref
? "</xref>"
: "");
String templateId = getTemplateId(endType);
String templateVersion = getTemplateVersion(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup
? "<tt>"
: "");
message.append(templateId);
// if there is an extension, add a colon followed by its value
if (!StringUtils.isEmpty(templateVersion)) {
message.append(":" + templateVersion);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
message.append(markup
? "</li>"
: "");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
private static String getNameSpacePrefix(Property property) {
Property cdaBaseProperty = CDAModelUtil.getCDAProperty(property);
String nameSpacePrefix = null;
if (cdaBaseProperty != null) {
Stereotype eReferenceStereoetype = cdaBaseProperty.getAppliedStereotype(CDAModelUtil.EREFERENCE);
if (eReferenceStereoetype != null) {
String nameSpace = (String) cdaBaseProperty.getValue(eReferenceStereoetype, CDAModelUtil.XMLNAMESPACE);
if (!StringUtils.isEmpty(nameSpace)) {
Package topPackage = org.openhealthtools.mdht.uml.common.util.UMLUtil.getTopPackage(cdaBaseProperty.getNearestPackage());
Stereotype ePackageStereoetype = topPackage.getApplicableStereotype(CDAModelUtil.EPACKAGE);
if (ePackageStereoetype != null) {
if (nameSpace.equals(topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) topPackage.getValue(ePackageStereoetype, CDAModelUtil.NSPREFIX);
} else {
for (Package nestedPackage : topPackage.getNestedPackages()) {
if (nameSpace.equals(nestedPackage.getValue(ePackageStereoetype, CDAModelUtil.NSURI))) {
nameSpacePrefix = (String) nestedPackage.getValue(
ePackageStereoetype, CDAModelUtil.NSPREFIX);
}
}
}
}
}
}
}
return nameSpacePrefix;
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
return computeConformanceMessage(property, markup, xrefSource, true);
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource,
boolean appendNestedConformanceRules) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource, appendNestedConformanceRules);
}
StringBuffer message = new StringBuffer();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeywordWithPropertyRange(property);
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" contain ");
} else {
if (property.getUpper() < 0 || property.getUpper() > 1) {
message.append("contains ");
} else {
message.append("contain ");
}
}
message.append(getMultiplicityText(property));
if (!cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
message.append(" ");
message.append(markup
? "<tt><b>"
: "");
// classCode/moodCode
if (isXMLAttribute(property)) {
message.append("@");
}
String propertyPrefix = getNameSpacePrefix(property);
message.append(propertyPrefix != null
? propertyPrefix + ":" + property.getName()
: property.getName());
message.append(markup
? "</b>"
: "");
message.append(getBusinessName(property));
if (isXMLAttribute(property) && property.getDefault() != null) {
message.append("=\"").append(property.getDefault()).append("\" ");
}
message.append(markup
? "</tt>"
: "");
if (cardinalityAfterElement) {
message.append(getMultiplicityRange(property));
}
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property, ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(
ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(
property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup
? "<tt>"
: "");
message.append("/@nullFlavor");
message.append(markup
? "</tt>"
: "");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup
? "<i>"
: "");
message.append(nullFlavorLabel);
message.append(markup
? "</i>"
: "");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
SeverityKind level = (SeverityKind) property.getValue(
textValue, ICDAProfileConstants.VALIDATION_SEVERITY);
message.append(" and ").append(markup
? "<b>"
: "").append(level != null
? getValidationKeyword(level.getLiteral())
: keyword).append(markup
? "</b>"
: "").append(" equal \"").append(value).append("\"");
}
}
/*
* Append datatype restriction, if redefined to a specialized type
*/
List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property);
Property redefinedProperty = redefinedProperties.isEmpty()
? null
: redefinedProperties.get(0);
if (property.getType() != null &&
((redefinedProperty == null || (!isXMLAttribute(property) && (property.getType() != redefinedProperty.getType()))))) {
message.append(" with " + "@xsi:type=\"");
message.append(property.getType().getName());
message.append("\"");
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
// if there are terminology rule IDs, then include property rule IDs here
if (ruleIds.length() > 0) {
appendConformanceRuleIds(property, message, markup);
}
} else {
// PropertyConstraint stereotype ruleIds, if specified
appendConformanceRuleIds(property, message, markup);
}
Stereotype codeSystemConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
} else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
} else if (isHL7VocabAttribute(property) && property.getDefault() != null) {
String vocab = computeHL7VocabAttributeMessage(property, markup);
message.append(vocab);
}
// for vocab properties, put rule ID at end, use terminology constraint if specified
if (isHL7VocabAttribute(property)) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
appendTerminologyConformanceRuleIds(property, message, markup);
} else {
appendConformanceRuleIds(property, message, markup);
}
} else {
// rule IDs for the terminology constraint
appendTerminologyConformanceRuleIds(property, message, markup);
}
if (property.getType() != null && appendNestedConformanceRules && property.getType() instanceof Class) {
if (isInlineClass((Class) property.getType())) {
if (isPublishSeperately((Class) property.getType())) {
String xref = (property.getType() instanceof Classifier && UMLUtil.isSameProject(
property, property.getType()))
? computeXref(xrefSource, (Classifier) property.getType())
: null;
boolean showXref = markup && (xref != null);
if (showXref) {
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
message.append(showXref
? "<xref " + format + "href=\"" + xref + "\">"
: "");
message.append(UMLUtil.splitName(property.getType()));
message.append(showXref
? "</xref>"
: "");
}
} else {
StringBuilder sb = new StringBuilder();
boolean hadSideEffect = appendPropertyComments(sb, property, markup);
// this commented out line currently creates duplicate property messages if enabled (and hadSideEffect check is removed)
// appendConformanceRules(sb, (Class) property.getType(), "", markup);
if (hadSideEffect) {
message.append(" " + sb);
}
}
}
}
return message.toString();
}
private static void appendSubsetsNotation(Property property, StringBuffer message, boolean markup,
Package xrefSource) {
StringBuffer notation = new StringBuffer();
for (Property subsets : property.getSubsettedProperties()) {
if (subsets.getClass_() == null) {
// eliminate NPE when publishing stereotype references to UML metamodel
continue;
}
if (notation.length() == 0) {
notation.append(" {subsets ");
} else {
notation.append(", ");
}
String xref = computeXref(xrefSource, subsets.getClass_());
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
notation.append(showXref
? " <xref " + format + "href=\"" + xref + "\">"
: " ");
notation.append(UMLUtil.splitName(subsets.getClass_()));
notation.append(showXref
? "</xref>"
: "");
notation.append("::" + subsets.getName());
}
if (notation.length() > 0) {
notation.append("}");
}
message.append(notation);
}
private static final String[] OL = { "<ol>", "</ol>" };
private static final String[] LI = { "<li>", "</li>" };
private static final String[] NOOL = { "", " " };
private static final String[] NOLI = { "", " " };
static private void appendConformanceRules(StringBuilder appendB, Class umlClass, String prefix, boolean markup) {
String[] ol = markup
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
StringBuilder sb = new StringBuilder();
boolean hasRules = false;
if (!CDAModelUtil.isInlineClass(umlClass)) {
for (Generalization generalization : umlClass.getGeneralizations()) {
Classifier general = generalization.getGeneral();
if (!RIMModelUtil.isRIMModel(general) && !CDAModelUtil.isCDAModel(general)) {
String message = CDAModelUtil.computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
hasRules = true;
sb.append(li[0] + prefix + message + li[1]);
}
}
}
}
// categorize constraints by constrainedElement name
List<Constraint> unprocessedConstraints = new ArrayList<Constraint>();
// propertyName -> constraints
Map<String, List<Constraint>> constraintMap = new HashMap<String, List<Constraint>>();
// constraint -> sub-constraints
Map<Constraint, List<Constraint>> subConstraintMap = new HashMap<Constraint, List<Constraint>>();
for (Constraint constraint : umlClass.getOwnedRules()) {
unprocessedConstraints.add(constraint);
for (Element element : constraint.getConstrainedElements()) {
if (element instanceof Property) {
String name = ((Property) element).getName();
List<Constraint> rules = constraintMap.get(name);
if (rules == null) {
rules = new ArrayList<Constraint>();
constraintMap.put(name, rules);
}
rules.add(constraint);
} else if (element instanceof Constraint) {
Constraint subConstraint = (Constraint) element;
List<Constraint> rules = subConstraintMap.get(subConstraint);
if (rules == null) {
rules = new ArrayList<Constraint>();
subConstraintMap.put(subConstraint, rules);
}
rules.add(constraint);
}
}
}
PropertyList propertyList = new PropertyList(umlClass, CDAModelUtil.isInlineClass(umlClass));
// XML attributes
for (Property property : propertyList.getAttributes()) {
hasRules = hasRules |
appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
// XML elements
for (Property property : propertyList.getAssociationEnds()) {
hasRules = hasRules |
appendPropertyList(
umlClass, property, markup, ol, sb, prefix, li, constraintMap, unprocessedConstraints,
subConstraintMap);
}
for (Constraint constraint : unprocessedConstraints) {
hasRules = true;
sb.append(li[0] + prefix + CDAModelUtil.computeConformanceMessage(constraint, markup) + li[1]);
}
if (hasRules) {
appendB.append(ol[0]);
appendB.append(sb);
appendB.append(ol[1]);
}
}
private static boolean appendPropertyList(Element umlClass, Property property, boolean markup, String[] ol,
StringBuilder sb, String prefix, String[] li, Map<String, List<Constraint>> constraintMap,
List<Constraint> unprocessedConstraints, Map<Constraint, List<Constraint>> subConstraintMap) {
boolean result = false;
if (!CDAModelUtil.isCDAModel(umlClass) && !CDAModelUtil.isCDAModel(property) &&
!CDAModelUtil.isDatatypeModel(property)) {
result = true;
String ccm = CDAModelUtil.computeConformanceMessage(property, markup);
boolean order = ccm.trim().endsWith(ol[1]);
boolean currentlyItem = false;
if (order) {
int olIndex = ccm.lastIndexOf(ol[1]);
ccm = ccm.substring(0, olIndex);
currentlyItem = ccm.trim().endsWith(li[1]);
}
sb.append(li[0] + prefix + ccm);
StringBuilder propertyComments = new StringBuilder();
currentlyItem &= appendPropertyComments(propertyComments, property, markup);
if (currentlyItem) {
sb.append(li[0]).append(propertyComments).append(li[1]);
}
appendPropertyRules(sb, property, constraintMap, subConstraintMap, unprocessedConstraints, markup, !order);
if (order) {
sb.append(ol[1]);
}
sb.append(li[1]);
}
return result;
}
private static boolean appendPropertyComments(StringBuilder sb, Property property, boolean markup) {
// INLINE
Association association = property.getAssociation();
int startingStrLength = sb.length();
if (association != null && association.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : association.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
if (property.getOwnedComments().size() > 0) {
if (markup) {
sb.append("<p><lines><i>");
}
for (Comment comment : property.getOwnedComments()) {
sb.append(CDAModelUtil.fixNonXMLCharacters(comment.getBody()));
}
if (markup) {
sb.append("</i></lines></p>");
}
}
return sb.length() > startingStrLength;
}
private static void appendPropertyRules(StringBuilder sb, Property property,
Map<String, List<Constraint>> constraintMap, Map<Constraint, List<Constraint>> subConstraintMap,
List<Constraint> unprocessedConstraints, boolean markup, boolean newOrder) {
String[] ol = markup && newOrder
? OL
: NOOL;
String[] li = markup
? LI
: NOLI;
// association typeCode and property type
String assocConstraints = "";
if (property.getAssociation() != null) {
assocConstraints = CDAModelUtil.computeAssociationConstraints(property, markup);
}
StringBuffer ruleConstraints = new StringBuffer();
List<Constraint> rules = constraintMap.get(property.getName());
if (rules != null && !rules.isEmpty()) {
for (Constraint constraint : rules) {
unprocessedConstraints.remove(constraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(constraint, markup));
appendSubConstraintRules(ruleConstraints, constraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
}
if (assocConstraints.length() > 0 || ruleConstraints.length() > 0) {
sb.append(ol[0]);
sb.append(assocConstraints);
sb.append(ruleConstraints);
sb.append(ol[1]);
}
}
private static void appendSubConstraintRules(StringBuffer ruleConstraints, Constraint constraint,
Map<Constraint, List<Constraint>> subConstraintMap, List<Constraint> unprocessedConstraints, boolean markup) {
String[] ol;
String[] li;
if (markup) {
ol = OL;
li = LI;
} else {
ol = NOOL;
li = NOLI;
}
List<Constraint> subConstraints = subConstraintMap.get(constraint);
if (subConstraints != null && subConstraints.size() > 0) {
ruleConstraints.append(ol[0]);
for (Constraint subConstraint : subConstraints) {
unprocessedConstraints.remove(subConstraint);
ruleConstraints.append(li[0] + CDAModelUtil.computeConformanceMessage(subConstraint, markup));
appendSubConstraintRules(
ruleConstraints, subConstraint, subConstraintMap, unprocessedConstraints, markup);
ruleConstraints.append(li[1]);
}
ruleConstraints.append(ol[1]);
}
}
private static boolean isHL7VocabAttribute(Property property) {
String name = property.getName();
return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name);
}
private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());
String code = property.getDefault();
String displayName = null;
String codeSystemId = null;
String codeSystemName = null;
if (rimClass != null) {
if ("Act".equals(rimClass.getName())) {
if ("classCode".equals(property.getName())) {
codeSystemName = "HL7ActClass";
codeSystemId = "2.16.840.1.113883.5.6";
if ("ACT".equals(code)) {
displayName = "Act";
} else if ("OBS".equals(code)) {
displayName = "Observation";
}
} else if ("moodCode".equals(property.getName())) {
codeSystemName = "HL7ActMood";
codeSystemId = "2.16.840.1.113883.5.1001";
if ("EVN".equals(code)) {
displayName = "Event";
}
}
}
}
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
if (codeSystemId != null || codeSystemName != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (codeSystemId != null) {
message.append(" ").append(codeSystemId);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
Stereotype codeSystemConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
CodeSystemConstraint codeSystemConstraint = TermProfileUtil.getCodeSystemConstraint(property);
String keyword = getValidationKeyword(property, codeSystemConstraintStereotype);
String id = null;
String name = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
codeSystemVersion.getVersion();
} else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
codeSystemConstraint.getVersion();
}
codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup
? "<tt><b>"
: "");
// single value binding
message.append("/@code");
message.append(markup
? "</b>"
: "");
message.append("=\"").append(code).append("\" ");
message.append(markup
? "</tt>"
: "");
if (displayName != null) {
message.append(markup
? "<i>"
: "");
message.append(displayName);
message.append(markup
? "</i>"
: "");
}
} else {
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from");
}
if (id != null || name != null) {
message.append(" (CodeSystem:");
message.append(markup
? "<tt>"
: "");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(markup
? "</tt>"
: "");
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
Stereotype valueSetConstraintStereotype = TermProfileUtil.getAppliedStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
ValueSetConstraint valueSetConstraint = TermProfileUtil.getValueSetConstraint(property);
String keyword = getValidationKeyword(property, valueSetConstraintStereotype);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html")
? "format=\"html\" "
: "";
} else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
// capture and return proper xml binding message based on mandatory or not
message.append(mandatoryOrNotMessage(property));
if (keyword != null) {
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" be");
} else {
message.append("is");
}
message.append(" selected from ValueSet");
message.append(markup
? "<tt>"
: "");
if (name != null) {
message.append(" ");
message.append(showXref
? "<xref " + xrefFormat + "href=\"" + xref + "\">"
: "");
message.append(name);
message.append(showXref
? "</xref>"
: "");
}
if (id != null) {
message.append(" ").append(id);
}
message.append(markup
? "</tt>"
: "");
message.append(markup
? "<b>"
: "");
message.append(" ").append(binding.getName().toUpperCase());
message.append(markup
? "</b>"
: "");
if (BindingKind.STATIC == binding && version != null) {
message.append(" ").append(version);
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
LogicalConstraint logicConstraint = CDAProfileUtil.getLogicalConstraint(constraint);
if (logicConstraint != null) {
return computeLogicalConformanceMessage(constraint, logicConstraint, markup);
} else {
return computeCustomConformanceMessage(constraint, markup);
}
}
private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String strucTextBody = null;
String analysisBody = null;
Map<String, String> langBodyMap = new HashMap<String, String>();
CDAProfileUtil.getLogicalConstraint(constraint);
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("StrucText".equals(lang)) {
strucTextBody = body;
} else if ("Analysis".equals(lang)) {
analysisBody = body;
} else {
langBodyMap.put(lang, body);
}
}
}
String displayBody = null;
if (strucTextBody != null && strucTextBody.trim().length() > 0) {
// TODO if markup, parse strucTextBody and insert DITA markup
displayBody = strucTextBody;
} else if (analysisBody != null && analysisBody.trim().length() > 0) {
Boolean ditaEnabled = false;
try {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);
ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
} catch (IllegalArgumentException e) { /* Swallow this */
}
if (markup && !ditaEnabled) {
// escape non-dita markup in analysis text
displayBody = escapeMarkupCharacters(analysisBody);
// change severity words to bold text
displayBody = replaceSeverityWithBold(displayBody);
} else {
displayBody = analysisBody;
}
}
if (displayBody == null) {
List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
if (stereotypes.isEmpty()) {
// This should never happen but in case it does we deal with it appropriately
// by bypassing custom constraint message additions
return "";
}
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
if (displayBody == null || !containsSeverityWord(displayBody)) {
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" satisfy: ");
}
if (displayBody == null) {
message.append(constraint.getName());
} else {
message.append(displayBody);
}
appendConformanceRuleIds(constraint, message, markup);
if (!markup) {
// remove line feeds
int index;
while ((index = message.indexOf("\r")) >= 0) {
message.deleteCharAt(index);
}
while ((index = message.indexOf("\n")) >= 0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
private static String computeLogicalConformanceMessage(Constraint constraint, LogicalConstraint logicConstraint,
boolean markup) {
StringBuffer message = new StringBuffer();
logicConstraint.getMessage();
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup
? "<b>"
: "");
message.append(keyword);
message.append(markup
? "</b>"
: "");
message.append(" satisfy the following ");
boolean appendLogic = false;
message.append(OL[0]);
for (Element element : constraint.getConstrainedElements()) {
message.append(LI[0]);
if (appendLogic) {
message.append(markup
? "<b>"
: " ");
message.append(" " + logicConstraint.getOperation() + " ");
message.append(markup
? "</b>"
: " ");
} else {
appendLogic = true;
}
message.append(computeConformanceMessage(element, markup));
message.append(LI[1]);
}
message.append(OL[1]);
appendConformanceRuleIds(constraint, message, markup);
return message.toString();
}
private static boolean containsSeverityWord(String text) {
return text.indexOf("SHALL") >= 0 || text.indexOf("SHOULD") >= 0 || text.indexOf("MAY") >= 0;
}
private static String replaceSeverityWithBold(String input) {
String output;
output = input.replaceAll("SHALL", "<b>SHALL</b>");
output = output.replaceAll("SHOULD", "<b>SHOULD</b>");
output = output.replaceAll("MAY", "<b>MAY</b>");
output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>");
output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>");
return output;
}
/**
* FindResourcesByNameVisitor searches the resource for resources of a particular name
* You would think there was a method for this already but i could not find it
*
* @author seanmuir
*
*/
public static class FindResourcesByNameVisitor implements IResourceVisitor {
private String resourceName;
private ArrayList<IResource> resources = new ArrayList<IResource>();
/**
* @return the resources
*/
public ArrayList<IResource> getResources() {
return resources;
}
/**
* @param resourceName
*/
public FindResourcesByNameVisitor(String resourceName) {
super();
this.resourceName = resourceName;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceVisitor#visit(org.eclipse.core.resources.IResource)
*/
public boolean visit(IResource arg0) throws CoreException {
if (resourceName != null && resourceName.equals(arg0.getName())) {
resources.add(arg0);
}
return true;
}
}
public static IProject getElementModelProject(Element element) {
try {
Package elementPackage = UMLUtil.getTopPackage(element);
if (elementPackage != null && elementPackage.eResource() != null) {
FindResourcesByNameVisitor visitor = new FindResourcesByNameVisitor(
elementPackage.eResource().getURI().lastSegment());
IWorkspace iw = org.eclipse.core.resources.ResourcesPlugin.getWorkspace();
iw.getRoot().accept(visitor);
if (!visitor.getResources().isEmpty()) {
return visitor.getResources().get(0).getProject();
}
}
} catch (CoreException e) {
// If there is an issue with the workspace - return null
}
return null;
}
public static IProject getModelDocProject(IProject modelProject) {
if (modelProject != null && modelProject.exists()) {
return org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getProject(
modelProject.getName().replace(".model", ".doc"));
}
return null;
}
/**
* computeXref returns the XREF for DITA publication
*
* TODO Refactor and move out of model util
*
* @param source
* @param target
* @return
*/
public static String computeXref(Element source, Classifier target) {
if (target == null) {
return null;
}
if (target instanceof Enumeration) {
return computeTerminologyXref(source, (Enumeration) target);
}
if (UMLUtil.isSameProject(source, target)) {
return "../" + normalizeCodeName(target.getName()) + ".dita";
}
// If the model project is available (should be) and the dita content is part of the doc project
if (!isCDAModel(target)) {
IProject sourceProject = getElementModelProject(source);
sourceProject = getModelDocProject(sourceProject);
IProject targetProject = getElementModelProject(target);
targetProject = getModelDocProject(targetProject);
if (targetProject != null && sourceProject != null) {
IPath projectPath = new Path("/dita/classes/" + targetProject.getName());
IFolder referenceDitaFolder = sourceProject.getFolder(projectPath);
if (referenceDitaFolder.exists()) {
return "../" + targetProject.getName() + "/classes/" + normalizeCodeName(target.getName()) +
".dita";
}
}
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
} else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
} else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
return INFOCENTER_URL + "/topic/" + basePackage + "." + prefix + "doc/" + pathFolder + "/" +
normalizeCodeName(target.getName()) + ".html";
}
return null;
}
protected static String computeTerminologyXref(Element source, Enumeration target) {
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href = "../../terminology/" + normalizeCodeName(target.getName()) + ".dita";
}
return href;
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
/**
* getExtensionNamespace returns the name space from a extension package in the CDA model
*
* @param type
* @return
*/
private static String getExtensionNamespace(Type type) {
String nameSpace = null;
if (type != null && type.getNearestPackage() != null &&
!CDA_PACKAGE_NAME.equals(type.getNearestPackage().getName())) {
Stereotype ecoreStereotype = type.getNearestPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = type.getNearestPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
nameSpace = (String) object;
}
}
}
return nameSpace;
}
public static String getNameSpacePrefix(Class cdaSourceClass) {
if (cdaSourceClass != null && cdaSourceClass.getPackage() != null &&
!CDA_PACKAGE_NAME.equals(cdaSourceClass.getPackage().getName())) {
Stereotype ecoreStereotype = cdaSourceClass.getPackage().getAppliedStereotype(EPACKAGE);
if (ecoreStereotype != null) {
Object object = cdaSourceClass.getPackage().getValue(ecoreStereotype, NSPREFIX);
if (object instanceof String) {
return (String) object;
}
}
}
return null;
}
/**
* getCDAElementName - Returns the CDA Element name as a string
*
* @TODO Refactor to use org.openhealthtools.mdht.uml.transform.ecore.TransformAbstract.getInitialProperty(Property)
*
* Currently walk the redefines to see if we can match the CDA property using the name and type
* If none found - for backwards compatibility we look for a property in the base class with a matching type which is potential error prone
* If none still - leverage the getassociation
*
* @param property
* @return
*/
public static String getCDAElementName(Property property) {
String elementName = null;
if (property.getType() instanceof Class) {
Class cdaSourceClass = getCDAClass(property.getClass_());
if (cdaSourceClass != null) {
// First check for definitions
for (Property redefinedProperty : property.getRedefinedProperties()) {
// This will never succeed for associations, does not include ActRelationship
if (redefinedProperty.getType() != null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
redefinedProperty.getName(), getCDAClass((Classifier) redefinedProperty.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
break;
}
}
}
// Next check using property type and name
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
property.getName(), getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
// Ultimately use original logic for backwards compatibility
if (elementName == null) {
Property cdaProperty = cdaSourceClass.getOwnedAttribute(
null, getCDAClass((Classifier) property.getType()));
if (cdaProperty != null && cdaProperty.getName() != null) {
String modelPrefix = getExtensionNamespace(cdaProperty.getType());
elementName = !StringUtils.isEmpty(modelPrefix)
? modelPrefix + ":" + cdaProperty.getName()
: cdaProperty.getName();
}
}
}
}
// look for CDA association class element name, e.g. "component"
if (elementName == null) {
elementName = getCDAAssociationElementName(property);
}
if (elementName == null) {
elementName = property.getName();
}
return elementName;
}
public static String getCDAAssociationElementName(Property property) {
Class cdaSourceClass = getCDAClass(property.getClass_());
Class endType = (property.getType() instanceof Class)
? (Class) property.getType()
: null;
Class cdaTargetClass = endType != null
? getCDAClass(endType)
: null;
// This is incomplete determination of XML element name, but same logic as used in model transform
String elementName = null;
if (cdaSourceClass == null) {
elementName = property.getName();
} else if ("ClinicalDocument".equals(cdaSourceClass.getName()) &&
(CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) && (CDAModelUtil.isSection(cdaTargetClass))) {
elementName = "component";
} else if (CDAModelUtil.isSection(cdaSourceClass) &&
(CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {
elementName = "entry";
} else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "component";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "entryRelationship";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"ParticipantRole".equals(cdaTargetClass.getName())) {
elementName = "participant";
} else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && cdaTargetClass != null &&
"AssignedEntity".equals(cdaTargetClass.getName())) {
elementName = "performer";
}
return elementName;
}
private static String getMultiplicityRange(Property property) {
StringBuffer message = new StringBuffer();
String lower = Integer.toString(property.getLower());
String upper = property.getUpper() == -1
? "*"
: Integer.toString(property.getUpper());
message.append(" [").append(lower).append("..").append(upper).append("]");
return message.toString();
}
private static String getMultiplicityText(Property property) {
StringBuffer message = new StringBuffer();
if (property.getLower() == 1 && property.getUpper() == 1) {
message.append("exactly one");
} else if (property.getLower() == 0 && property.getUpper() == 1) {
message.append("zero or one");
} else if (property.getLower() == 0 && property.getUpper() == -1) {
message.append("zero or more");
} else if (property.getLower() == 1 && property.getUpper() == -1) {
message.append("at least one");
}
return message.toString();
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null) {
return true;
}
}
return false;
}
private static String getMultiplicityRange(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null && template.hasValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY)) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_MULTIPLICITY);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getMultiplicityRange((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
} else {
for (Classifier parent : template.getGenerals()) {
templateId = getTemplateId((Class) parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getTemplateVersion(Class template) {
String templateVersion = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateVersion = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_VERSION);
} else {
for (Classifier parent : template.getGenerals()) {
templateVersion = getTemplateId((Class) parent);
if (templateVersion != null) {
break;
}
}
}
return templateVersion;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package thePackage = UMLUtil.getTopPackage(element);
if (thePackage != null) {
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(
thePackage, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) thePackage.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
} else if (CDA_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "CDA";
} else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(thePackage.getName())) {
prefix = "RIM";
}
}
return prefix != null
? prefix
: "";
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda")) {
nsURI = "urn:hl7-org:v3";
} else if (model.getName().equals("datatypes")) {
nsURI = "http:
} else if (model.getName().equals("vocab")) {
nsURI = "http:
}
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null && modelPrefix.length() > 0) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
protected static void appendTerminologyConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getTerminologyConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Property property, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(property);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Association association, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(association);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(element);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
protected static void appendConformanceRuleIds(Element element, Stereotype stereotype, StringBuffer message,
boolean markup) {
String ruleIds = getConformanceRuleIds(element, stereotype);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Property property) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.PROPERTY_VALIDATION);
return getConformanceRuleIds(property, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getTerminologyConformanceRuleIds(Property property) {
Stereotype terminologyConstraint = getTerminologyConstraint(property);
return getConformanceRuleIds(property, terminologyConstraint);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Association association) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ASSOCIATION_VALIDATION);
return getConformanceRuleIds(association, validationSupport);
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return getConformanceRuleIds(element, validationSupport);
}
public static String getConformanceRuleIds(Element element, Stereotype validationSupport) {
StringBuffer ruleIdDisplay = new StringBuffer();
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0) {
ruleIdDisplay.append(", ");
}
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static Stereotype getTerminologyConstraint(Element element) {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
element, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
}
if (stereotype == null) {
stereotype = CDAProfileUtil.getAppliedCDAStereotype(element, ITermProfileConstants.VALUE_SET_CONSTRAINT);
}
return stereotype;
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
/**
* @deprecated Use {@link #getValidationSeverity(Property, String)} to get the severity for a specific validation stereotype.
* If necessary, this can be the abstract {@link ICDAProfileConstants#VALIDATION Validation} stereotype to get any available
* validation severity.
*/
@Deprecated
public static String getValidationSeverity(Property property) {
return getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
}
public static String getValidationSeverity(Property property, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(property, validationStereotypeName);
return getValidationSeverity(property, validationStereotype);
}
public static String getValidationSeverity(Element element) {
// use first available validation stereotype
return getValidationSeverity(element, ICDAProfileConstants.VALIDATION);
}
public static String getValidationSeverity(Element element, String validationStereotypeName) {
Stereotype validationStereotype = CDAProfileUtil.getAppliedCDAStereotype(element, validationStereotypeName);
return getValidationSeverity(element, validationStereotype);
}
public static String getValidationSeverity(Element element, Stereotype validationStereotype) {
String severity = null;
if ((validationStereotype != null) && CDAProfileUtil.isValidationStereotype(validationStereotype)) {
Object value = element.getValue(validationStereotype, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
severity = ((Enumerator) value).getName();
}
}
return severity;
}
public static String getValidationKeywordWithPropertyRange(Property property) {
String keyword = getValidationKeyword(property);
return addShallNot(keyword, property);
}
public static String getValidationKeyword(Property property) {
String severity = getValidationSeverity(property, ICDAProfileConstants.PROPERTY_VALIDATION);
if (severity == null) {
// get other validation stereotype, usually for terminology
severity = getValidationSeverity((Element) property);
}
return getValidationKeyword(severity);
}
public static String getValidationKeywordWithPropertyRange(Element element, Property property) {
// use first available validation stereotype
String keyword = getValidationKeyword(element);
return addShallNot(keyword, property);
}
private static String addShallNot(String keyword, Property property) {
if (property.getLower() == 0 && property.getUpper() == 0 && "SHALL".equals(keyword)) {
keyword += " NOT";
}
return keyword;
}
public static String getValidationKeyword(Element element) {
// use first available validation stereotype
String severity = getValidationSeverity(element);
return getValidationKeyword(severity);
}
public static String getValidationKeyword(Element element, Stereotype validationStereotype) {
String severity = getValidationSeverity(element, validationStereotype);
return getValidationKeyword(severity);
}
private static String getValidationKeyword(String severity) {
String keyword = null;
if (SEVERITY_INFO.equals(severity)) {
keyword = "MAY";
} else if (SEVERITY_WARNING.equals(severity)) {
keyword = "SHOULD";
} else if (SEVERITY_ERROR.equals(severity)) {
keyword = "SHALL";
}
return keyword;
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(
constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getName();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName,
Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral) value).getLabel();
} else if (value instanceof Enumerator) {
name = ((Enumerator) value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') {
newText.append("\"");
} else if (text.charAt(i) == '\u201C') {
newText.append("\"");
} else if (text.charAt(i) == '\u2019') {
newText.append("'");
} else if (text.charAt(i) == '\u2018') {
newText.append("'");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '<') {
newText.append("<");
} else if (text.charAt(i) == '>') {
newText.append(">");
} else {
newText.append(text.charAt(i));
}
}
return newText.toString();
}
public static String normalizeCodeName(String name) {
String result = "";
String[] parts = name.split(" ");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
result = UML2Util.getValidJavaIdentifier(result);
return result;
}
private static String mandatoryOrNotMessage(Property curProperty) {
// capture if allows nullFlavor or not
boolean mandatory = CDAProfileUtil.isMandatory(curProperty);
// mandatory implies nullFlavor is NOT allowed ", where the @code "
// non-mandatory implies nullFlavor is allowed ", which "
// return the proper message based on mandatory or not
return mandatory
? ", where the @code "
: ", which ";
}
public static boolean isInlineClass(Class _class) {
Inline inline = CDAProfileUtil.getInline(_class);
if (inline != null) {
return true;
}
if (_class.getOwner() instanceof Class) {
return true;
}
for (Comment comment : _class.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE")) {
return true;
}
}
return false;
}
public static String getInlineFilter(Class inlineClass) {
Inline inline = CDAProfileUtil.getInline(inlineClass);
if (inline != null) {
return inline.getFilter() != null
? inline.getFilter()
: "";
}
String filter = "";
for (Comment comment : inlineClass.getOwnedComments()) {
if (comment.getBody().startsWith("INLINE&")) {
String[] temp = comment.getBody().split("&");
if (temp.length == 2) {
filter = String.format("->select(%s)", temp[1]);
}
break;
}
}
if ("".equals(filter)) {
// search hierarchy
for (Classifier next : inlineClass.getGenerals()) {
if (next instanceof Class) {
filter = getInlineFilter((Class) next);
if (!"".equals(filter)) {
break;
}
}
}
}
return filter;
}
public static boolean isPublishSeperately(Class _class) {
boolean publish = false;
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(_class, ICDAProfileConstants.INLINE);
if (stereotype != null) {
Boolean result = (Boolean) _class.getValue(stereotype, "publishSeperately");
publish = result.booleanValue();
}
return publish;
}
}
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.cda.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
public static Class getCDAClass(Class templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass))
return templateClass;
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class and not a template
if (isCDAModel(templateProperty))
return templateProperty;
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName())
&& isCDAModel(inherited)) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*/
public static Property getInheritedProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName())) {
return inherited;
}
}
}
return null;
}
public static boolean isCDAModel(Element element) {
return CDA_PACKAGE_NAME.equals(element.getNearestPackage().getName());
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class)templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName()))
return true;
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class)templateClass);
String cdaName = cdaClass==null ? null : cdaClass.getName();
if (cdaClass != null && (
"Act".equals(cdaName) || "Encounter".equals(cdaName)
|| "Observation".equals(cdaName) || "ObservationMedia".equals(cdaName)
|| "Organizer".equals(cdaName) || "Procedure".equals(cdaName)
|| "RegionOfInterest".equals(cdaName) || "SubstanceAdministration".equals(cdaName)
|| "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(
Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, boolean markup) {
StringBuffer message = new StringBuffer();
String templateId = getTemplateId(template);
if (templateId != null) {
String ruleId = getConformanceRuleIds(template);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(template)).append(" ");
}
message.append("SHALL contain the template identifier ").append(templateId);
}
return message.toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
return computeGeneralizationConformanceMessage(general, markup, xrefSource);
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !isSameModel(xrefSource, general) ? getModelPrefix(general)+" " : "";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
// String ruleId = getConformanceRuleIds(generalization);
// if (ruleId.length() > 0) {
// message.append(markup?"<b>":"");
// message.append(ruleId + ": ");
// message.append(markup?"</b>":"");
message.append("Conforms to ");
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref?"</xref>":"");
String templateId = getTemplateId(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup?"<tt>":"");
message.append(templateId);
message.append(markup?"</tt>":"");
message.append(")");
}
return message.toString();
}
private static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String ruleId = getConformanceRuleIds(association);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
String elementName = getCDAElementName(property);
message.append(markup?"<tt>":"");
message.append(elementName);
message.append(markup?"</tt>":"");
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
if (endType != null) {
message.append(", where its type is ");
String prefix = !isSameModel(xrefSource, endType) ? getModelPrefix(endType)+" " : "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref?"</xref>":"");
}
// include comment text only in markup output
if (markup && association.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : association.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Stereotype entryStereotype = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ENTRY);
Stereotype entryRelationshipStereotype = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ENTRY_RELATIONSHIP);
String typeCode = null;
String typeCodeDisplay = null;
if (entryStereotype != null) {
typeCode = getLiteralValue(association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE);
Enumeration profileEnum = (Enumeration) entryStereotype.getProfile().getOwnedType(ICDAProfileConstants.ENTRY_KIND);
typeCodeDisplay = getLiteralValueLabel(association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE, profileEnum);
}
else if (entryRelationshipStereotype != null) {
typeCode = getLiteralValue(association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE);
Enumeration profileEnum = (Enumeration) entryRelationshipStereotype.getProfile().getOwnedType(ICDAProfileConstants.ENTRY_RELATIONSHIP_KIND);
typeCodeDisplay = getLiteralValueLabel(association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE, profileEnum);
}
String elementName = getCDAElementName(property);
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
String ruleId = getConformanceRuleIds(association);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup?"<tt>":"");
message.append(elementName);
message.append(markup?"</tt>":"");
if (typeCode != null || endType != null) {
message.append(", such that it");
message.append(markup?"<ol>":"");
if (typeCode != null) {
message.append(markup?"\n<li>":" ");
message.append("has @typeCode=\"");
message.append(typeCode).append("\" ");
message.append(markup?"<i>":"");
message.append(typeCodeDisplay);
message.append(markup?"</i>":"");
message.append(markup?"</li>":", and");
}
if (endType != null) {
message.append(markup?"\n<li>":" ");
message.append("contains ");
String prefix = !isSameModel(xrefSource, endType) ? getModelPrefix(endType)+" " : "";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref?"</xref>":"");
String templateId = getTemplateId(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup?"<tt>":"");
message.append(templateId);
message.append(markup?"</tt>":"");
message.append(")");
}
message.append(markup?"</li>":"");
}
message.append(markup?"</ol>":"");
}
// include comment text only in markup output
if (markup && association.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : association.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
String ruleId = getConformanceRuleIds(property);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(property);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup?"<tt>":"");
if (isXMLAttribute(property)) {
message.append("@");
}
message.append(property.getName());
message.append(markup?"</tt>":"");
if (isXMLAttribute(property) && property.getDefault() != null) {
message.append(" = \"").append(property.getDefault()).append("\"");
}
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property,
ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup?"<tt>":"");
message.append("/@nullFlavor");
message.append(markup?"</tt>":"");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup?"<i>":"");
message.append(nullFlavorLabel);
message.append(markup?"</i>":"");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
message.append(" = \"").append(value).append("\"");
}
}
// Stereotype conceptDomainConstraint = CDAProfileUtil.getAppliedCDAStereotype(
// property, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
Stereotype codeSystemConstraint = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
Stereotype vocabSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.VOCAB_SPECIFICATION);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
}
else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
}
else if (vocabSpecification != null) {
String vocab = computeVocabSpecificationMessage(property, markup);
message.append(vocab);
}
List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property);
Property redefinedProperty = redefinedProperties.isEmpty() ? null : redefinedProperties.get(0);
if (property.getType() != null && (redefinedProperty == null ||
(!isXMLAttribute(property)
&& (property.getType() != redefinedProperty.getType())))) {
message.append(", where its data type is ").append(property.getType().getName());
}
// include comment text only in markup output
if (markup && property.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : property.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
Stereotype codeSystemConstraintStereotype = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
CodeSystemConstraint codeSystemConstraint = (CodeSystemConstraint) property.getStereotypeApplication(codeSystemConstraintStereotype);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
version = codeSystemVersion.getVersion();
}
else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
version = codeSystemConstraint.getVersion();
}
binding = codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup?"<tt>":"");
message.append("/@code");
message.append(markup?"</tt>":"");
message.append(" = \"").append(code).append("\" ");
}
if (displayName != null) {
message.append(markup?"<i>":"");
message.append(displayName);
message.append(markup?"</i>":"");
}
if (id !=null || name != null) {
message.append(" (CodeSystem:");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(" ").append(binding.getName().toUpperCase());
if (version != null) {
message.append(" ").append(version);
}
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
Stereotype valueSetConstraintStereotype = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
ValueSetConstraint valueSetConstraint = (ValueSetConstraint) property.getStereotypeApplication(valueSetConstraintStereotype);
String keyword = getValidationKeyword(property);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
}
else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
message.append(", which ");
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" be selected from ValueSet");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ");
message.append(showXref ? "<xref " + xrefFormat + "href=\"" + xref + "\">" : "");
message.append(name);
message.append(showXref?"</xref>":"");
}
message.append(" ").append(binding.getName().toUpperCase());
if (version != null) {
message.append(" ").append(version);
}
return message.toString();
}
private static String computeVocabSpecificationMessage(Property property, boolean markup) {
Stereotype vocabSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.VOCAB_SPECIFICATION);
StringBuffer message = new StringBuffer();
String codeSystem = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM);
String codeSystemName = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM_NAME);
String codeSystemVersion = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM_VERSION);
String code = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE);
String displayName = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_DISPLAY_NAME);
if (code != null) {
message.append(markup?"<tt>":"");
message.append("/@code");
message.append(markup?"</tt>":"");
message.append(" = \"").append(code).append("\" ");
if (displayName != null) {
message.append(markup?"<i>":"");
message.append(displayName);
message.append(markup?"</i>":"");
}
if (codeSystem !=null || codeSystemName != null) {
message.append(" (CodeSystem:");
if (codeSystem != null) {
message.append(" ").append(codeSystem);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(" STATIC");
if (codeSystemVersion != null) {
message.append(" ").append(codeSystemVersion);
}
message.append(")");
}
}
//TODO for now, assume it's a value set if no code
else if (codeSystem !=null || codeSystemName != null) {
String keyword = getValidationKeyword(property);
message.append(", which ");
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" be selected from ValueSet");
if (codeSystem != null) {
message.append(" ").append(codeSystem);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
if (codeSystemVersion != null) {
message.append(" STATIC");
message.append(" ").append(codeSystemVersion);
}
else {
message.append(" DYNAMIC");
}
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String analysisBody = null;
Map<String,String> langBodyMap = new HashMap<String,String>();
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i=0; i<((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("Analysis".equals(lang)) {
analysisBody = body;
}
else {
langBodyMap.put(lang, body);
}
}
}
String ruleId = getConformanceRuleIds(constraint);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" satisfy: ");
if (analysisBody == null) {
message.append(constraint.getName());
}
else {
message.append(escapeMarkupCharacters(analysisBody));
}
// include comment text only in markup output
if (markup && constraint.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : constraint.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
if (markup && langBodyMap.size()>0) {
message.append("<ul>");
for (String lang : langBodyMap.keySet()) {
message.append("<li>");
message.append("<codeblock>[" + lang + "]: ");
message.append(escapeMarkupCharacters(langBodyMap.get(lang)));
message.append("</codeblock>");
message.append("</li>");
}
message.append("</ul>");
}
if (!markup) {
// remove line feeds
int index;
while ((index=message.indexOf("\r")) >=0) {
message.deleteCharAt(index);
}
while ((index=message.indexOf("\n")) >=0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
protected static String computeXref(Element source, Class target) {
String href = null;
if (isSameModel(source, target)) {
href="../" + target.getName() + ".dita";
}
else {
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
}
else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
href = INFOCENTER_URL + "/topic/" + basePackage + "."
+ prefix + "doc/" + pathFolder + "/" + target.getName() + ".html";
}
return href;
}
protected static String computeTerminologyXref(Class source, Enumeration target) {
String href = null;
if (isSameProject(source, target)) {
href="../../terminology/" + validFileName(target.getName()) + ".dita";
}
return href;
}
protected static boolean isSameModel(Element first, Element second) {
if (first == null || second == null)
return false;
else
return UMLUtil.getTopPackage(first).equals(UMLUtil.getTopPackage(second));
}
protected static boolean isSameProject(Element first, Element second) {
// get Resource, compare base path except for file name
// TODO also strip folder within project
URI firstURI = first.eResource().getURI();
URI secondURI = second.eResource().getURI();
return firstURI.trimSegments(1).equals(secondURI.trimSegments(1));
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
public static String getCDAElementName(Property property) {
Class cdaSourceClass = getCDAClass(property.getClass_());
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
Class cdaTargetClass = endType != null ? getCDAClass(endType) : null;
//TODO this is incomplete determination of XML element name
String elementName = property.getName();
if (cdaSourceClass == null) {
elementName = property.getName();
}
else if ("ClinicalDocument".equals(cdaSourceClass.getName())
&& (CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {
elementName = "component";
}
else if (CDAModelUtil.isSection(cdaSourceClass)
&& (CDAModelUtil.isSection(cdaTargetClass))) {
elementName = "component";
}
else if (CDAModelUtil.isSection(cdaSourceClass)
&& (CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {
elementName = "entry";
}
else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "component";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "entryRelationship";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && "ParticipantRole".equals(cdaTargetClass.getName())) {
elementName = "participant";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && "AssignedEntity".equals(cdaTargetClass.getName())) {
elementName = "performer";
}
return elementName;
}
public static String getMultiplicityString(Property property) {
String lower = Integer.toString(property.getLower());
String upper = property.getUpper()==-1 ? "*" : Integer.toString(property.getUpper());
StringBuffer message = new StringBuffer();
message.append("[").append(lower).append("..").append(upper).append("]");
return message.toString();
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null)
return true;
}
return false;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(
template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
}
return templateId;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
}
else if (CDA_PACKAGE_NAME.equals(model.getName())) {
prefix = "CDA";
}
else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(model.getName())) {
prefix = "RIM";
}
return prefix;
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda"))
nsURI = "urn:hl7-org:v3";
else if (model.getName().equals("datatypes"))
nsURI = "http:
else if (model.getName().equals("vocab"))
nsURI = "http:
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
public static String getValidationSeverity(Element element) {
String severity = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Object value = element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral)value).getName();
}
else if (value instanceof Enumerator) {
severity = ((Enumerator)value).getName();
}
// return (severity != null) ? severity : SEVERITY_ERROR;
}
return severity;
}
public static String getValidationMessage(Element element) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
StringBuffer ruleIdDisplay = new StringBuffer();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0)
ruleIdDisplay.append(", ");
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static String getValidationKeyword(Element element) {
String severity = getValidationSeverity(element);
if (severity != null) {
if (SEVERITY_INFO.equals(severity))
return "MAY";
else if (SEVERITY_WARNING.equals(severity))
return "SHOULD";
else if (SEVERITY_ERROR.equals(severity))
return "SHALL";
}
return null;
// if (element instanceof Association) {
// for (Property end : ((Association)element).getMemberEnds()) {
// if (end.isNavigable()) {
// element = end;
// break;
// if (element instanceof MultiplicityElement) {
// if (((MultiplicityElement)element).getLower() == 0)
// return "MAY";
// else
// return "SHALL";
// else {
// return "SHALL";
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
public static void setValidationRuleId(Element constrainedElement, String ruleId) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
List<String> ruleIds = new ArrayList<String>();
ruleIds.add(ruleId);
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_RULE_ID, ruleIds);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral)value).getName();
}
else if (value instanceof Enumerator) {
name = ((Enumerator)value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName, Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral)value).getLabel();
}
else if (value instanceof Enumerator) {
name = ((Enumerator)value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i=0; i<text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') // right double quote
newText.append("\"");
else if (text.charAt(i) == '\u201C') // left double quote
newText.append("\"");
else if (text.charAt(i) == '\u2019') // right single quote
newText.append("'");
else if (text.charAt(i) == '\u2018') // left single quote
newText.append("'");
// this won't allow markup in comments
// else if (text.charAt(i) == '<')
// newText.append("<");
// else if (text.charAt(i) == '>')
// newText.append(">");
// can't include this or escaped characters don't render, e.g. &
// else if (text.charAt(i) == '&')
// newText.append("&");
else
newText.append(text.charAt(i));
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i=0; i<text.length(); i++) {
if (text.charAt(i) == '<')
newText.append("<");
else if (text.charAt(i) == '>')
newText.append(">");
// can't include this or escaped characters don't render, e.g. &
// else if (text.charAt(i) == '&')
// newText.append("&");
else
newText.append(text.charAt(i));
}
return newText.toString();
}
public static String validFileName(String fileName) {
StringBuffer validName = new StringBuffer();
for (int i=0; i<fileName.length(); i++) {
if (fileName.charAt(i) == '/')
validName.append(" ");
else if (fileName.charAt(i) == '\\')
validName.append(" ");
else if (fileName.charAt(i) == '?')
validName.append("");
else
validName.append(fileName.charAt(i));
}
return validName.toString();
}
}
|
package nerd.tuxmobil.fahrplan.congress;
import nerd.tuxmobil.fahrplan.congress.CustomHttpClient.HTTP_STATUS;
import nerd.tuxmobil.fahrplan.congress.MyApp.TASKS;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.format.Time;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends SherlockFragmentActivity implements OnParseCompleteListener, OnDownloadCompleteListener, OnCloseDetailListener, OnRefreshEventMarers {
private static final String LOG_TAG = "MainActivity";
private FetchFahrplan fetcher;
private FahrplanParser parser;
private ProgressDialog progress = null;
private MyApp global;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.LogDebug(LOG_TAG, "onCreate");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main_layout);
if (MyApp.fetcher == null) {
fetcher = new FetchFahrplan();
} else {
fetcher = MyApp.fetcher;
}
if (MyApp.parser == null) {
parser = new FahrplanParser(getApplicationContext());
} else {
parser = MyApp.parser;
}
progress = null;
global = (MyApp) getApplicationContext();
FahrplanMisc.loadMeta(this);
FahrplanMisc.loadDays(this);
MyApp.LogDebug(LOG_TAG, "task_running:" + MyApp.task_running);
switch (MyApp.task_running) {
case FETCH:
MyApp.LogDebug(LOG_TAG, "fetch was pending, restart");
showFetchingStatus();
break;
case PARSE:
MyApp.LogDebug(LOG_TAG, "parse was pending, restart");
showParsingStatus();
break;
case NONE:
if (MyApp.numdays == 0) {
MyApp.LogDebug(LOG_TAG,"fetch in onCreate bc. numdays==0");
fetchFahrplan(this);
}
break;
}
if (findViewById(R.id.schedule) != null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.schedule, new FahrplanFragment(), "schedule");
fragmentTransaction.commit();
}
if (findViewById(R.id.detail) == null) {
FragmentManager fm = getSupportFragmentManager();
Fragment detail = fm.findFragmentByTag("detail");
if (detail != null) {
FragmentTransaction ft = fm.beginTransaction();
ft.remove(detail).commit();
}
}
}
public void parseFahrplan() {
showParsingStatus();
MyApp.task_running = TASKS.PARSE;
parser.setListener(this);
parser.parse(MyApp.fahrplan_xml, MyApp.eTag);
}
public void onGotResponse(HTTP_STATUS status, String response, String eTagStr) {
MyApp.LogDebug(LOG_TAG, "Response... " + status);
MyApp.task_running = TASKS.NONE;
if (MyApp.numdays == 0) {
if (progress != null) {
progress.dismiss();
progress = null;
}
}
if ((status == HTTP_STATUS.HTTP_OK) || (status == HTTP_STATUS.HTTP_NOT_MODIFIED)) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Time now = new Time();
now.setToNow();
long millis = now.toMillis(true);
Editor edit = prefs.edit();
edit.putLong("last_fetch", millis);
edit.commit();
}
if (status != HTTP_STATUS.HTTP_OK) {
switch (status) {
case HTTP_CANCELLED:
break;
case HTTP_LOGIN_FAIL_UNTRUSTED_CERTIFICATE: {
UntrustedCertDialogs.acceptKeyDialog(
R.string.dlg_certificate_message_fmt, this,
new cert_accepted() {
@Override
public void cert_accepted() {
MyApp.LogDebug(LOG_TAG, "fetch on cert accepted.");
fetchFahrplan(MainActivity.this);
}
}, (Object) null);
}
break;
}
CustomHttpClient.showHttpError(this, global, status);
setProgressBarIndeterminateVisibility(false);
return;
}
MyApp.LogDebug(LOG_TAG, "yehhahh");
setProgressBarIndeterminateVisibility(false);
MyApp.fahrplan_xml = response;
MyApp.eTag = eTagStr;
parseFahrplan();
}
@Override
public void onParseDone(Boolean result, String version) {
MyApp.LogDebug(LOG_TAG, "parseDone: " + result + " , numdays="+MyApp.numdays);
MyApp.task_running = TASKS.NONE;
MyApp.fahrplan_xml = null;
if (MyApp.numdays == 0) {
if (progress != null) {
progress.dismiss();
progress = null;
}
}
setProgressBarIndeterminateVisibility(false);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag("schedule");
if ((fragment != null) && (fragment instanceof OnParseCompleteListener)) {
((OnParseCompleteListener)fragment).onParseDone(result, version);
}
}
public void showFetchingStatus() {
if (MyApp.numdays == 0) {
// initial load
MyApp.LogDebug(LOG_TAG, "fetchFahrplan with numdays == 0");
progress = ProgressDialog.show(this, "", getResources().getString(
R.string.progress_loading_data), true);
} else {
MyApp.LogDebug(LOG_TAG, "show fetch status");
setProgressBarIndeterminateVisibility(true);
}
}
public void showParsingStatus() {
if (MyApp.numdays == 0) {
// initial load
progress = ProgressDialog.show(this, "", getResources().getString(
R.string.progress_processing_data), true);
} else {
MyApp.LogDebug(LOG_TAG, "show parse status");
setProgressBarIndeterminateVisibility(true);
}
}
public void fetchFahrplan(OnDownloadCompleteListener completeListener) {
if (MyApp.task_running == TASKS.NONE) {
MyApp.task_running = TASKS.FETCH;
showFetchingStatus();
fetcher.setListener(completeListener);
fetcher.fetch(MyApp.schedulePath, MyApp.eTag);
} else {
MyApp.LogDebug(LOG_TAG, "fetch already in progress");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (progress != null) {
progress.dismiss();
progress = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getSupportMenuInflater();
mi.inflate(R.menu.mainmenu, menu);
return true;
}
void aboutDialog() {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.about_dialog, (ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.eventVersion);
text.setText(getString(R.string.fahrplan) + " " + MyApp.version);
text = (TextView) layout.findViewById(R.id.eventTitle);
text.setText(MyApp.title);
MyApp.LogDebug(LOG_TAG, "title:" + MyApp.title);
text = (TextView) layout.findViewById(R.id.eventSubtitle);
text.setText(MyApp.subtitle);
text = (TextView) layout.findViewById(R.id.appVersion);
try {
text
.setText(getString(R.string.appVersion)
+ " "
+ getApplicationContext().getPackageManager()
.getPackageInfo("nerd.tuxmobil.fahrplan.congress", 0).versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
text.setText("");
}
TextView logo_copyright = (TextView)layout.findViewById(R.id.copyright_logo);
logo_copyright.setText(Html.fromHtml(getString(R.string.copyright_logo)));
logo_copyright.setMovementMethod(LinkMovementMethod.getInstance());
new AlertDialog.Builder(this).setTitle(getString(R.string.app_name))
.setView(layout).setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).create().show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.item_refresh:
fetchFahrplan(this);
return true;
case R.id.item_about:
aboutDialog();
return true;
case R.id.item_alarms:
intent = new Intent(this, AlarmList.class);
startActivityForResult(intent, MyApp.ALARMLIST);
return true;
case R.id.item_settings:
intent = new Intent(this, Prefs.class);
startActivity(intent);
return true;
default:
}
return super.onOptionsItemSelected(item);
}
public void openLectureDetail(Lecture lecture, int mDay) {
FrameLayout sidePane = (FrameLayout) findViewById(R.id.detail);
MyApp.LogDebug(LOG_TAG, "openLectureDetail sidePane="+sidePane);
if (sidePane != null) {
sidePane.setVisibility(View.VISIBLE);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
EventDetailFragment ev = new EventDetailFragment();
Bundle args = new Bundle();
args.putString("title", lecture.title);
args.putString("subtitle", lecture.subtitle);
args.putString("abstract", lecture.abstractt);
args.putString("descr", lecture.description);
args.putString("spkr", lecture.speakers.replaceAll(";", ", "));
args.putString("links", lecture.links);
args.putString("eventid", lecture.lecture_id);
args.putInt("time", lecture.startTime);
args.putInt("day", mDay);
args.putBoolean("sidepane", true);
ev.setArguments(args);
fragmentTransaction.replace(R.id.detail, ev, "detail");
fragmentTransaction.commit();
} else {
Intent intent = new Intent(this, EventDetail.class);
intent.putExtra("title", lecture.title);
intent.putExtra("subtitle", lecture.subtitle);
intent.putExtra("abstract", lecture.abstractt);
intent.putExtra("descr", lecture.description);
intent.putExtra("spkr", lecture.speakers.replaceAll(";", ", "));
intent.putExtra("links", lecture.links);
intent.putExtra("eventid", lecture.lecture_id);
intent.putExtra("time", lecture.startTime);
intent.putExtra("day", mDay);
startActivityForResult(intent, MyApp.EVENTVIEW);
}
}
@Override
public void closeDetailView() {
View sidePane = findViewById(R.id.detail);
if (sidePane != null) sidePane.setVisibility(View.GONE);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag("detail");
if (fragment != null) {
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.remove(fragment).commit();
}
}
@Override
public void refreshEventMarkers() {
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag("schedule");
if (fragment != null) {
((FahrplanFragment)fragment).refreshEventMarkers();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case MyApp.ALARMLIST:
case MyApp.EVENTVIEW:
if (resultCode == SherlockFragmentActivity.RESULT_OK) {
refreshEventMarkers();
}
break;
}
}
}
|
package org.openhealthtools.mdht.uml.cda.core.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.Generalization;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.util.UMLSwitch;
import org.openhealthtools.mdht.uml.cda.core.profile.CodeSystemConstraint;
import org.openhealthtools.mdht.uml.cda.core.profile.Validation;
import org.openhealthtools.mdht.uml.cda.core.profile.ValueSetConstraint;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.BindingKind;
import org.openhealthtools.mdht.uml.term.core.profile.CodeSystemVersion;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.ITermProfileConstants;
public class CDAModelUtil {
public static final String CDA_PACKAGE_NAME = "cda";
/** This base URL may be set from preferences or Ant task options. */
public static String INFOCENTER_URL = "http:
public static final String SEVERITY_ERROR = "ERROR";
public static final String SEVERITY_WARNING = "WARNING";
public static final String SEVERITY_INFO = "INFO";
public static Class getCDAClass(Class templateClass) {
Class cdaClass = null;
// if the provided class is from CDA and not a template
if (isCDAModel(templateClass))
return templateClass;
for (Classifier parent : templateClass.allParents()) {
// nearest package may be null if CDA model is not available
if (parent.getNearestPackage() != null) {
if (isCDAModel(parent) && parent instanceof Class) {
cdaClass = (Class) parent;
break;
}
}
}
return cdaClass;
}
public static Property getCDAProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
// if the provided property is from a CDA class and not a template
if (isCDAModel(templateProperty))
return templateProperty;
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName())
&& isCDAModel(inherited)) {
return inherited;
}
}
}
return null;
}
/**
* Returns the nearest inherited property with the same name, or null if not found.
*/
public static Property getInheritedProperty(Property templateProperty) {
if (templateProperty.getClass_() == null) {
return null;
}
for (Classifier parent : templateProperty.getClass_().allParents()) {
for (Property inherited : parent.getAttributes()) {
if (inherited.getName().equals(templateProperty.getName())) {
return inherited;
}
}
}
return null;
}
public static boolean isCDAModel(Element element) {
return CDA_PACKAGE_NAME.equals( (element.getNearestPackage()!=null) ? element.getNearestPackage().getName(): "");
}
public static boolean isCDAType(Type templateClass, String typeName) {
if (templateClass instanceof Class && typeName != null) {
Class cdaClass = getCDAClass((Class)templateClass);
if (cdaClass != null && typeName.equals(cdaClass.getName()))
return true;
}
return false;
}
public static boolean isClinicalDocument(Type templateClass) {
return isCDAType(templateClass, "ClinicalDocument");
}
public static boolean isSection(Type templateClass) {
return isCDAType(templateClass, "Section");
}
public static boolean isOrganizer(Type templateClass) {
return isCDAType(templateClass, "Organizer");
}
public static boolean isEntry(Type templateClass) {
return isCDAType(templateClass, "Entry");
}
public static boolean isClinicalStatement(Type templateClass) {
if (templateClass instanceof Class) {
Class cdaClass = getCDAClass((Class)templateClass);
String cdaName = cdaClass==null ? null : cdaClass.getName();
if (cdaClass != null && (
"Act".equals(cdaName) || "Encounter".equals(cdaName)
|| "Observation".equals(cdaName) || "ObservationMedia".equals(cdaName)
|| "Organizer".equals(cdaName) || "Procedure".equals(cdaName)
|| "RegionOfInterest".equals(cdaName) || "SubstanceAdministration".equals(cdaName)
|| "Supply".equals(cdaName))) {
return true;
}
}
return false;
}
public static void composeAllConformanceMessages(Element element, final PrintStream stream, final boolean markup) {
final TreeIterator<EObject> iterator = EcoreUtil.getAllContents(
Collections.singletonList(element));
while (iterator != null && iterator.hasNext()) {
EObject child = iterator.next();
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
public Object caseAssociation(Association association) {
iterator.prune();
return association;
}
public Object caseClass(Class umlClass) {
String message = computeConformanceMessage(umlClass, markup);
stream.println(message);
return umlClass;
}
public Object caseGeneralization(Generalization generalization) {
String message = computeConformanceMessage(generalization, markup);
if (message.length() > 0) {
stream.println(message);
}
return generalization;
}
public Object caseProperty(Property property) {
String message = computeConformanceMessage(property, markup);
if (message.length() > 0) {
stream.println(message);
}
return property;
}
public Object caseConstraint(Constraint constraint) {
String message = computeConformanceMessage(constraint, markup);
if (message.length() > 0) {
stream.println(message);
}
return constraint;
}
};
umlSwitch.doSwitch(child);
}
}
public static String computeConformanceMessage(Element element, final boolean markup) {
UMLSwitch<Object> umlSwitch = new UMLSwitch<Object>() {
public Object caseAssociation(Association association) {
String message = null;
Property property = getNavigableEnd(association);
if (property != null) {
message = computeConformanceMessage(property, false);
}
return message;
}
public Object caseClass(Class umlClass) {
return computeConformanceMessage(umlClass, markup);
}
public Object caseGeneralization(Generalization generalization) {
return computeConformanceMessage(generalization, markup);
}
public Object caseProperty(Property property) {
return computeConformanceMessage(property, markup);
}
public Object caseConstraint(Constraint constraint) {
return computeConformanceMessage(constraint, markup);
}
};
return (String) umlSwitch.doSwitch(element);
}
public static String computeConformanceMessage(Class template, boolean markup) {
StringBuffer message = new StringBuffer();
String templateId = getTemplateId(template);
if (templateId != null) {
String ruleId = getConformanceRuleIds(template);
if (ruleId.length() > 0) {
message.append(markup?"<b>":"");
message.append(ruleId + ": ");
message.append(markup?"</b>":"");
}
if (!markup) {
message.append(getPrefixedSplitName(template)).append(" ");
}
message.append("SHALL contain the template identifier ").append(templateId);
}
return message.toString();
}
public static String computeConformanceMessage(Generalization generalization, boolean markup) {
return computeConformanceMessage(generalization, markup, UMLUtil.getTopPackage(generalization));
}
public static String computeConformanceMessage(Generalization generalization, boolean markup, Package xrefSource) {
Class general = (Class) generalization.getGeneral();
StringBuffer message = new StringBuffer(computeGeneralizationConformanceMessage(general, markup, xrefSource));
appendConformanceRuleIds(generalization, message, markup);
return message.toString();
}
public static String computeGeneralizationConformanceMessage(Class general, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
String prefix = !UMLUtil.isSameModel(xrefSource, general) ? getModelPrefix(general)+" " : "";
// String prefix = getModelPrefix(general)+" ";
String xref = computeXref(xrefSource, general);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
message.append(markup?"<b>":"");
message.append("SHALL");
message.append(markup?"</b>":"");
message.append(" conform to ");
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(general));
message.append(showXref?"</xref>":"");
String templateId = getTemplateId(general);
if (templateId != null) {
message.append(" template (templateId: ");
message.append(markup?"<tt>":"");
message.append(templateId);
message.append(markup?"</tt>":"");
message.append(")");
}
return message.toString();
}
private static String computeAssociationConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (getTemplateId(property.getClass_()) != null) {
return computeTemplateAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
String elementName = getCDAElementName(property);
message.append(markup?"<tt><b>":"");
message.append(elementName);
message.append(markup?"</b></tt>":"");
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
if (endType != null) {
message.append(", where its type is ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType) ? getModelPrefix(endType)+" " : "";
// String prefix = getModelPrefix(endType)+" ";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref?"</xref>":"");
}
appendConformanceRuleIds(association, message, markup);
return message.toString();
}
private static String computeTemplateAssociationConformanceMessage(Property property, boolean markup, Package xrefSource) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
String elementName = getCDAElementName(property);
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(association);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup?"<tt><b>":"");
message.append(elementName);
message.append(markup?"</b></tt>":"");
appendConformanceRuleIds(association, message, markup);
message.append(", such that");
if (!markup) {
String assocConstraints = computeAssociationConstraints(property, markup);
if (assocConstraints.length() > 0) {
// message.append(", such that ");
// message.append(property.upperBound()==1 ? "it" : "each");
message.append(assocConstraints);
}
}
return message.toString();
}
public static String computeAssociationConstraints(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Association association = property.getAssociation();
Package xrefSource = UMLUtil.getTopPackage(property);
Stereotype entryStereotype = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ENTRY);
Stereotype entryRelationshipStereotype = CDAProfileUtil.getAppliedCDAStereotype(
association, ICDAProfileConstants.ENTRY_RELATIONSHIP);
String typeCode = null;
String typeCodeDisplay = null;
if (entryStereotype != null) {
typeCode = getLiteralValue(association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE);
Enumeration profileEnum = (Enumeration) entryStereotype.getProfile().getOwnedType(ICDAProfileConstants.ENTRY_KIND);
typeCodeDisplay = getLiteralValueLabel(association, entryStereotype, ICDAProfileConstants.ENTRY_TYPE_CODE, profileEnum);
}
else if (entryRelationshipStereotype != null) {
typeCode = getLiteralValue(association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE);
Enumeration profileEnum = (Enumeration) entryRelationshipStereotype.getProfile().getOwnedType(ICDAProfileConstants.ENTRY_RELATIONSHIP_KIND);
typeCodeDisplay = getLiteralValueLabel(association, entryRelationshipStereotype, ICDAProfileConstants.ENTRY_RELATIONSHIP_TYPE_CODE, profileEnum);
}
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
if (typeCode != null) {
message.append(markup?"\n<li>":" ");
// message.append(markup?"<b>":"").append("SHALL").append(markup?"</b>":"");
// message.append(" contain ");
message.append("Contains ");
message.append(markup?"<tt><b>":"").append("@typeCode=\"").append(markup?"</b>":"");
message.append(typeCode).append("\" ");
message.append(markup?"</tt>":"");
message.append(markup?"<i>":"");
message.append(typeCodeDisplay);
message.append(markup?"</i>":"");
message.append(markup?"</li>":", and");
}
// TODO: what I should really do is test for an *implied* ActRelationship or Participation association
if (endType != null && !CDAModelUtil.isCDAModel(endType)) {
message.append(markup?"\n<li>":" ");
// message.append(markup?"<b>":"").append("SHALL").append(markup?"</b>":"");
// message.append(" contain exactly one [1..1] ");
message.append("Contains exactly one [1..1] ");
String prefix = !UMLUtil.isSameModel(xrefSource, endType) ? getModelPrefix(endType)+" " : "";
// String prefix = getModelPrefix(endType)+" ";
String xref = computeXref(xrefSource, endType);
boolean showXref = markup && (xref != null);
String format = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
message.append(showXref ? "<xref " + format + "href=\"" + xref + "\">" : "");
message.append(prefix).append(UMLUtil.splitName(endType));
message.append(showXref?"</xref>":"");
String templateId = getTemplateId(endType);
if (templateId != null) {
message.append(" (templateId: ");
message.append(markup?"<tt>":"");
message.append(templateId);
message.append(markup?"</tt>":"");
message.append(")");
}
message.append(markup?"</li>":"");
}
return message.toString();
}
public static String computeConformanceMessage(Property property, boolean markup) {
return computeConformanceMessage(property, markup, UMLUtil.getTopPackage(property));
}
public static String computeConformanceMessage(Property property, boolean markup, Package xrefSource) {
if (property.getType() == null) {
System.out.println("Property has null type: " + property.getQualifiedName());
}
if (property.getAssociation() != null && property.isNavigable()) {
return computeAssociationConformanceMessage(property, markup, xrefSource);
}
StringBuffer message = new StringBuffer();
if (!markup) {
message.append(getPrefixedSplitName(property.getClass_())).append(" ");
}
String keyword = getValidationKeyword(property);
if (keyword != null) {
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" contain ");
}
else {
message.append("Contains ");
}
message.append(getMultiplicityString(property)).append(" ");
message.append(markup?"<tt><b>":"");
if (isXMLAttribute(property)) {
message.append("@");
}
message.append(property.getName());
message.append(markup?"</b>":"");
if (isXMLAttribute(property) && property.getDefault() != null) {
message.append("=\"").append(property.getDefault()).append("\" ");
}
message.append(markup?"</tt>":"");
Stereotype nullFlavorSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.NULL_FLAVOR);
Stereotype textValue = CDAProfileUtil.getAppliedCDAStereotype(property,
ICDAProfileConstants.TEXT_VALUE);
if (nullFlavorSpecification != null) {
String nullFlavor = getLiteralValue(property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR);
Enumeration profileEnum = (Enumeration) nullFlavorSpecification.getProfile().getOwnedType(ICDAProfileConstants.NULL_FLAVOR_KIND);
String nullFlavorLabel = getLiteralValueLabel(property, nullFlavorSpecification, ICDAProfileConstants.NULL_FLAVOR_NULL_FLAVOR, profileEnum);
if (nullFlavor != null) {
message.append(markup?"<tt>":"");
message.append("/@nullFlavor");
message.append(markup?"</tt>":"");
message.append(" = \"").append(nullFlavor).append("\" ");
message.append(markup?"<i>":"");
message.append(nullFlavorLabel);
message.append(markup?"</i>":"");
}
}
if (textValue != null) {
String value = (String) property.getValue(textValue, ICDAProfileConstants.TEXT_VALUE_VALUE);
if (value != null && value.length() > 0) {
message.append(" = \"").append(value).append("\"");
}
}
// Stereotype conceptDomainConstraint = CDAProfileUtil.getAppliedCDAStereotype(
// property, ITermProfileConstants.CONCEPT_DOMAIN_CONSTRAINT);
Stereotype codeSystemConstraint = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
Stereotype valueSetConstraint = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
Stereotype vocabSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.VOCAB_SPECIFICATION);
if (codeSystemConstraint != null) {
String vocab = computeCodeSystemMessage(property, markup);
message.append(vocab);
}
else if (valueSetConstraint != null) {
String vocab = computeValueSetMessage(property, markup, xrefSource);
message.append(vocab);
}
else if (vocabSpecification != null) {
String vocab = computeVocabSpecificationMessage(property, markup);
message.append(vocab);
}
else if (isHL7VocabAttribute(property) && property.getDefault() != null) {
String vocab = computeHL7VocabAttributeMessage(property, markup);
message.append(vocab);
}
List<Property> redefinedProperties = UMLUtil.getRedefinedProperties(property);
Property redefinedProperty = redefinedProperties.isEmpty() ? null : redefinedProperties.get(0);
if (property.getType() != null && (redefinedProperty == null ||
(!isXMLAttribute(property)
&& (property.getType() != redefinedProperty.getType())))) {
message.append(", where its data type is ").append(property.getType().getName());
}
appendConformanceRuleIds(property, message, markup);
return message.toString();
}
private static boolean isHL7VocabAttribute(Property property) {
String name = property.getName();
return "classCode".equals(name) || "moodCode".equals(name) || "typeCode".equals(name);
}
private static String computeHL7VocabAttributeMessage(Property property, boolean markup) {
StringBuffer message = new StringBuffer();
Class rimClass = RIMModelUtil.getRIMClass(property.getClass_());
String code = property.getDefault();
String displayName = null;
String codeSystemId = null;
String codeSystemName = null;
if (rimClass != null) {
if ("Act".equals(rimClass.getName())) {
if ("classCode".equals(property.getName())) {
codeSystemName = "HL7ActClass";
codeSystemId = "2.16.840.1.113883.5.6";
if ("ACT".equals(code))
displayName = "Act";
else if ("OBS".equals(code))
displayName = "Observation";
}
else if ("moodCode".equals(property.getName())) {
codeSystemName = "HL7ActMood";
codeSystemId = "2.16.840.1.113883.5.1001";
if ("EVN".equals(code))
displayName = "Event";
}
}
}
if (displayName != null) {
message.append(markup?"<i>":"");
message.append(displayName);
message.append(markup?"</i>":"");
}
if (codeSystemId != null || codeSystemName != null) {
message.append(" (CodeSystem:");
message.append(markup?"<tt>":"");
if (codeSystemId != null) {
message.append(" ").append(codeSystemId);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(markup?"</tt>":"");
message.append(")");
}
return message.toString();
}
private static String computeCodeSystemMessage(Property property, boolean markup) {
Stereotype codeSystemConstraintStereotype = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.CODE_SYSTEM_CONSTRAINT);
CodeSystemConstraint codeSystemConstraint = (CodeSystemConstraint) property.getStereotypeApplication(codeSystemConstraintStereotype);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String code = null;
String displayName = null;
if (codeSystemConstraint != null) {
if (codeSystemConstraint.getReference() != null) {
CodeSystemVersion codeSystemVersion = codeSystemConstraint.getReference();
id = codeSystemVersion.getIdentifier();
name = codeSystemVersion.getEnumerationName();
version = codeSystemVersion.getVersion();
}
else {
id = codeSystemConstraint.getIdentifier();
name = codeSystemConstraint.getName();
version = codeSystemConstraint.getVersion();
}
binding = codeSystemConstraint.getBinding();
code = codeSystemConstraint.getCode();
displayName = codeSystemConstraint.getDisplayName();
}
StringBuffer message = new StringBuffer();
if (code != null) {
message.append(markup?"<tt><b>":"");
message.append("/@code");
message.append(markup?"</b>":"");
message.append("=\"").append(code).append("\" ");
message.append(markup?"</tt>":"");
}
if (displayName != null) {
message.append(markup?"<i>":"");
message.append(displayName);
message.append(markup?"</i>":"");
}
if (id !=null || name != null) {
message.append(" (CodeSystem:");
message.append(markup?"<tt>":"");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ").append(name);
}
message.append(markup?"</tt>":"");
// message.append(" ").append(binding.getName().toUpperCase());
// if (version != null) {
// message.append(" ").append(version);
message.append(")");
}
return message.toString();
}
private static String computeValueSetMessage(Property property, boolean markup, Package xrefSource) {
Stereotype valueSetConstraintStereotype = CDAProfileUtil.getAppliedCDAStereotype(
property, ITermProfileConstants.VALUE_SET_CONSTRAINT);
ValueSetConstraint valueSetConstraint = (ValueSetConstraint) property.getStereotypeApplication(valueSetConstraintStereotype);
String keyword = getValidationKeyword(property);
String id = null;
String name = null;
String version = null;
BindingKind binding = null;
String xref = null;
String xrefFormat = "";
boolean showXref = false;
if (valueSetConstraint != null) {
if (valueSetConstraint.getReference() != null) {
ValueSetVersion valueSetVersion = valueSetConstraint.getReference();
id = valueSetVersion.getIdentifier();
name = valueSetVersion.getEnumerationName();
version = valueSetVersion.getVersion();
binding = valueSetVersion.getBinding();
if (valueSetVersion.getBase_Enumeration() != null) {
xref = computeTerminologyXref(property.getClass_(), valueSetVersion.getBase_Enumeration());
}
showXref = markup && (xref != null);
xrefFormat = showXref && xref.endsWith(".html") ? "format=\"html\" " : "";
}
else {
id = valueSetConstraint.getIdentifier();
name = valueSetConstraint.getName();
version = valueSetConstraint.getVersion();
binding = valueSetConstraint.getBinding();
}
}
StringBuffer message = new StringBuffer();
message.append(", which ");
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" be selected from ValueSet");
message.append(markup?"<tt>":"");
if (id != null) {
message.append(" ").append(id);
}
if (name != null) {
message.append(" ");
message.append(showXref ? "<xref " + xrefFormat + "href=\"" + xref + "\">" : "");
message.append(name);
message.append(showXref?"</xref>":"");
}
message.append(markup?"</tt>":"");
message.append(markup?"<b>":"");
message.append(" ").append(binding.getName().toUpperCase());
message.append(markup?"</b>":"");
if (BindingKind.STATIC == binding && version != null) {
message.append(" ").append(version);
}
return message.toString();
}
private static String computeVocabSpecificationMessage(Property property, boolean markup) {
Stereotype vocabSpecification = CDAProfileUtil.getAppliedCDAStereotype(
property, ICDAProfileConstants.VOCAB_SPECIFICATION);
StringBuffer message = new StringBuffer();
String codeSystem = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM);
String codeSystemName = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM_NAME);
String codeSystemVersion = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE_SYSTEM_VERSION);
String code = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_CODE);
String displayName = (String) property.getValue(vocabSpecification, ICDAProfileConstants.VOCAB_SPECIFICATION_DISPLAY_NAME);
if (code != null) {
message.append(markup?"<tt>":"");
message.append("/@code");
message.append(markup?"</tt>":"");
message.append(" = \"").append(code).append("\" ");
if (displayName != null) {
message.append(markup?"<i>":"");
message.append(displayName);
message.append(markup?"</i>":"");
}
if (codeSystem !=null || codeSystemName != null) {
message.append(" (CodeSystem:");
if (codeSystem != null) {
message.append(" ").append(codeSystem);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
message.append(" STATIC");
if (codeSystemVersion != null) {
message.append(" ").append(codeSystemVersion);
}
message.append(")");
}
}
//TODO for now, assume it's a value set if no code
else if (codeSystem !=null || codeSystemName != null) {
String keyword = getValidationKeyword(property);
message.append(", which ");
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" be selected from ValueSet");
if (codeSystem != null) {
message.append(" ").append(codeSystem);
}
if (codeSystemName != null) {
message.append(" ").append(codeSystemName);
}
if (codeSystemVersion != null) {
message.append(" STATIC");
message.append(" ").append(codeSystemVersion);
}
else {
message.append(" DYNAMIC");
}
}
return message.toString();
}
public static String computeConformanceMessage(Constraint constraint, boolean markup) {
StringBuffer message = new StringBuffer();
String strucTextBody = null;
String analysisBody = null;
Map<String,String> langBodyMap = new HashMap<String,String>();
ValueSpecification spec = constraint.getSpecification();
if (spec instanceof OpaqueExpression) {
for (int i=0; i<((OpaqueExpression) spec).getLanguages().size(); i++) {
String lang = ((OpaqueExpression) spec).getLanguages().get(i);
String body = ((OpaqueExpression) spec).getBodies().get(i);
if ("StrucText".equals(lang)) {
strucTextBody = body;
}
else if ("Analysis".equals(lang)) {
analysisBody = body;
}
else {
langBodyMap.put(lang, body);
}
}
}
String displayBody = null;
if (strucTextBody != null && strucTextBody.trim().length() > 0) {
//TODO if markup, parse strucTextBody and insert DITA markup
displayBody = strucTextBody;
}
else if (analysisBody != null && analysisBody.trim().length() > 0) {
if (markup) {
// escape non-dita markup in analysis text
displayBody = escapeMarkupCharacters(analysisBody);
// change severity words to bold text
displayBody = replaceSeverityWithBold(displayBody);
}
else {
displayBody = analysisBody;
}
}
if (!markup) {
message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
}
if (displayBody == null || !containsSeverityWord(displayBody)) {
String keyword = getValidationKeyword(constraint);
if (keyword == null) {
keyword = "SHALL";
}
message.append(markup?"<b>":"");
message.append(keyword);
message.append(markup?"</b>":"");
message.append(" satisfy: ");
}
if (displayBody == null) {
message.append(constraint.getName());
}
else {
message.append(displayBody);
}
appendConformanceRuleIds(constraint, message, markup);
// include comment text only in markup output
if (markup && constraint.getOwnedComments().size() > 0) {
message.append("<ul>");
for (Comment comment : constraint.getOwnedComments()) {
message.append("<li>");
message.append(fixNonXMLCharacters(comment.getBody()));
message.append("</li>");
}
message.append("</ul>");
}
// Include other constraint languages, e.g. OCL or XPath
if (markup && langBodyMap.size()>0) {
message.append("<ul>");
for (String lang : langBodyMap.keySet()) {
message.append("<li>");
message.append("<codeblock>[" + lang + "]: ");
message.append(escapeMarkupCharacters(langBodyMap.get(lang)));
message.append("</codeblock>");
message.append("</li>");
}
message.append("</ul>");
}
if (!markup) {
// remove line feeds
int index;
while ((index=message.indexOf("\r")) >=0) {
message.deleteCharAt(index);
}
while ((index=message.indexOf("\n")) >=0) {
message.deleteCharAt(index);
if (message.charAt(index) != ' ') {
message.insert(index, " ");
}
}
}
return message.toString();
}
private static boolean containsSeverityWord(String text) {
return text.indexOf("SHALL") >= 0
|| text.indexOf("SHOULD") >= 0
|| text.indexOf("MAY") >= 0;
}
private static String replaceSeverityWithBold(String input) {
String output;
output = input.replaceAll("SHALL", "<b>SHALL</b>");
output = output.replaceAll("SHOULD", "<b>SHOULD</b>");
output = output.replaceAll("MAY", "<b>MAY</b>");
output = output.replaceAll("\\<b>SHALL\\</b> NOT", "<b>SHALL NOT</b>");
output = output.replaceAll("\\<b>SHOULD\\</b> NOT", "<b>SHOULD NOT</b>");
return output;
}
protected static String computeXref(Element source, Class target) {
String href = null;
if (UMLUtil.isSameModel(source, target)) {
href="../" + target.getName() + ".dita";
}
else if (isCDAModel(target)) {
// no xref to CDA available at this time
}
else {
String pathFolder = "classes";
String basePackage = "";
String prefix = "";
String packageName = target.getNearestPackage().getName();
if (RIMModelUtil.RIM_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.hl7.rim";
}
else if (CDA_PACKAGE_NAME.equals(packageName)) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
else {
basePackage = getModelBasePackage(target);
prefix = getModelNamespacePrefix(target);
}
if (basePackage == null || basePackage.trim().length() == 0) {
basePackage = "org.openhealthtools.mdht.uml.cda";
}
if (prefix != null && prefix.trim().length() > 0) {
prefix += ".";
}
href = INFOCENTER_URL + "/topic/" + basePackage + "."
+ prefix + "doc/" + pathFolder + "/" + target.getName() + ".html";
// pathFolder = "dita/classes";
// href = "../../../../" + basePackage + "."
// + prefix + "doc/" + pathFolder + "/" + target.getName() + ".dita";
}
return href;
}
protected static String computeTerminologyXref(Class source, Enumeration target) {
String href = null;
if (UMLUtil.isSameProject(source, target)) {
href="../../terminology/" + validFileName(target.getName()) + ".dita";
}
return href;
}
public static Property getNavigableEnd(Association association) {
Property navigableEnd = null;
for (Property end : association.getMemberEnds()) {
if (end.isNavigable()) {
if (navigableEnd != null) {
return null; // multiple navigable ends
}
navigableEnd = end;
}
}
return navigableEnd;
}
public static String getCDAElementName(Property property) {
Class cdaSourceClass = getCDAClass(property.getClass_());
Class endType = (property.getType() instanceof Class)
? (Class)property.getType() : null;
Class cdaTargetClass = endType != null ? getCDAClass(endType) : null;
//TODO this is incomplete determination of XML element name
String elementName = property.getName();
if (cdaSourceClass == null) {
elementName = property.getName();
}
else if ("ClinicalDocument".equals(cdaSourceClass.getName())
&& (CDAModelUtil.isSection(cdaTargetClass) || CDAModelUtil.isClinicalStatement(cdaTargetClass))) {
elementName = "component";
}
else if (CDAModelUtil.isSection(cdaSourceClass)
&& (CDAModelUtil.isSection(cdaTargetClass))) {
elementName = "component";
}
else if (CDAModelUtil.isSection(cdaSourceClass)
&& (CDAModelUtil.isClinicalStatement(cdaTargetClass) || CDAModelUtil.isEntry(cdaTargetClass))) {
elementName = "entry";
}
else if (CDAModelUtil.isOrganizer(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "component";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && CDAModelUtil.isClinicalStatement(cdaTargetClass)) {
elementName = "entryRelationship";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && "ParticipantRole".equals(cdaTargetClass.getName())) {
elementName = "participant";
}
else if (CDAModelUtil.isClinicalStatement(cdaSourceClass) && "AssignedEntity".equals(cdaTargetClass.getName())) {
elementName = "performer";
}
return elementName;
}
public static String getMultiplicityString(Property property) {
StringBuffer message = new StringBuffer();
if (property.getLower()==1 && property.getUpper()==1) {
message.append("exactly one");
}
else if (property.getLower()==0 && property.getUpper()==1) {
message.append("zero or one");
}
else if (property.getLower()==0 && property.getUpper()==-1) {
message.append("zero or more");
}
else if (property.getLower()==1 && property.getUpper()==-1) {
message.append("at least one");
}
String lower = Integer.toString(property.getLower());
String upper = property.getUpper()==-1 ? "*" : Integer.toString(property.getUpper());
message.append(" [").append(lower).append("..").append(upper).append("]");
return message.toString();
}
public static boolean isXMLAttribute(Property property) {
Property cdaProperty = getCDAProperty(property);
if (cdaProperty != null) {
Stereotype eAttribute = cdaProperty.getAppliedStereotype("Ecore::EAttribute");
if (eAttribute != null)
return true;
}
return false;
}
public static String getTemplateId(Class template) {
String templateId = null;
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(
template, ICDAProfileConstants.CDA_TEMPLATE);
if (hl7Template != null) {
templateId = (String) template.getValue(hl7Template, ICDAProfileConstants.CDA_TEMPLATE_TEMPLATE_ID);
}
else {
for (Classifier parent : template.getGenerals()) {
templateId = getTemplateId((Class)parent);
if (templateId != null) {
break;
}
}
}
return templateId;
}
public static String getModelPrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_PREFIX);
}
else if (CDA_PACKAGE_NAME.equals(model.getName())) {
prefix = "CDA";
}
else if (RIMModelUtil.RIM_PACKAGE_NAME.equals(model.getName())) {
prefix = "RIM";
}
return prefix;
}
public static String getModelNamespacePrefix(Element element) {
String prefix = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
prefix = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_PREFIX);
}
return prefix;
}
public static String getModelBasePackage(Element element) {
String basePackage = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
basePackage = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_BASE_PACKAGE);
}
return basePackage;
}
public static String getEcorePackageURI(Element element) {
String nsURI = null;
Package model = UMLUtil.getTopPackage(element);
Stereotype codegenSupport = CDAProfileUtil.getAppliedCDAStereotype(model, ICDAProfileConstants.CODEGEN_SUPPORT);
if (codegenSupport != null) {
nsURI = (String) model.getValue(codegenSupport, ICDAProfileConstants.CODEGEN_SUPPORT_NS_URI);
}
if (nsURI == null) {
// for base models without codegenSupport
if (model.getName().equals("cda"))
nsURI = "urn:hl7-org:v3";
else if (model.getName().equals("datatypes"))
nsURI = "http:
else if (model.getName().equals("vocab"))
nsURI = "http:
}
return nsURI;
}
public static String getPrefixedSplitName(NamedElement element) {
StringBuffer buffer = new StringBuffer();
String modelPrefix = getModelPrefix(element);
if (modelPrefix != null) {
buffer.append(modelPrefix).append(" ");
}
buffer.append(UMLUtil.splitName(element));
return buffer.toString();
}
public static boolean hasValidationSupport(Element element) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
return validationSupport != null;
}
public static String getValidationSeverity(Element element) {
String severity = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Object value = element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_SEVERITY);
if (value instanceof EnumerationLiteral) {
severity = ((EnumerationLiteral)value).getName();
}
else if (value instanceof Enumerator) {
severity = ((Enumerator)value).getName();
}
// return (severity != null) ? severity : SEVERITY_ERROR;
}
return severity;
}
public static String getValidationMessage(Element element) {
String message = null;
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
message = (String) element.getValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE);
}
if (message == null || message.length() == 0) {
message = computeConformanceMessage(element, false);
}
return message;
}
/**
* Returns a list conformance rule IDs.
*/
public static List<String> getConformanceRuleIdList(Element element) {
List<String> ruleIds = new ArrayList<String>();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
ruleIds.add(ruleId);
}
}
return ruleIds;
}
protected static void appendConformanceRuleIds(Element element, StringBuffer message, boolean markup) {
String ruleIds = getConformanceRuleIds(element);
if (ruleIds.length() > 0) {
message.append(" (");
message.append(ruleIds);
message.append(")");
}
}
/**
* Returns a comma separated list of conformance rule IDs, or an empty string if no IDs.
*/
public static String getConformanceRuleIds(Element element) {
StringBuffer ruleIdDisplay = new StringBuffer();
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(element, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
Validation validation = (Validation) element.getStereotypeApplication(validationSupport);
for (String ruleId : validation.getRuleId()) {
if (ruleIdDisplay.length() > 0)
ruleIdDisplay.append(", ");
ruleIdDisplay.append(ruleId);
}
}
return ruleIdDisplay.toString();
}
public static String getValidationKeyword(Element element) {
String severity = getValidationSeverity(element);
if (severity != null) {
if (SEVERITY_INFO.equals(severity))
return "MAY";
else if (SEVERITY_WARNING.equals(severity))
return "SHOULD";
else if (SEVERITY_ERROR.equals(severity))
return "SHALL";
}
return null;
// if (element instanceof Association) {
// for (Property end : ((Association)element).getMemberEnds()) {
// if (end.isNavigable()) {
// element = end;
// break;
// if (element instanceof MultiplicityElement) {
// if (((MultiplicityElement)element).getLower() == 0)
// return "MAY";
// else
// return "SHALL";
// else {
// return "SHALL";
}
public static void setValidationMessage(Element constrainedElement, String message) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_MESSAGE, message);
}
}
public static void setValidationRuleId(Element constrainedElement, String ruleId) {
Stereotype validationSupport = CDAProfileUtil.getAppliedCDAStereotype(constrainedElement, ICDAProfileConstants.VALIDATION);
if (validationSupport != null) {
List<String> ruleIds = new ArrayList<String>();
ruleIds.add(ruleId);
constrainedElement.setValue(validationSupport, ICDAProfileConstants.VALIDATION_RULE_ID, ruleIds);
}
}
protected static String getLiteralValue(Element element, Stereotype stereotype, String propertyName) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral)value).getName();
}
else if (value instanceof Enumerator) {
name = ((Enumerator)value).getName();
}
return name;
}
protected static String getLiteralValueLabel(Element element, Stereotype stereotype, String propertyName, Enumeration umlEnumeration) {
Object value = element.getValue(stereotype, propertyName);
String name = null;
if (value instanceof EnumerationLiteral) {
name = ((EnumerationLiteral)value).getLabel();
}
else if (value instanceof Enumerator) {
name = ((Enumerator)value).getName();
if (umlEnumeration != null) {
name = umlEnumeration.getOwnedLiteral(name).getLabel();
}
}
return name;
}
public static String fixNonXMLCharacters(String text) {
if (text == null) {
return null;
}
StringBuffer newText = new StringBuffer();
for (int i=0; i<text.length(); i++) {
// test for unicode characters from copy/paste of MS Word text
if (text.charAt(i) == '\u201D') // right double quote
newText.append("\"");
else if (text.charAt(i) == '\u201C') // left double quote
newText.append("\"");
else if (text.charAt(i) == '\u2019') // right single quote
newText.append("'");
else if (text.charAt(i) == '\u2018') // left single quote
newText.append("'");
// this won't allow markup in comments
// else if (text.charAt(i) == '<')
// newText.append("<");
// else if (text.charAt(i) == '>')
// newText.append(">");
// can't include this or escaped characters don't render, e.g. &
// else if (text.charAt(i) == '&')
// newText.append("&");
else
newText.append(text.charAt(i));
}
return newText.toString();
}
public static String escapeMarkupCharacters(String text) {
if (text == null) {
return null;
}
text = fixNonXMLCharacters(text);
StringBuffer newText = new StringBuffer();
for (int i=0; i<text.length(); i++) {
if (text.charAt(i) == '<')
newText.append("<");
else if (text.charAt(i) == '>')
newText.append(">");
// can't include this or escaped characters don't render, e.g. &
// else if (text.charAt(i) == '&')
// newText.append("&");
else
newText.append(text.charAt(i));
}
return newText.toString();
}
public static String validFileName(String fileName) {
StringBuffer validName = new StringBuffer();
for (int i=0; i<fileName.length(); i++) {
if (fileName.charAt(i) == '/')
validName.append(" ");
else if (fileName.charAt(i) == '\\')
validName.append(" ");
else if (fileName.charAt(i) == '?')
validName.append("");
else
validName.append(fileName.charAt(i));
}
return validName.toString();
}
}
|
package org.eclipse.birt.chart.reportitem.ui;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.birt.chart.aggregate.IAggregateFunction;
import org.eclipse.birt.chart.api.ChartEngine;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.factory.DataRowExpressionEvaluatorAdapter;
import org.eclipse.birt.chart.factory.IDataRowExpressionEvaluator;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.DataType;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.impl.QueryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesGroupingImpl;
import org.eclipse.birt.chart.model.impl.ChartModelHelper;
import org.eclipse.birt.chart.reportitem.AbstractChartBaseQueryGenerator;
import org.eclipse.birt.chart.reportitem.BIRTCubeResultSetEvaluator;
import org.eclipse.birt.chart.reportitem.BaseGroupedQueryResultSetEvaluator;
import org.eclipse.birt.chart.reportitem.ChartBaseQueryHelper;
import org.eclipse.birt.chart.reportitem.ChartCubeQueryHelper;
import org.eclipse.birt.chart.reportitem.ChartReportItemUtil;
import org.eclipse.birt.chart.reportitem.SharedCubeResultSetEvaluator;
import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil;
import org.eclipse.birt.chart.reportitem.api.ChartItemUtil;
import org.eclipse.birt.chart.reportitem.api.ChartReportItemConstants;
import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ColumnBindingInfo;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizard;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionCodec;
import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionSet;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.PluginSettings;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.data.IColumnBinding;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IDataQueryDefinition;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults;
import org.eclipse.birt.data.engine.olap.api.query.IBaseCubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ICubeFilterDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider;
import org.eclipse.birt.report.designer.data.ui.util.DummyEngineTask;
import org.eclipse.birt.report.designer.internal.ui.data.DataService;
import org.eclipse.birt.report.designer.internal.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionUtility;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.ui.IReportClasspathResolver;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.impl.ReportEngine;
import org.eclipse.birt.report.engine.api.impl.ReportEngineFactory;
import org.eclipse.birt.report.engine.api.impl.ReportEngineHelper;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.re.CrosstabQueryUtil;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSetParameterHandle;
import org.eclipse.birt.report.model.api.DesignConfig;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.DesignEngine;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.MultiViewsHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SharedStyleHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.metadata.IPredefinedStyle;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.util.CubeUtil;
import org.eclipse.birt.report.model.elements.interfaces.IExtendedItemModel;
import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel;
import org.eclipse.core.resources.IProject;
import org.eclipse.emf.common.util.EList;
import com.ibm.icu.text.Collator;
import com.ibm.icu.util.ULocale;
/**
* Data service provider of chart builder for BIRT integration.
*/
public class ReportDataServiceProvider implements IDataServiceProvider
{
protected ExtendedItemHandle itemHandle;
protected ChartWizardContext context;
/** The helper handle is used to do things for share binding case. */
private final ShareBindingQueryHelper fShareBindingQueryHelper = new ShareBindingQueryHelper( );
static final String OPTION_NONE = Messages.getString( "ReportDataServiceProvider.Option.None" ); //$NON-NLS-1$
ChartReportItemUIFactory uiFactory = ChartReportItemUIFactory.instance( );
protected DteAdapter dteAdapter = uiFactory.createDteAdapter( );
protected Object sessionLock = new Object( );
/**
* This flag indicates whether the error is found when fetching data. This
* is to help reduce invalid query.
*/
private boolean isErrorFound = false;
private IProject project = null;
// These fields are used to execute query for live preview.
protected DataRequestSession session = null;
private ReportEngine engine = null;
private ChartDummyEngineTask engineTask = null;
private Object dataSetReference = null;
private Map<String, ReportItemHandle> referMap = new HashMap<String, ReportItemHandle>( );
protected final ExpressionCodec exprCodec = ChartModelHelper.instance( )
.createExpressionCodec( );
public ReportDataServiceProvider( ExtendedItemHandle itemHandle )
{
super( );
this.itemHandle = itemHandle;
project = UIUtil.getCurrentProject( );
}
private String[] getDesignWorkspaceClasspath( )
{
IReportClasspathResolver provider = ReportPlugin.getDefault( )
.getReportClasspathResolverService( );
if ( provider != null )
{
String designPath = ( (ReportDesignHandle) itemHandle.getModuleHandle( ) ).getFileName( );
return provider.resolveClasspath( designPath );
}
return null;
}
/**
* Initializes some instance handles for query execution.
*
* @throws ChartException
*/
@SuppressWarnings("unchecked")
public void initialize( ) throws ChartException
{
try
{
if ( isReportDesignHandle( ) )
{
EngineConfig config = new EngineConfig( );
String[] paths = getDesignWorkspaceClasspath( );
if ( paths != null && paths.length > 0 )
{
StringBuffer buffer = new StringBuffer( );
for ( String path : paths )
{
if ( buffer.length( ) > 0 )
{
buffer.append( ';' );
}
buffer.append( path );
}
if ( buffer.length( ) != 0 )
{
HashMap<Object, Object> appContext = config.getAppContext( );
appContext.put( EngineConstants.PROJECT_CLASSPATH_KEY,
buffer.toString( ) );
}
}
engine = (ReportEngine) new ReportEngineFactory( ).createReportEngine( config );
engineTask = new ChartDummyEngineTask( engine,
new ReportEngineHelper( engine ).openReportDesign( (ReportDesignHandle) itemHandle.getModuleHandle( ) ),
itemHandle.getModuleHandle( ) );
session = engineTask.getDataSession( );
engineTask.run( );
dteAdapter.setExecutionContext( engineTask.getExecutionContext( ) );
}
else
{
DataSessionContext dsc = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION,
getReportDesignHandle( ) );
session = DataRequestSession.newSession( dsc );
}
}
catch ( BirtException e )
{
if ( engine == null && session != null )
{
session.shutdown( );
}
if ( engineTask != null )
{
engineTask.close( );
}
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
}
/**
* Disposes instance handles.
*/
public void dispose( )
{
if ( engineTask != null )
{
engineTask.close( );
}
else if ( session != null )
{
session.shutdown( );
}
}
public void setWizardContext( ChartWizardContext context )
{
this.context = context;
}
ModuleHandle getReportDesignHandle( )
{
return itemHandle.getModuleHandle( );
}
@SuppressWarnings("unchecked")
protected String[] getAllDataSets( )
{
List<DataSetHandle> list = getReportDesignHandle( ).getVisibleDataSets( );
String[] names = new String[list.size( )];
for ( int i = 0; i < list.size( ); i++ )
{
names[i] = list.get( i ).getQualifiedName( );
}
return names;
}
@SuppressWarnings("unchecked")
protected String[] getAllDataCubes( )
{
List<CubeHandle> list = getReportDesignHandle( ).getVisibleCubes( );
String[] names = new String[list.size( )];
for ( int i = 0; i < list.size( ); i++ )
{
names[i] = list.get( i ).getQualifiedName( );
}
return names;
}
/**
* Gets data cube from chart itself
*
* @return data cube name
*/
String getDataCube( )
{
CubeHandle cube = itemHandle.getCube( );
if ( cube == null )
{
return null;
}
return cube.getQualifiedName( );
}
/**
* Gets data cube from chart container
*
* @return data cube name
*/
String getInheritedCube( )
{
CubeHandle cube = null;
DesignElementHandle container = itemHandle.getContainer( );
while ( container != null )
{
if ( container instanceof ReportItemHandle )
{
cube = ( (ReportItemHandle) container ).getCube( );
if ( cube != null )
{
break;
}
}
container = container.getContainer( );
}
if ( cube == null )
{
return null;
}
return cube.getQualifiedName( );
}
void setDataCube( String cubeName )
{
try
{
// Clean references if it's set
boolean isPreviousDataBindingReference = false;
if ( itemHandle.getDataBindingType( ) == ReportItemHandle.DATABINDING_TYPE_REPORT_ITEM_REF )
{
isPreviousDataBindingReference = true;
itemHandle.setDataBindingReference( null );
}
itemHandle.setDataSet( null );
if ( cubeName == null )
{
itemHandle.setCube( null );
// Clear parameters and filters, binding if dataset changed
clearBindings( );
}
else
{
if ( !cubeName.equals( getDataCube( ) )
|| isPreviousDataBindingReference )
{
CubeHandle cubeHandle = getReportDesignHandle( ).findCube( cubeName );
itemHandle.setCube( cubeHandle );
// Clear parameters and filters, binding if dataset changed
clearBindings( );
generateBindings( ChartXTabUIUtil.generateComputedColumns( itemHandle,
cubeHandle ) );
}
}
ChartWizard.removeException( ChartWizard.RepDSProvider_Cube_ID );
}
catch ( SemanticException e )
{
ChartWizard.showException( ChartWizard.RepDSProvider_Cube_ID,
e.getLocalizedMessage( ) );
}
}
public final String[] getPreviewHeader( )
{
Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle );
List<String> list = new ArrayList<String>( );
boolean bInheritColumnsOnly = isInheritColumnsOnly( );
while ( iterator.hasNext( ) )
{
ComputedColumnHandle binding = iterator.next( );
// Remove the aggregation bindings if "inherit columns" used.
if ( bInheritColumnsOnly && binding.getAggregateFunction( ) != null )
{
continue;
}
list.add( ( binding ).getName( ) );
}
return list.toArray( new String[list.size( )] );
}
public final List<Object[]> getPreviewData( ) throws ChartException
{
synchronized ( sessionLock )
{
if ( engineTask != null )
{
try
{
engineTask.run( );
}
catch ( EngineException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
}
List<Object[]> values = null;
if ( isSharedBinding( ) || isInheritColumnsGroups( ) )
{
values = fShareBindingQueryHelper.getPreviewRowData( getPreviewHeadersInfo( ),
-1,
true );
}
else
{
values = getPreviewRowData( getPreviewHeader( false ), -1, true );
}
dataSetReference = ChartItemUtil.getBindingDataSet( itemHandle );
return values;
}
}
private void removeIndirectRefOfAggregates(
List<ComputedColumnHandle> list,
Map<String, ComputedColumnHandle> bindingMap ) throws BirtException
{
for ( Iterator<ComputedColumnHandle> iter = list.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
if ( !isCommonBinding( cch, bindingMap ) )
{
iter.remove( );
continue;
}
}
}
/**
* Checks if specified column binding is a common binding,excluding
* aggregation binding.
*
* @param cch
* @param bindingMap
* @return
* @throws BirtException
*/
@SuppressWarnings("unchecked")
private boolean isCommonBinding( ComputedColumnHandle cch,
Map<String, ComputedColumnHandle> bindingMap ) throws BirtException
{
ScriptExpression se = ChartReportItemUtil.newExpression( session.getModelAdaptor( ),
cch );
List<IColumnBinding> bindings = ExpressionUtil.extractColumnExpressions( se.getText( ),
ExpressionUtil.ROW_INDICATOR );
for ( int i = 0; i < bindings.size( ); i++ )
{
ComputedColumnHandle refCch = bindingMap.get( bindings.get( i )
.getResultSetColumnName( ) );
if ( refCch.getAggregateFunction( ) != null )
{
return false;
}
else if ( refCch.getExpression( ) != null
&& !isCommonBinding( refCch, bindingMap ) )
{
return false;
}
}
return true;
}
/**
* Returns columns header info.
*
* @throws ChartException
* @since BIRT 2.3
*/
public final ColumnBindingInfo[] getPreviewHeadersInfo( )
throws ChartException
{
Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle );
if ( iterator == null )
{
return new ColumnBindingInfo[]{};
}
Map<String, ComputedColumnHandle> bindingMap = new HashMap<String, ComputedColumnHandle>( );
List<ComputedColumnHandle> columnList = new ArrayList<ComputedColumnHandle>( );
boolean bInheritColumnsOnly = isInheritColumnsOnly( );
while ( iterator.hasNext( ) )
{
ComputedColumnHandle binding = iterator.next( );
bindingMap.put( binding.getName( ), binding );
// Remove the aggregation bindings if "inherit columns" used.
if ( bInheritColumnsOnly && binding.getAggregateFunction( ) != null )
{
continue;
}
columnList.add( binding );
}
// Remove indirect reference of aggregation bindings.
try
{
if ( bInheritColumnsOnly )
{
removeIndirectRefOfAggregates( columnList, bindingMap );
}
}
catch ( BirtException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
if ( columnList.size( ) == 0 )
{
return new ColumnBindingInfo[]{};
}
ColumnBindingInfo[] columnHeaders = null;
if ( isTableSharedBinding( ) || isInheritColumnsGroups( ) )
{
columnHeaders = fShareBindingQueryHelper.getPreviewHeadersInfo( columnList );
}
else
{
columnHeaders = new ColumnBindingInfo[columnList.size( )];
for ( int i = 0; i < columnHeaders.length; i++ )
{
ComputedColumnHandle cch = columnList.get( i );
columnHeaders[i] = new ColumnBindingInfo( cch.getName( ),
ExpressionUtil.createJSRowExpression( cch.getName( ) ),
null,
null,
cch );
}
}
// Sort columns.
List<ColumnBindingInfo> columnsSet = new ArrayList<ColumnBindingInfo>( );
for ( int i = columnHeaders.length - 1; i >= 0; i
columnsSet.add( columnHeaders[i] );
Collections.sort( columnsSet, new ColumnNameComprator( ) );
columnHeaders = columnsSet.toArray( new ColumnBindingInfo[]{} );
return columnHeaders;
}
static class ColumnNameComprator implements
Comparator<ColumnBindingInfo>,
Serializable
{
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
// use JDK String's compare method to map the same sorting logic as
// column binding dialog(270079)
// private com.ibm.icu.text.Collator collator =
// com.ibm.icu.text.Collator.getInstance( );
public int compare( ColumnBindingInfo src, ColumnBindingInfo target )
{
return src.getName( ).compareTo( target.getName( ) );
}
}
private String[] getPreviewHeader( boolean isExpression )
throws ChartException
{
ColumnBindingInfo[] cbis = getPreviewHeadersInfo( );
String[] exps = new String[cbis.length];
int i = 0;
for ( ColumnBindingInfo cbi : cbis )
{
if ( isExpression )
{
exps[i] = ExpressionUtil.createJSRowExpression( cbi.getName( ) );
}
else
{
exps[i] = cbi.getName( );
}
i++;
}
return exps;
}
protected final List<Object[]> getPreviewRowData( String[] bindingNames,
int rowCount, boolean isStringType ) throws ChartException
{
List<Object[]> dataList = new ArrayList<Object[]>( );
// Set thread context class loader so Rhino can find POJOs in workspace
// projects
ClassLoader oldContextLoader = Thread.currentThread( )
.getContextClassLoader( );
ClassLoader parentLoader = oldContextLoader;
if ( parentLoader == null )
parentLoader = this.getClass( ).getClassLoader( );
ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader,
itemHandle.getModuleHandle( ) );
Thread.currentThread( ).setContextClassLoader( newContextLoader );
try
{
QueryDefinition queryDefn = new QueryDefinition( );
queryDefn.setMaxRows( getMaxRow( ) );
queryDefn.setDataSetName( getDataSetFromHandle( ).getQualifiedName( ) );
setQueryDefinitionWithDataSet( itemHandle, queryDefn );
IQueryResults actualResultSet = executeDataSetQuery( queryDefn );
if ( actualResultSet != null )
{
String[] expressions = bindingNames;
int columnCount = expressions.length;
IResultIterator iter = actualResultSet.getResultIterator( );
while ( iter.next( ) )
{
if ( isStringType )
{
String[] record = new String[columnCount];
for ( int n = 0; n < columnCount; n++ )
{
// Bugzilla#190229, to get string with localized
// format
record[n] = valueAsString( iter.getValue( expressions[n] ) );
}
dataList.add( record );
}
else
{
Object[] record = new Object[columnCount];
for ( int n = 0; n < columnCount; n++ )
{
record[n] = iter.getValue( expressions[n] );
}
dataList.add( record );
}
}
actualResultSet.close( );
}
}
catch ( BirtException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
finally
{
// Restore old thread context class loader
Thread.currentThread( ).setContextClassLoader( oldContextLoader );
}
return dataList;
}
/**
* @param source
* @return
* @throws NumberFormatException
* @throws BirtException
*/
private String valueAsString( Object source ) throws NumberFormatException,
BirtException
{
if ( source == null )
return null;
if ( source instanceof Number )
{
ULocale locale = ULocale.getDefault( );
String value = source.toString( );
int index = value.indexOf( 'E' );
// It means the value is very larger, using E marked.
if ( index >= 0 )
{
String returnValue = DataTypeUtil.toString( Double.valueOf( value.substring( 0,
index ) ),
locale )
+ "E"; //$NON-NLS-1$
String exponent = value.substring( index + 1 );
if ( exponent.matches( "[\\+-]+[1-9]{1}[0-9]*" ) ) //$NON-NLS-1$
{
returnValue += exponent.substring( 0, 1 )
+ DataTypeUtil.toString( Integer.valueOf( exponent.substring( 1 ) ),
locale );
}
else
{
returnValue += DataTypeUtil.toString( Integer.valueOf( exponent ),
locale );
}
return returnValue;
}
}
return DataTypeUtil.toString( source );
}
private boolean isReportDesignHandle( )
{
return itemHandle.getModuleHandle( ) instanceof ReportDesignHandle;
}
/**
* Add group definitions into query definition.
*
* @param queryDefn
* query definition.
* @param reportItemHandle
* the item handle contains groups.
*/
@SuppressWarnings({
"unchecked"
})
private void handleGroup( QueryDefinition queryDefn,
ExtendedItemHandle reportItemHandle, IModelAdapter modelAdapter )
{
ReportItemHandle handle = ChartReportItemUtil.getBindingHolder( reportItemHandle );
if ( handle instanceof ListingHandle )
{
SlotHandle groups = ( (ListingHandle) handle ).getGroups( );
for ( Iterator<GroupHandle> iter = groups.iterator( ); iter.hasNext( ); )
{
ChartBaseQueryHelper.handleGroup( iter.next( ),
queryDefn,
modelAdapter );
}
}
}
/**
* Check if current parameters is explicit value in chart builder, otherwise
* default value of parameters will be used to get preview data.
*
* @param dataSetHandle
* current dataset handle.
* @param queryDefn
* query definition.
* @return query definition.
*/
@SuppressWarnings("unchecked")
private QueryDefinition resetParametersForDataPreview(
DataSetHandle dataSetHandle, QueryDefinition queryDefn )
{
// 1. Get parameters description from dataset.
Map<String, DataSetParameterHandle> dsphMap = new LinkedHashMap<String, DataSetParameterHandle>( );
if ( dataSetHandle != null )
{
Iterator<DataSetParameterHandle> iterParams = dataSetHandle.parametersIterator( );
while ( iterParams.hasNext( ) )
{
DataSetParameterHandle dsph = iterParams.next( );
dsphMap.put( dsph.getName( ), dsph );
}
}
// 2. Get parameters setting from current handle.
Iterator<ParamBindingHandle> iterParams = itemHandle.getPropertyHandle( ReportItemHandle.PARAM_BINDINGS_PROP )
.iterator( );
Map<String, ParamBindingHandle> pbhMap = new LinkedHashMap<String, ParamBindingHandle>( );
while ( iterParams.hasNext( ) )
{
ParamBindingHandle paramBindingHandle = iterParams.next( );
pbhMap.put( paramBindingHandle.getParamName( ), paramBindingHandle );
}
// 3. Check and reset parameters expression.
Object[] names = pbhMap.keySet( ).toArray( );
for ( int i = 0; i < names.length; i++ )
{
DataSetParameterHandle dsph = dsphMap.get( names[i] );
ScriptExpression se = null;
String expr = pbhMap.get( names[i] ).getExpression( );
// The parameters must be a explicit value, the 'row[]' and
// 'row.' expressions only be converted to a explicit value
// under runtime case. So use default value of parameter to get
// data in Chart Builder.
if ( dsph.getDefaultValue( ) != null
&& ( expr == null || expr.indexOf( "row[" ) >= 0 || expr.indexOf( "row." ) >= 0 ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
se = new ScriptExpression( dsph.getDefaultValue( ) );
}
else
{
se = new ScriptExpression( expr );
}
InputParameterBinding ipb = new InputParameterBinding( (String) names[i],
se );
queryDefn.addInputParamBinding( ipb );
}
return queryDefn;
}
/**
* Gets data set from chart itself
*
* @return data set name
*/
String getDataSet( )
{
if ( itemHandle.getDataSet( ) == null )
{
return null;
}
return itemHandle.getDataSet( ).getQualifiedName( );
}
/**
* Checks if only inheritance allowed.
*
*/
boolean isInheritanceOnly( )
{
if ( isInXTabCell( ) || isInMultiView( ) || isInXTabMeasureCell( ) )
{
return true;
}
return false;
}
/**
* Check whether an inherited data cube is used.
*
* @return
* @since 2.5.3
*/
boolean isInheritCube( )
{
return getDataSet( ) == null
&& getDataCube( ) == null
&& checkState( IDataServiceProvider.INHERIT_CUBE );
}
/**
* Check if chart is in multiple view.
*
* @return
* @since 2.3
*/
boolean isInMultiView( )
{
return itemHandle.getContainer( ) instanceof MultiViewsHandle;
}
/**
* Gets data set from chart container
*
* @return data set name
*/
@SuppressWarnings("unchecked")
String getInheritedDataSet( )
{
List<DataSetHandle> list = DEUtil.getDataSetList( itemHandle.getContainer( ) );
if ( list.size( ) > 0 )
{
return list.get( 0 ).getQualifiedName( );
}
return null;
}
public void setDataSet( String datasetName )
{
try
{
// Clean references if it's set
boolean isPreviousDataBindingReference = false;
if ( itemHandle.getDataBindingType( ) == ReportItemHandle.DATABINDING_TYPE_REPORT_ITEM_REF )
{
isPreviousDataBindingReference = true;
itemHandle.setDataBindingReference( null );
}
itemHandle.setCube( null );
if ( datasetName == null )
{
if ( getDataSet( ) != null )
{
// Clean old bindings and use container's binding
clearBindings( );
}
itemHandle.setDataSet( null );
}
else
{
DataSetHandle dataset = getReportDesignHandle( ).findDataSet( datasetName );
if ( isPreviousDataBindingReference
|| itemHandle.getDataSet( ) != dataset )
{
itemHandle.setDataSet( dataset );
// Clean old bindings and add new bindings
clearBindings( );
generateBindings( generateComputedColumns( dataset ) );
// enable default category grouping
List<SeriesDefinition> sds = ChartUIUtil.getBaseSeriesDefinitions( context.getModel( ) );
if ( sds != null && sds.size( ) > 0 )
{
SeriesDefinition base = sds.get( 0 );
if ( !ChartUIConstants.TYPE_GANTT.equals( context.getModel( )
.getType( ) ) )
{
if ( base.getGrouping( ) == null )
{
base.setGrouping( SeriesGroupingImpl.create( ) );
}
base.getGrouping( ).setEnabled( true );
}
}
}
}
ChartWizard.removeException( ChartWizard.RepDSProvider_Set_ID );
}
catch ( SemanticException e )
{
ChartWizard.showException( ChartWizard.RepDSProvider_Set_ID,
e.getLocalizedMessage( ) );
}
}
private void clearBindings( ) throws SemanticException
{
clearProperty( itemHandle.getPropertyHandle( ReportItemHandle.PARAM_BINDINGS_PROP ) );
clearProperty( itemHandle.getPropertyHandle( ExtendedItemHandle.FILTER_PROP ) );
clearProperty( itemHandle.getColumnBindings( ) );
}
private void clearProperty( PropertyHandle property )
throws SemanticException
{
if ( property != null )
{
property.clearValue( );
}
}
private Iterator<?> getPropertyIterator( PropertyHandle property )
{
if ( property != null )
{
return property.iterator( );
}
return null;
}
private void generateBindings( List<ComputedColumn> columnList )
throws SemanticException
{
if ( columnList.size( ) > 0 )
{
for ( Iterator<ComputedColumn> iter = columnList.iterator( ); iter.hasNext( ); )
{
DEUtil.addColumn( itemHandle, iter.next( ), false );
}
}
}
/**
* Generate computed columns for the given report item with the closest data
* set available.
*
* @param dataSetHandle
* Data Set. No aggregation created.
*
* @return true if succeed,or fail if no column generated.
* @see DataUtil#generateComputedColumns(ReportItemHandle)
*
*/
@SuppressWarnings("unchecked")
private List<ComputedColumn> generateComputedColumns(
DataSetHandle dataSetHandle ) throws SemanticException
{
if ( dataSetHandle != null )
{
List<ResultSetColumnHandle> resultSetColumnList = DataUtil.getColumnList( dataSetHandle );
List<ComputedColumn> columnList = new ArrayList<ComputedColumn>( );
for ( ResultSetColumnHandle resultSetColumn : resultSetColumnList )
{
ComputedColumn column = StructureFactory.newComputedColumn( itemHandle,
resultSetColumn.getColumnName( ) );
column.setDataType( resultSetColumn.getDataType( ) );
ExpressionUtility.setBindingColumnExpression( resultSetColumn,
column );
columnList.add( column );
}
return columnList;
}
return Collections.emptyList( );
}
/**
* Gets dataset from ReportItemHandle at first. If null, get dataset from
* its container.
*
* @return direct dataset
*/
@SuppressWarnings("unchecked")
protected DataSetHandle getDataSetFromHandle( )
{
if ( itemHandle.getDataSet( ) != null )
{
return itemHandle.getDataSet( );
}
List<DataSetHandle> datasetList = DEUtil.getDataSetList( itemHandle.getContainer( ) );
if ( datasetList.size( ) > 0 )
{
return datasetList.get( 0 );
}
return null;
}
/**
* The method is designed for overriding purpose. Subclasses can do some
* additional processing on the QueryDefinition here (e.g. add sorts or
* filters), before that it is going to be executed.
*
* @param queryDefn
*/
protected void processQueryDefinition( QueryDefinition queryDefn )
{
// nothing to do here.
}
@SuppressWarnings("unchecked")
private StyleHandle[] getAllStyleHandles( )
{
List<StyleHandle> sLst = getReportDesignHandle( ).getAllStyles( );
StyleHandle[] list = sLst.toArray( new StyleHandle[sLst.size( )] );
Arrays.sort( list, new Comparator<StyleHandle>( ) {
Collator collator = Collator.getInstance( ULocale.getDefault( ) );
public int compare( StyleHandle s1, StyleHandle s2 )
{
return collator.compare( s1.getDisplayLabel( ),
s2.getDisplayLabel( ) );
}
} );
return list;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.interfaces.IDataServiceProvider#getAllStyles()
*/
public String[] getAllStyles( )
{
StyleHandle[] handles = getAllStyleHandles( );
String[] names = new String[handles.length];
for ( int i = 0; i < names.length; i++ )
{
names[i] = handles[i].getQualifiedName( );
}
// Filter predefined styles to make its logic same with report design
// side.
names = filterPreStyles( names );
return names;
}
/**
* Filter predefined styles.
*
* @param items
* all available styles
* @return filtered styles.
*/
private String[] filterPreStyles( String items[] )
{
String[] newItems = items;
if ( items == null )
{
newItems = new String[]{};
}
List<IPredefinedStyle> preStyles = new DesignEngine( new DesignConfig( ) ).getMetaData( )
.getPredefinedStyles( );
List<String> preStyleNames = new ArrayList<String>( );
for ( int i = 0; i < preStyles.size( ); i++ )
{
preStyleNames.add( preStyles.get( i ).getName( ) );
}
List<String> sytleNames = new ArrayList<String>( );
for ( int i = 0; i < newItems.length; i++ )
{
if ( preStyleNames.indexOf( newItems[i] ) == -1 )
{
sytleNames.add( newItems[i] );
}
}
return sytleNames.toArray( new String[]{} );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#
* getAllStyleDisplayNames()
*/
public String[] getAllStyleDisplayNames( )
{
List<String> styles = Arrays.asList( getAllStyles( ) );
StyleHandle[] handles = getAllStyleHandles( );
String[] names = new String[styles.size( )];
for ( int i = 0, j = 0; i < handles.length; i++ )
{
// Remove predefined styles to make its logic same with report
// design side.
if ( styles.contains( handles[i].getQualifiedName( ) ) )
{
names[j++] = handles[i].getDisplayLabel( );
}
}
return names;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.interfaces.IDataServiceProvider#getCurrentStyle
* ()
*/
public String getCurrentStyle( )
{
if ( itemHandle.getStyle( ) == null )
{
return null;
}
return itemHandle.getStyle( ).getQualifiedName( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.interfaces.IDataServiceProvider#setStyle(java
* .lang.String)
*/
public void setStyle( String styleName )
{
try
{
if ( styleName == null )
{
itemHandle.setStyle( null );
}
else
{
itemHandle.setStyle( getStyle( styleName ) );
}
ChartWizard.removeException( ChartWizard.RepDSProvider_Style_ID );
}
catch ( SemanticException e )
{
ChartWizard.showException( ChartWizard.RepDSProvider_Style_ID,
e.getLocalizedMessage( ) );
}
}
private SharedStyleHandle getStyle( String styleName )
{
return getReportDesignHandle( ).findStyle( styleName );
}
/**
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#getDataForColumns(java.lang.String[],
* int, boolean)
* @deprecated since BIRT 2.3, the method is not used for chart live
* preview, use
* {@link #prepareRowExpressionEvaluator(Chart, List, int, boolean)}
* instead.
*
*/
@SuppressWarnings("dep-ann")
public final Object[] getDataForColumns( String[] sExpressions,
int iMaxRecords, boolean byRow ) throws ChartException
{
return null;
}
protected int getMaxRow( )
{
return PreferenceFactory.getInstance( )
.getPreferences( ChartReportItemUIActivator.getDefault( ),
project )
.getInt( ChartReportItemUIActivator.PREFERENCE_MAX_ROW );
}
public boolean isLivePreviewEnabled( )
{
return !isErrorFound
&& PreferenceFactory.getInstance( )
.getPreferences( ChartReportItemUIActivator.getDefault( ),
project )
.getBoolean( ChartReportItemUIActivator.PREFERENCE_ENALBE_LIVE )
&& ChartReportItemUtil.getBindingHolder( itemHandle ) != null;
}
boolean isInvokingSupported( )
{
// If report item reference is set, all operations, including filters,
// parameter bindings and column bindings are not supported
if ( isSharedBinding( ) || isInMultiView( ) )
{
return false;
}
ReportItemHandle container = DEUtil.getBindingHolder( itemHandle );
if ( container != null )
{
// To check container's report item reference
return container.getDataBindingReference( ) == null;
}
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#getDataType
* (java.lang.String)
*/
public DataType getDataType( String expression )
{
return ChartItemUtil.getExpressionDataType( expression, itemHandle );
}
@SuppressWarnings("unchecked")
protected String[] getAllReportItemReferences( )
{
List<ReportItemHandle> availableList = itemHandle.getAvailableDataBindingReferenceList( );
List<ReportItemHandle> referenceList = new ArrayList<ReportItemHandle>( );
for ( ReportItemHandle handle : availableList )
{
if ( handle instanceof ExtendedItemHandle )
{
String extensionName = ( (ExtendedItemHandle) handle ).getExtensionName( );
if ( !isAvailableExtensionToReferenceDataBinding( extensionName ) )
{
continue;
}
}
referenceList.add( handle );
}
return getAllReportItemReferences( referenceList );
}
/**
* Returns if reference binding can accept this type of extended item
*
* @param extensionName
* extension name of item
* @return true means reference binding can accept this type of extended
* item
* @since 3.7
*/
protected boolean isAvailableExtensionToReferenceDataBinding(
String extensionName )
{
return ChartReportItemConstants.CHART_EXTENSION_NAME.equals( extensionName )
|| ICrosstabConstants.CROSSTAB_EXTENSION_NAME.equals( extensionName );
}
private String[] getAllReportItemReferences(
List<ReportItemHandle> referenceList )
{
referMap.clear( );
if ( referenceList.isEmpty( ) )
{
return new String[0];
}
String[] references = new String[referenceList.size( )];
int i = 0;
for ( ReportItemHandle item : referenceList )
{
if ( item.getName( ) != null )
{
references[i] = item.getQualifiedName( );
referMap.put( references[i], item );
i++;
}
}
int tmp = i;
Arrays.sort( references, 0, tmp );
for ( ReportItemHandle item : referenceList )
{
if ( item.getName( ) == null )
{
references[i++] = item.getElement( )
.getDefn( )
.getDisplayName( )
+ " (ID " //$NON-NLS-1$
+ item.getID( )
+ ") - " //$NON-NLS-1$
+ org.eclipse.birt.report.designer.nls.Messages.getString( "BindingPage.ReportItem.NoName" ); //$NON-NLS-1$
}
}
Arrays.sort( references, tmp, referenceList.size( ) );
return references;
}
protected boolean isNoNameItem( String name )
{
ReportItemHandle item = referMap.get( name );
return item == null || item.getName( ) == null;
}
String getReportItemReference( )
{
ReportItemHandle ref = itemHandle.getDataBindingReference( );
if ( ref == null )
{
return null;
}
return ref.getQualifiedName( );
}
void setReportItemReference( String referenceName )
{
try
{
if ( referenceName == null )
{
itemHandle.setDataBindingReference( null );
// Select the corresponding data set, no need to reset bindings
}
else
{
itemHandle.setDataSet( null );
itemHandle.setCube( null );
if ( !referenceName.equals( getReportItemReference( ) ) )
{
// Change reference and reset all bindings
itemHandle.setDataBindingReference( (ReportItemHandle) getReportDesignHandle( ).findElement( referenceName ) );
// //Model will reset bindings
// clearBindings( );
// generateBindings( );
}
}
ChartWizard.removeException( ChartWizard.RepDSProvider_Ref_ID );
}
catch ( SemanticException e )
{
ChartWizard.showException( ChartWizard.RepDSProvider_Ref_ID,
e.getLocalizedMessage( ) );
}
}
/**
* Sets row limit to specified dte's session.
*
* @param session
* @param rowLimit
* @param isCubeMode
*/
protected void setRowLimit( DataRequestSession session, int rowLimit,
boolean isCubeMode )
{
// Bugzilla #210225.
// If filter is set on report item handle of chart, here should not use
// data cache mode and get all valid data firstly, then set row limit on
// query(QueryDefinition.setMaxRows) to get required rows.
PropertyHandle filterProperty = itemHandle.getPropertyHandle( IExtendedItemModel.FILTER_PROP );
if ( filterProperty == null
|| filterProperty.getListValue( ) == null
|| filterProperty.getListValue( ).size( ) == 0 )
{
dteAdapter.setRowLimit( session, rowLimit, isCubeMode );
}
else
{
// Needs to clear previous settings if filter is set.
dteAdapter.setRowLimit( session, -1, isCubeMode );
}
}
/**
* Check it should set cube into query session.
*
* @param cube
* @return
*/
protected boolean needDefineCube( CubeHandle cube )
{
return dataSetReference != cube;
}
private boolean needDefineDataSet( DataSetHandle dataSetHandle )
{
return dataSetReference != dataSetHandle;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#
* prepareRowExpressionEvaluator(org.eclipse.birt.chart.model.Chart,
* java.lang.String[], int, boolean)
*/
public IDataRowExpressionEvaluator prepareRowExpressionEvaluator( Chart cm,
List<String> columnExpression, int rowCount, boolean isStringType )
throws ChartException
{
synchronized ( sessionLock )
{
if ( engineTask != null )
{
try
{
engineTask.run( );
}
catch ( EngineException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
}
// Set thread context class loader so Rhino can find POJOs in
// workspace
// projects
ClassLoader oldContextLoader = Thread.currentThread( )
.getContextClassLoader( );
ClassLoader parentLoader = oldContextLoader;
if ( parentLoader == null )
parentLoader = this.getClass( ).getClassLoader( );
ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader,
itemHandle.getModuleHandle( ) );
Thread.currentThread( ).setContextClassLoader( newContextLoader );
IDataRowExpressionEvaluator evaluator = null;
try
{
CubeHandle cube = ChartCubeUtil.getBindingCube( itemHandle );
if ( cube != null )
{
// Create evaluator for data cube, even if in multiple view
evaluator = createCubeEvaluator( cube, cm, columnExpression );
dataSetReference = cube;
}
else
{
// Create evaluator for data set
if ( isSharedBinding( )
&& !ChartReportItemUtil.isOldChartUsingInternalGroup( itemHandle,
cm )
|| isInheritColumnsGroups( ) )
{
if ( isSharingChart( true ) )
{
evaluator = createBaseEvaluator( (ExtendedItemHandle) ChartReportItemUtil.getReportItemReference( itemHandle ),
cm,
columnExpression );
}
else
{
evaluator = fShareBindingQueryHelper.createShareBindingEvaluator( cm,
columnExpression );
}
}
else
{
evaluator = createBaseEvaluator( itemHandle,
cm,
columnExpression );
}
dataSetReference = ChartItemUtil.getBindingDataSet( itemHandle );
}
return evaluator;
}
catch ( BirtException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
catch ( RuntimeException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
finally
{
// Restore old thread context class loader
Thread.currentThread( )
.setContextClassLoader( oldContextLoader );
}
}
}
/**
* Create base evaluator for chart using data set.
*
* @param handle
* @param cm
* @param columnExpression
* @return
* @throws ChartException
*/
private IDataRowExpressionEvaluator createBaseEvaluator(
ExtendedItemHandle handle, Chart cm, List<String> columnExpression )
throws ChartException
{
IQueryResults actualResultSet;
BaseQueryHelper cbqh = new BaseQueryHelper( handle, cm );
QueryDefinition queryDefn = (QueryDefinition) cbqh.createBaseQuery( columnExpression );
try
{
setQueryDefinitionWithDataSet( handle, queryDefn );
processQueryDefinition( queryDefn );
actualResultSet = executeDataSetQuery( queryDefn );
if ( actualResultSet != null )
{
if ( ChartReportItemUtil.isOldChartUsingInternalGroup( itemHandle,
cm ) )
{
return createSimpleExpressionEvaluator( actualResultSet );
}
else
{
return new BaseGroupedQueryResultSetEvaluator( actualResultSet.getResultIterator( ),
ChartReportItemUtil.isSetSummaryAggregation( cm ),
cm,
itemHandle );
}
}
}
catch ( BirtException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
return null;
}
/**
* @param queryDefn
* @return
* @throws AdapterException
* @throws BirtException
*/
private IQueryResults executeDataSetQuery( QueryDefinition queryDefn )
throws AdapterException, BirtException
{
IQueryResults actualResultSet;
DataSetHandle dataSetHandle = ChartItemUtil.getBindingDataSet( itemHandle );
if ( needDefineDataSet( dataSetHandle ) )
{
DataService.getInstance( ).registerSession( dataSetHandle, session );
dteAdapter.defineDataSet( dataSetHandle, session, true, false );
}
setRowLimit( session, getMaxRow( ), false );
actualResultSet = dteAdapter.executeQuery( session, queryDefn );
return actualResultSet;
}
/**
* @param handle
* @param queryDefn
* @throws AdapterException
* @throws DataException
*/
private void setQueryDefinitionWithDataSet( ExtendedItemHandle handle,
QueryDefinition queryDefn ) throws AdapterException, DataException
{
// Iterate parameter bindings to check if its expression is a
// explicit
// value, otherwise use default value of parameter as its
// expression.
resetParametersForDataPreview( getDataSetFromHandle( ), queryDefn );
// Add bindings and filters from report handle.
Iterator<?> bindingIt = ChartReportItemUtil.getColumnDataBindings( handle,
true );
while ( bindingIt != null && bindingIt.hasNext( ) )
{
Object computedBinding = bindingIt.next( );
IBinding binding = session.getModelAdaptor( )
.adaptBinding( (ComputedColumnHandle) computedBinding );
if ( binding == null
|| queryDefn.getBindings( )
.containsKey( binding.getBindingName( ) ) )
{
continue;
}
queryDefn.addBinding( binding );
}
Iterator<FilterConditionHandle> filtersIterator = getFiltersIterator( );
if ( filtersIterator != null )
{
while ( filtersIterator.hasNext( ) )
{
IFilterDefinition filter = session.getModelAdaptor( )
.adaptFilter( filtersIterator.next( ) );
queryDefn.addFilter( filter );
}
}
handleGroup( queryDefn, handle, session.getModelAdaptor( ) );
}
/**
* Create a simple expression evaluator, it will causes chart engine using
* default grouping instead of DTE's grouping.
*
* @param actualResultSet
* @return
* @throws BirtException
*/
private IDataRowExpressionEvaluator createSimpleExpressionEvaluator(
IQueryResults actualResultSet ) throws BirtException
{
final IResultIterator resultIterator = actualResultSet.getResultIterator( );
return new DataRowExpressionEvaluatorAdapter( ) {
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.chart.factory. IDataRowExpressionEvaluator
* #evaluate(java.lang.String)
*/
public Object evaluate( String expression )
{
try
{
return resultIterator.getValue( expression );
}
catch ( BirtException e )
{
return null;
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.chart.factory. IDataRowExpressionEvaluator
* #evaluateGlobal(java.lang.String)
*/
public Object evaluateGlobal( String expression )
{
return evaluate( expression );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.chart.factory.
* IDataRowExpressionEvaluator#next()
*/
public boolean next( )
{
try
{
return resultIterator.next( );
}
catch ( BirtException e )
{
return false;
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.chart.factory.
* IDataRowExpressionEvaluator#close()
*/
public void close( )
{
try
{
resultIterator.close( );
}
catch ( BirtException e )
{
return;
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.chart.factory.
* IDataRowExpressionEvaluator#first()
*/
public boolean first( )
{
try
{
return resultIterator.next( );
}
catch ( BirtException e )
{
return false;
}
}
};
}
/**
* Returns iterator of all filters.
*
* @return
*/
@SuppressWarnings("unchecked")
private Iterator<FilterConditionHandle> getFiltersIterator( )
{
List<FilterConditionHandle> filterList = new ArrayList<FilterConditionHandle>( );
PropertyHandle ph = null;
// Inherit case.
if ( getDataSet( ) == null && getReportItemReference( ) == null )
{
// Get filters on container.
ReportItemHandle bindingHolder = ChartReportItemUtil.getBindingHolder( itemHandle );
ph = bindingHolder == null ? null
: bindingHolder.getPropertyHandle( IExtendedItemModel.FILTER_PROP );
if ( ph != null )
{
Iterator<FilterConditionHandle> filterIterator = ph.iterator( );
if ( filterIterator != null )
{
while ( filterIterator.hasNext( ) )
{
// Design time doesn't support parent query expressions
FilterConditionHandle filter = filterIterator.next( );
if ( ( filter.getValue1( ) == null || filter.getValue1( )
.indexOf( "._outer" ) < 0 ) //$NON-NLS-1$
&& ( filter.getValue2( ) == null || filter.getValue2( )
.indexOf( "._outer" ) < 0 ) ) //$NON-NLS-1$
{
filterList.add( filter );
}
}
}
}
}
// Get filters on current item hanlde.
ph = itemHandle.getPropertyHandle( ExtendedItemHandle.FILTER_PROP );
if ( ph != null )
{
Iterator<FilterConditionHandle> filterIterator = ph.iterator( );
if ( filterIterator != null )
{
while ( filterIterator.hasNext( ) )
{
// Design time doesn't support parent query expressions
FilterConditionHandle filter = filterIterator.next( );
if ( ( filter.getValue1( ) == null || filter.getValue1( )
.indexOf( "._outer" ) < 0 )//$NON-NLS-1$
&& ( filter.getValue2( ) == null || filter.getValue2( )
.indexOf( "._outer" ) < 0 ) ) //$NON-NLS-1$
{
filterList.add( filter );
}
}
}
}
return filterList.isEmpty( ) ? null : filterList.iterator( );
}
/**
* Creates the evaluator for Cube Live preview.
*
* @param cube
* @param cm
* @param columnExpression
* @return
* @throws BirtException
*/
protected IDataRowExpressionEvaluator createCubeEvaluator( CubeHandle cube,
final Chart cm, List<String> columnExpression )
throws BirtException
{
// Use the chart model in context, because this model will be updated
// once UI changes it. On the contrary, the model in handle may be old.
IBaseCubeQueryDefinition qd = null;
ReportItemHandle referredHandle = ChartReportItemUtil.getReportItemReference( itemHandle );
boolean isCrosstabReference = referredHandle != null
&& ICrosstabConstants.CROSSTAB_EXTENSION_NAME.equals( ( (ExtendedItemHandle) referredHandle ).getExtensionName( ) );
if ( referredHandle != null && isCrosstabReference )
{
// If it is 'sharing' case, include sharing crosstab and multiple
// view, we just invokes referred crosstab handle to create
// query.
ExtendedItemHandle bindingHandle = (ExtendedItemHandle) referredHandle;
qd = CrosstabQueryUtil.createCubeQuery( (CrosstabReportItemHandle) bindingHandle.getReportItem( ),
null,
session.getModelAdaptor( ),
true,
true,
true,
true,
true,
true );
}
else
{
qd = new ChartCubeQueryHelper( itemHandle,
cm,
session.getModelAdaptor( ) ).createCubeQuery( null );
}
// Add additional bindings, those bindings might be defined in chart's triggers.
if ( qd instanceof ICubeQueryDefinition
&& columnExpression != null
&& columnExpression.size( ) > 0 )
{
ICubeQueryDefinition queryDef = (ICubeQueryDefinition) qd;
// Generates a set of available binding names.
Set<String> bindingNames = new HashSet<String>( );
List<Object> bindings = queryDef.getBindings( );
for ( int i = 0; i < bindings.size( ); i++ )
{
bindingNames.add( ( (Binding) bindings.get( i ) ).getBindingName( ) );
}
ExpressionSet exprSet = new ExpressionSet( );
exprSet.addAll( columnExpression );
for ( String expr : exprSet )
{
exprCodec.decode( expr );
String bindingName = null;
if ( exprCodec.isCubeBinding( false ) )
{
bindingName = exprCodec.getCubeBindingName( false );
}
else
{
bindingName = exprCodec.getExpression( );
}
// Don't add duplicate binding.
if ( bindingNames.contains( bindingName ) )
{
continue;
}
bindingNames.add( bindingName );
// Create new binding
Binding colBinding = new Binding( bindingName );
colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE );
colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec,
session.getModelAdaptor( ),
true ) );
queryDef.addBinding( colBinding );
}
}
resetCubeQuery( qd );
if ( needDefineCube( cube ) )
{
DataService.getInstance( ).registerSession( cube, session );
session.defineCube( cube );
}
// Always cube query returned
ICubeQueryResults cqr = dteAdapter.executeQuery( session,
(ICubeQueryDefinition) qd );
// Sharing case
BIRTCubeResultSetEvaluator bcrse = null;
if ( referredHandle != null && isCrosstabReference )
{
bcrse = new SharedCubeResultSetEvaluator( cqr, qd, cm );
}
else
{
bcrse = new BIRTCubeResultSetEvaluator( cqr );
}
bcrse.setSizeLimit( getMaxRow( ) );
return bcrse;
}
/**
* @param qd
*/
@SuppressWarnings("unchecked")
protected void resetCubeQuery( IBaseCubeQueryDefinition qd )
{
// Remove special filters that contain _outer expression, live
// preview doesn't support it.
ICubeQueryDefinition cqd = (ICubeQueryDefinition) qd;
for ( Iterator<ICubeFilterDefinition> iter = cqd.getFilters( )
.iterator( ); iter.hasNext( ); )
{
ICubeFilterDefinition cfd = iter.next( );
ConditionalExpression ce = (ConditionalExpression) cfd.getExpression( );
if ( hasOuterExpr( ce ) )
{
iter.remove( );
}
}
}
/**
* Check if specified base expression contains .outer expression.
*
* @param be
* @return
*/
private boolean hasOuterExpr( IBaseExpression be )
{
if ( be == null )
{
return false;
}
if ( be instanceof IScriptExpression )
{
IScriptExpression se = (IScriptExpression) be;
return ( se.getText( ) != null && se.getText( ).indexOf( "._outer" ) >= 0 ); //$NON-NLS-1$
}
else if ( be instanceof IExpressionCollection )
{
IExpressionCollection ec = (IExpressionCollection) be;
for ( Object expr : ec.getExpressions( ) )
{
if ( expr instanceof IBaseExpression )
{
if ( hasOuterExpr( (IBaseExpression) expr ) )
{
return true;
}
}
}
}
else if ( be instanceof IConditionalExpression )
{
IConditionalExpression ce = (IConditionalExpression) be;
return hasOuterExpr( ce.getExpression( ) )
|| hasOuterExpr( ce.getOperand1( ) )
|| hasOuterExpr( ce.getOperand2( ) );
}
return false;
}
/**
* The class is responsible to create query definition.
*
* @since BIRT 2.3
*/
class BaseQueryHelper extends AbstractChartBaseQueryGenerator
{
/**
* Constructor of the class.
*
* @param chart
* @param handle
* @param query
*/
public BaseQueryHelper( ExtendedItemHandle handle, Chart chart )
{
// Used query expressions have been wrapped as bindings, so do not
// wrap them again.
super( handle, chart, false, session.getModelAdaptor( ) );
}
/**
* Create query definition.
*
* @param columnExpression
* @throws DataException
*/
public IDataQueryDefinition createBaseQuery(
List<String> columnExpression ) throws ChartException
{
QueryDefinition queryDefn = new QueryDefinition( );
int maxRow = getMaxRow( );
queryDefn.setMaxRows( maxRow );
DataSetHandle dsHandle = getDataSetFromHandle( );
queryDefn.setDataSetName( dsHandle == null ? null
: dsHandle.getQualifiedName( ) );
for ( int i = 0; i < columnExpression.size( ); i++ )
{
String expr = columnExpression.get( i );
exprCodec.decode( expr );
String name = exprCodec.getExpression( );
if ( !fNameSet.contains( name ) )
{
Binding colBinding = new Binding( name );
colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec,
modelAdapter,
false ) );
try
{
queryDefn.addBinding( colBinding );
}
catch ( DataException e )
{
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.DATA_BINDING,
e );
}
fNameSet.add( name );
}
}
generateExtraBindings( queryDefn );
return queryDefn;
}
/**
* Add aggregate bindings of value series for grouping case.
*
* @param query
* @param seriesDefinitions
* @param innerMostGroupDef
* @param valueExprMap
* @param baseSD
* @throws DataException
* @throws DataException
*/
protected void addValueSeriesAggregateBindingForGrouping(
BaseQueryDefinition query,
EList<SeriesDefinition> seriesDefinitions,
GroupDefinition innerMostGroupDef,
Map<String, String[]> valueExprMap, SeriesDefinition baseSD )
throws ChartException
{
for ( SeriesDefinition orthSD : seriesDefinitions )
{
Series series = orthSD.getDesignTimeSeries( );
// The qlist contains available expressions which have
// aggregation.
List<Query> qlist = ChartEngine.instance( )
.getDataSetProcessor( series.getClass( ) )
.getDataDefinitionsForGrouping( series );
for ( Query qry : series.getDataDefinition( ) )
{
String expr = qry.getDefinition( );
if ( expr == null || "".equals( expr ) ) //$NON-NLS-1$
{
continue;
}
String aggName = ChartUtil.getAggregateFuncExpr( orthSD,
baseSD,
qry );
if ( aggName == null || "".equals( aggName ) ) //$NON-NLS-1$
{
continue;
}
// Get a unique name.
String name = ChartUtil.generateBindingNameOfValueSeries( qry,
orthSD,
baseSD );
if ( fNameSet.contains( name ) )
{
query.getBindings( ).remove( name );
}
fNameSet.add( name );
Binding colBinding = new Binding( name );
colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE );
if ( qlist.contains( qry ) ) // Has aggregation.
{
// Set binding expression by different aggregation, some
// aggregations can't set expression, like Count and so
try
{
setBindingExpressionDueToAggregation( colBinding,
expr,
aggName );
}
catch ( DataException e1 )
{
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.DATA_BINDING,
e1 );
}
if ( innerMostGroupDef != null )
{
try
{
colBinding.addAggregateOn( innerMostGroupDef.getName( ) );
}
catch ( DataException e )
{
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.DATA_BINDING,
e );
}
}
// Set aggregate parameters.
colBinding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggName ) );
IAggregateFunction aFunc = PluginSettings.instance( )
.getAggregateFunction( aggName );
if ( aFunc.getParametersCount( ) > 0 )
{
String[] parameters = ChartUtil.getAggFunParameters( orthSD,
baseSD,
qry );
for ( int i = 0; i < parameters.length
&& i < aFunc.getParametersCount( ); i++ )
{
String param = parameters[i];
colBinding.addArgument( new ScriptExpression( param ) );
}
}
}
else
{
// Direct setting expression for non-aggregation case.
exprCodec.decode( expr );
colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec,
modelAdapter,
false ) );
}
String newExpr = getExpressionForEvaluator( name );
try
{
query.addBinding( colBinding );
}
catch ( DataException e )
{
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.DATA_BINDING,
e );
}
valueExprMap.put( expr, new String[]{
expr, newExpr
} );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.reportitem.AbstractChartBaseQueryGenerator
* #createBaseQuery
* (org.eclipse.birt.data.engine.api.IDataQueryDefinition)
*/
public IDataQueryDefinition createBaseQuery( IDataQueryDefinition parent )
{
throw new UnsupportedOperationException( "Don't be implemented in the class." ); //$NON-NLS-1$
}
} // End of class BaseQueryHelper.
boolean isInXTabMeasureCell( )
{
return ChartCubeUtil.isInXTabMeasureCell( itemHandle );
}
boolean isInXTabCell( )
{
try
{
return ChartCubeUtil.getXtabContainerCell( itemHandle, false ) != null;
}
catch ( BirtException e )
{
// do nothing
}
return false;
}
boolean isInXTabNonAggrCell( )
{
return isInXTabCell( ) && !isInXTabAggrCell( );
}
boolean isPartChart( )
{
return ChartCubeUtil.isPlotChart( itemHandle )
|| ChartCubeUtil.isAxisChart( itemHandle );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#isSharedBinding
* ()
*/
boolean isSharedBinding( )
{
return ( itemHandle.getDataBindingReference( ) != null || isInMultiView( ) );
}
/**
* Check if current item handle is table shared binding reference.
*
* @return
* @since 2.3
*/
boolean isTableSharedBinding( )
{
return isSharedBinding( )
&& ChartCubeUtil.getBindingCube( itemHandle ) == null;
}
/**
* Set predefined expressions for table shared binding, in table shared
* binding case, the binding/expression is read only, so predefined them.
*
* @param headers
* @since 2.3
*/
public void setPredefinedExpressions( ColumnBindingInfo[] headers )
{
if ( isSharedBinding( ) || isInheritColumnsGroups( ) )
{
fShareBindingQueryHelper.setPredefinedExpressions( headers );
}
else
{
// Add expressions into predefined query for the content assist
// function when user set category/value series/Y optional
// expressions on UI.
context.addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
headers );
context.addPredefinedQuery( ChartUIConstants.QUERY_VALUE, headers );
context.addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
headers );
}
}
/**
* Returns report item handle.
*
* @since 2.3
*/
public ReportItemHandle getReportItemHandle( )
{
if ( isSharedBinding( ) )
{
if ( isInMultiView( ) )
{
return (ReportItemHandle) itemHandle.getContainer( )
.getContainer( );
}
return itemHandle.getDataBindingReference( );
}
else if ( isInXTabNonAggrCell( ) && isInheritCube( ) )
{
DesignElementHandle handle = itemHandle;
while ( handle != null )
{
handle = handle.getContainer( );
if ( handle instanceof ReportItemHandle
&& ( (ReportItemHandle) handle ).getColumnBindings( ) != null )
{
return (ReportItemHandle) handle;
}
}
return null;
}
return itemHandle;
}
/**
* The class declares some methods for processing query share with table.
*
* @since 2.3
*/
class ShareBindingQueryHelper
{
protected final ExpressionCodec sbqhExprCodec = ChartModelHelper.instance( )
.createExpressionCodec( );
/**
* Set predefined expressions for UI selections.
*
* @param headers
*/
private void setPredefinedExpressions( ColumnBindingInfo[] headers )
{
Object[] expressionsArray = getPredefinedExpressionsForSharing( headers );
context.addPredefinedQuery( ChartUIConstants.QUERY_CATEGORY,
(Object[]) expressionsArray[0] );
context.addPredefinedQuery( ChartUIConstants.QUERY_OPTIONAL,
(Object[]) expressionsArray[1] );
context.addPredefinedQuery( ChartUIConstants.QUERY_VALUE,
(Object[]) expressionsArray[2] );
}
/**
* Returns predefined expressions for sharing case.
*
* @param headers
* @return
*/
private Object[] getPredefinedExpressionsForSharing(
ColumnBindingInfo[] headers )
{
List<ColumnBindingInfo> commons = new LinkedList<ColumnBindingInfo>( );
List<ColumnBindingInfo> aggs = new LinkedList<ColumnBindingInfo>( );
List<ColumnBindingInfo> groups = new LinkedList<ColumnBindingInfo>( );
for ( int i = 0; i < headers.length; i++ )
{
int type = headers[i].getColumnType( );
switch ( type )
{
case ColumnBindingInfo.COMMON_COLUMN :
commons.add( headers[i] );
break;
case ColumnBindingInfo.AGGREGATE_COLUMN :
aggs.add( headers[i] );
break;
case ColumnBindingInfo.GROUP_COLUMN :
groups.add( headers[i] );
break;
}
}
List<ColumnBindingInfo> groupsWithAgg = new LinkedList<ColumnBindingInfo>( );
List<ColumnBindingInfo> groupsWithoutAgg = new LinkedList<ColumnBindingInfo>( groups );
for ( Iterator<ColumnBindingInfo> iter = groupsWithoutAgg.iterator( ); iter.hasNext( ); )
{
ColumnBindingInfo cbiGroup = iter.next( );
String groupName = cbiGroup.getName( );
// Remove some groups defined aggregate.
for ( ColumnBindingInfo cbiAggr : aggs )
{
if ( groupName.equals( ( (ComputedColumnHandle) cbiAggr.getObjectHandle( ) ).getAggregateOn( ) ) )
{
iter.remove( );
groupsWithAgg.add( cbiGroup );
break;
}
}
}
// Prepare category and Y optional items.
// TODO
// ? Now(2008/02/18), for share binding case, we use following
// rules:
// 1. Y optional grouping just allow to use first grouping
// definition in table.
// 2. Category series allow to use all grouping definitions and
// binding.
ColumnBindingInfo[] categorys = new ColumnBindingInfo[groups.size( )
+ commons.size( )];
int index = 0;
for ( ColumnBindingInfo cbi : groups )
{
categorys[index++] = cbi;
}
for ( ColumnBindingInfo cbi : commons )
{
categorys[index++] = cbi;
}
// Prepare Y optional items.
// (2009/10/27) Rules of inherit colum group: for inheriting column
// groups case, the Y optional grouping should allow to use all the
// outer groups than current group handle level(include self group).
ColumnBindingInfo[] optionals = null;
if ( isInheritColumnsGroups( ) && groups.size( ) > 0 )
{
List<ColumnBindingInfo> g = new LinkedList<ColumnBindingInfo>( );
DesignElementHandle reh = itemHandle;
while ( reh != null )
{
if ( reh.getContainer( ) instanceof GroupHandle )
{
reh = reh.getContainer( );
for ( ColumnBindingInfo cbi : groups )
{
g.add( cbi );
if ( reh.getName( ).equals( cbi.getName( ) ) )
{
break;
}
}
break;
}
else if ( reh.getContainer( ) instanceof RowHandle
&& reh.getContainer( ) != null
&& !( reh.getContainer( ).getContainer( ) instanceof GroupHandle ) )
{
DesignElementHandle deh = reh;
while ( deh != null )
{
if ( deh.getContainer( ) instanceof ListingHandle )
{
deh = deh.getContainer( );
break;
}
deh = deh.getContainer( );
}
if ( deh != null && deh instanceof ListingHandle )
{
if ( ( (ListingHandle) deh ).getDetail( )
.findPosn( reh.getContainer( ) ) >= 0 )
{
g = groups;
}
else if ( ( (ListingHandle) deh ).getHeader( )
.findPosn( reh.getContainer( ) ) >= 0 )
{
g.add( groups.get( 0 ) );
}
else if ( ( (ListingHandle) deh ).getFooter( )
.findPosn( reh.getContainer( ) ) >= 0 )
{
g.add( groups.get( 0 ) );
}
}
break;
}
else if ( reh.getContainer( ) instanceof ListingHandle )
{
reh = null;
break;
}
reh = reh.getContainer( );
}
optionals = new ColumnBindingInfo[g.size( )];
int i = 0;
for ( ColumnBindingInfo cbi : g )
{
optionals[i++] = cbi;
}
}
else
{
int size = ( groups.size( ) > 0 ) ? 1 : 0;
optionals = new ColumnBindingInfo[size];
if ( groups.size( ) > 0 )
{
optionals[0] = groups.get( 0 );
}
}
// Prepare value items.
ColumnBindingInfo[] values = new ColumnBindingInfo[aggs.size( )
+ commons.size( )];
index = 0;
for ( ColumnBindingInfo cbi : aggs )
{
values[index++] = cbi;
}
for ( ColumnBindingInfo cbi : commons )
{
values[index++] = cbi;
}
return new Object[]{
categorys, optionals, values
};
}
/**
* Prepare data expression evaluator for query share with table.
*
* @param cm
* @param columnExpression
* @return
* @throws BirtException
* @throws AdapterException
* @throws DataException
* @throws ChartException
*/
private IDataRowExpressionEvaluator createShareBindingEvaluator(
Chart cm, List<String> columnExpression ) throws BirtException,
AdapterException, DataException, ChartException
{
IQueryResults actualResultSet;
// Now only create query for table shared binding.
// Create query definition.
QueryDefinition queryDefn = new QueryDefinition( );
int maxRow = getMaxRow( );
queryDefn.setMaxRows( maxRow );
// Binding columns, aggregates, filters and sorts.
final Map<String, String> bindingExprsMap = new HashMap<String, String>( );
Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle );
List<ComputedColumnHandle> columnList = new ArrayList<ComputedColumnHandle>( );
while ( iterator.hasNext( ) )
{
columnList.add( iterator.next( ) );
}
generateShareBindingsWithTable( getPreviewHeadersInfo( columnList ),
queryDefn,
session,
bindingExprsMap );
// Add custom expression of chart.
addCustomExpressions( queryDefn,
cm,
columnExpression,
bindingExprsMap );
// Add filters from report handle.
Iterator<?> filtersIterator = getPropertyIterator( itemHandle.getPropertyHandle( ExtendedItemHandle.FILTER_PROP ) );
if ( filtersIterator != null )
{
while ( filtersIterator.hasNext( ) )
{
IFilterDefinition filter = session.getModelAdaptor( )
.adaptFilter( (FilterConditionHandle) filtersIterator.next( ) );
queryDefn.addFilter( filter );
}
}
actualResultSet = executeSharedQuery( queryDefn );
if ( actualResultSet != null )
{
return new BaseGroupedQueryResultSetEvaluator( actualResultSet.getResultIterator( ),
ChartReportItemUtil.isSetSummaryAggregation( cm ),
cm,
itemHandle ) {
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.factory.IDataRowExpressionEvaluator
* #evaluate(java.lang.String)
*/
public Object evaluate( String expression )
{
try
{
String newExpr = bindingExprsMap.get( expression );
if ( newExpr != null )
{
return fResultIterator.getValue( newExpr );
}
else
{
return fResultIterator.getValue( expression );
}
}
catch ( BirtException e )
{
sLogger.log( e );
}
return null;
}
};
}
return null;
}
/**
* @param queryDefn
* @return
* @throws AdapterException
* @throws BirtException
*/
private IQueryResults executeSharedQuery( QueryDefinition queryDefn )
throws AdapterException, BirtException
{
IQueryResults actualResultSet;
DataSetHandle dataSetHandle = ChartItemUtil.getBindingDataSet( itemHandle );
if ( needDefineDataSet( dataSetHandle ) )
{
DataService.getInstance( ).registerSession( dataSetHandle,
session );
dteAdapter.defineDataSet( dataSetHandle, session, true, false );
}
setRowLimit( session, getMaxRow( ), false );
actualResultSet = dteAdapter.executeQuery( session, queryDefn );
return actualResultSet;
}
/**
* Add custom expressions of chart to query.
*
* @param queryDefn
* @param cm
* @param bindingExprsMap
* @throws DataException
*/
private void addCustomExpressions( QueryDefinition queryDefn, Chart cm,
List<String> columnExpression,
final Map<String, String> bindingExprsMap )
throws DataException
{
List<Query> queryList = ChartBaseQueryHelper.getAllQueryExpressionDefinitions( cm );
Set<String> exprSet = new HashSet<String>( );
for ( Query query : queryList )
{
String expr = query.getDefinition( );
if ( expr != null )
{
exprSet.add( expr );
}
}
exprSet.addAll( columnExpression );
for ( String expr : exprSet )
{
if ( expr.length( ) > 0 && !bindingExprsMap.containsKey( expr ) )
{
sbqhExprCodec.decode( expr );
String name = StructureFactory.newComputedColumn( itemHandle,
ChartUtil.escapeSpecialCharacters( sbqhExprCodec.getExpression( ) ) )
.getName( );
queryDefn.addBinding( new Binding( name,
ChartReportItemUtil.adaptExpression( sbqhExprCodec,
session.getModelAdaptor( ),
false ) ) );
bindingExprsMap.put( expr, name );
}
}
}
/**
* Returns columns header info.
*
* @throws ChartException
* @since BIRT 2.3
*/
private final ColumnBindingInfo[] getPreviewHeadersInfo(
List<ComputedColumnHandle> columnList ) throws ChartException
{
if ( columnList == null || columnList.size( ) == 0 )
{
return new ColumnBindingInfo[0];
}
ColumnBindingInfo[] columnHeaders = null;
// Process grouping and aggregate on group case.
// Get groups.
List<GroupHandle> groupList = getGroupsOfSharedBinding( );
columnHeaders = new ColumnBindingInfo[columnList.size( )
+ groupList.size( )];
int index = 0;
for ( int i = 0; i < groupList.size( ); i++ )
{
GroupHandle gh = groupList.get( i );
String groupName = gh.getName( );
Expression expr = (Expression) gh.getExpressionProperty( IGroupElementModel.KEY_EXPR_PROP )
.getValue( );
exprCodec.setExpression( expr.getStringExpression( ) );
exprCodec.setType( expr.getType( ) );
String groupKeyExpr = exprCodec.encode( );
String tooltip = Messages.getString( "ReportDataServiceProvider.Tooltip.GroupExpression" ) + exprCodec.getExpression( ); //$NON-NLS-1$
columnHeaders[index++] = new ColumnBindingInfo( groupName,
groupKeyExpr, // Use expression for group.
ColumnBindingInfo.GROUP_COLUMN,
"icons/obj16/group.gif", //$NON-NLS-1$
tooltip,
gh );
for ( Iterator<ComputedColumnHandle> iter = columnList.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
String aggOn = cch.getAggregateOn( );
if ( groupName.equals( aggOn ) )
{
// Remove the column binding from list.
iter.remove( );
tooltip = Messages.getString( "ReportDataServiceProvider.Tooltip.Aggregate" ) + cch.getAggregateFunction( ) + "\n" + Messages.getString( "ReportDataServiceProvider.Tooltip.OnGroup" ) + groupName; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
columnHeaders[index] = new ColumnBindingInfo( cch.getName( ),
ExpressionUtil.createJSRowExpression( cch.getName( ) ), // Use
// binding
// expression
// for
// aggregate.
ColumnBindingInfo.AGGREGATE_COLUMN,
ChartUIConstants.IMAGE_SIGMA,
tooltip,
cch );
columnHeaders[index].setChartAggExpression( ChartReportItemUtil.convertToChartAggExpression( cch.getAggregateFunction( ) ) );
index++;
}
}
}
// Process aggregate on whole table case.
for ( Iterator<ComputedColumnHandle> iter = columnList.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
if ( cch.getAggregateFunction( ) != null )
{
// Remove the column binding form list.
iter.remove( );
String tooltip = Messages.getString( "ReportDataServiceProvider.Tooltip.Aggregate" ) + cch.getAggregateFunction( ) + "\n" + Messages.getString( "ReportDataServiceProvider.Tooltip.OnGroup" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
columnHeaders[index] = new ColumnBindingInfo( cch.getName( ),
ExpressionUtil.createJSRowExpression( cch.getName( ) ), // Use
// binding
// expression
// for
// aggregate.
ColumnBindingInfo.AGGREGATE_COLUMN,
ChartUIConstants.IMAGE_SIGMA,
tooltip,
cch );
columnHeaders[index].setChartAggExpression( ChartReportItemUtil.convertToChartAggExpression( cch.getAggregateFunction( ) ) );
index++;
}
}
// Process common bindings.
for ( Iterator<ComputedColumnHandle> iter = columnList.iterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
columnHeaders[index++] = new ColumnBindingInfo( cch.getName( ),
ExpressionUtil.createJSRowExpression( cch.getName( ) ), // Use
// binding
// expression
// for
// common
// binding.
ColumnBindingInfo.COMMON_COLUMN,
null,
null,
cch );
}
return columnHeaders;
}
/**
* Returns groups in shared binding.
*
* @return
*/
@SuppressWarnings("unchecked")
private List<GroupHandle> getGroupsOfSharedBinding( )
{
List<GroupHandle> groupList = new ArrayList<GroupHandle>( );
ListingHandle table = null;
if ( isInheritColumnsGroups( ) )
{
table = findListingInheritance( );
}
else
{
ReportItemHandle handle = getReportItemHandle( );
table = getSharedListingHandle( handle );
}
if ( table != null )
{
SlotHandle groups = table.getGroups( );
for ( Iterator<GroupHandle> iter = groups.iterator( ); iter.hasNext( ); )
{
groupList.add( iter.next( ) );
}
}
return groupList;
}
/**
* Returns correct shared table handle when chart is sharing table's
* query.
*
* @param aItemHandle
* @return
*/
private ListingHandle getSharedListingHandle(
ReportItemHandle aItemHandle )
{
if ( aItemHandle instanceof ListingHandle )
{
return (ListingHandle) aItemHandle;
}
ReportItemHandle handle = aItemHandle.getDataBindingReference( );
if ( handle != null )
{
return getSharedListingHandle( handle );
}
if ( aItemHandle.getContainer( ) instanceof MultiViewsHandle )
{
return getSharedListingHandle( (ReportItemHandle) aItemHandle.getContainer( )
.getContainer( ) );
}
return null;
}
/**
* Returns preview row data for table shared binding, it will share
* table's bindings and get them data.
*
* @param headers
* @param rowCount
* @param isStringType
* @return
* @throws ChartException
* @since 2.3
*/
private List<Object[]> getPreviewRowData( ColumnBindingInfo[] headers,
int rowCount, boolean isStringType ) throws ChartException
{
List<Object[]> dataList = new ArrayList<Object[]>( );
// Set thread context class loader so Rhino can find POJOs in
// workspace
// projects
ClassLoader oldContextLoader = Thread.currentThread( )
.getContextClassLoader( );
ClassLoader parentLoader = oldContextLoader;
if ( parentLoader == null )
parentLoader = this.getClass( ).getClassLoader( );
ClassLoader newContextLoader = DataSetProvider.getCustomScriptClassLoader( parentLoader,
itemHandle.getModuleHandle( ) );
Thread.currentThread( ).setContextClassLoader( newContextLoader );
try
{
// Create query definition.
QueryDefinition queryDefn = new QueryDefinition( );
queryDefn.setMaxRows( getMaxRow( ) );
// Binding columns, aggregates, filters and sorts.
List<String> columns = generateShareBindingsWithTable( headers,
queryDefn,
session,
new HashMap<String, String>( ) );
// Add filters from report handle.
Iterator<?> filtersIterator = getPropertyIterator( itemHandle.getPropertyHandle( IExtendedItemModel.FILTER_PROP ) );
if ( filtersIterator != null )
{
while ( filtersIterator.hasNext( ) )
{
IFilterDefinition filter = session.getModelAdaptor( )
.adaptFilter( (FilterConditionHandle) filtersIterator.next( ) );
queryDefn.addFilter( filter );
}
}
IQueryResults actualResultSet = executeSharedQuery( queryDefn );
if ( actualResultSet != null )
{
int columnCount = columns.size( );
IResultIterator iter = actualResultSet.getResultIterator( );
while ( iter.next( ) )
{
if ( isStringType )
{
String[] record = new String[columnCount];
for ( int n = 0; n < columnCount; n++ )
{
// Bugzilla#190229, to get string with localized
// format
record[n] = valueAsString( iter.getValue( columns.get( n ) ) );
}
dataList.add( record );
}
else
{
Object[] record = new Object[columnCount];
for ( int n = 0; n < columnCount; n++ )
{
record[n] = iter.getValue( columns.get( n ) );
}
dataList.add( record );
}
}
actualResultSet.close( );
}
}
catch ( BirtException e )
{
throw new ChartException( ChartReportItemUIActivator.ID,
ChartException.DATA_BINDING,
e );
}
finally
{
// Restore old thread context class loader
Thread.currentThread( )
.setContextClassLoader( oldContextLoader );
}
return dataList;
}
/**
* Generate share bindings with table into query.
*
* @param headers
* @param queryDefn
* @param aSession
* @param bindingExprsMap
* @return
* @throws AdapterException
* @throws DataException
*/
@SuppressWarnings("unchecked")
private List<String> generateShareBindingsWithTable(
ColumnBindingInfo[] headers, QueryDefinition queryDefn,
DataRequestSession aSession, Map<String, String> bindingExprsMap )
throws AdapterException, DataException
{
List<String> columns = new ArrayList<String>( );
ReportItemHandle reportItemHandle = getReportItemHandle( );
if ( isInheritColumnsGroups( ) )
{
reportItemHandle = findListingInheritance( );
}
queryDefn.setDataSetName( reportItemHandle.getDataSet( )
.getQualifiedName( ) );
IModelAdapter modelAdapter = aSession.getModelAdaptor( );
for ( int i = 0; i < headers.length; i++ )
{
ColumnBindingInfo chi = headers[i];
int type = chi.getColumnType( );
switch ( type )
{
case ColumnBindingInfo.COMMON_COLUMN :
case ColumnBindingInfo.AGGREGATE_COLUMN :
IBinding binding = modelAdapter.adaptBinding( (ComputedColumnHandle) chi.getObjectHandle( ) );
queryDefn.addBinding( binding );
columns.add( binding.getBindingName( ) );
// Use original binding expression as map key for
// aggregate
// and common binding.
bindingExprsMap.put( chi.getExpression( ),
binding.getBindingName( ) );
break;
case ColumnBindingInfo.GROUP_COLUMN :
GroupDefinition gd = modelAdapter.adaptGroup( (GroupHandle) chi.getObjectHandle( ) );
queryDefn.addGroup( gd );
String name = StructureFactory.newComputedColumn( reportItemHandle,
gd.getName( ) )
.getName( );
binding = new Binding( name );
binding.setExpression( modelAdapter.adaptExpression( ChartReportItemUtil.getExpression( (GroupHandle) chi.getObjectHandle( ) ) ) );
queryDefn.addBinding( binding );
columns.add( name );
// Use created binding expression as map key for group.
bindingExprsMap.put( ( (ScriptExpression) binding.getExpression( ) ).getText( ),
binding.getBindingName( ) );
break;
}
}
// Add sorts.
if ( reportItemHandle instanceof ListingHandle )
{
queryDefn.getSorts( )
.addAll( ChartBaseQueryHelper.createSorts( ( (ListingHandle) reportItemHandle ).sortsIterator( ),
modelAdapter ) );
}
return columns;
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#update(
* java.lang.String, java.lang.Object)
*/
@SuppressWarnings("unchecked")
public boolean update( String type, Object value )
{
boolean isUpdated = false;
if ( ChartUIConstants.COPY_SERIES_DEFINITION.equals( type ) )
{
copySeriesDefinition( value );
}
else if ( ChartUIConstants.QUERY_VALUE.equals( type )
&& ( getDataCube( ) != null && isSharedBinding( ) || isInXTabNonAggrCell( )
&& isInheritCube( ) ) )
{
// Need to automated set category/Y optional bindings by value
// series
// binding.
// 1. Get all bindings.
Map<String, ComputedColumnHandle> bindingMap = new LinkedHashMap<String, ComputedColumnHandle>( );
for ( Iterator<ComputedColumnHandle> bindings = ChartReportItemUtil.getAllColumnBindingsIterator( itemHandle ); bindings.hasNext( ); )
{
ComputedColumnHandle column = bindings.next( );
bindingMap.put( column.getName( ), column );
}
// 2. Get value series bindings.
String bindingName = exprCodec.getBindingName( (String) value );
ComputedColumnHandle computedBinding = bindingMap.get( bindingName );
// 3. Get all levels which value series binding aggregate on and set
// correct binding to category/ Y optional.
ChartAdapter.beginIgnoreNotifications( );
String exprType = UIUtil.getDefaultScriptType( );
List<String> aggOnList = computedBinding.getAggregateOnList( );
if ( aggOnList.size( ) > 0 )
{
String[] levelNames = CubeUtil.splitLevelName( aggOnList.get( 0 ) );
ComputedColumnHandle cch = ChartCubeUtil.findDimensionBinding( exprCodec,
levelNames[0],
levelNames[1],
bindingMap.values( ) );
// Set category.
if ( cch != null )
{
setCategoryExpression( exprType, cch );
}
}
if ( aggOnList.size( ) > 1 )
{
String[] levelNames = CubeUtil.splitLevelName( aggOnList.get( 1 ) );
ComputedColumnHandle cch = ChartCubeUtil.findDimensionBinding( exprCodec,
levelNames[0],
levelNames[1],
bindingMap.values( ) );
// Set optional Y.
if ( cch != null )
{
isUpdated = setOptionalYExpression( exprType,
cch );
}
}
else
{
if ( aggOnList.size( ) == 0 )
{
// If it consumes xtab, including multiple view, sharing
// xtab, and inheriting from xtab. And the selected series
// expression is a computed/derived expression, we need
// update category and optional Y expressions list for user
// to select.
CrosstabReportItemHandle xtabHandle = null;
try
{
if ( checkState( IN_MULTI_VIEWS ) )
{
// Chart view of xtab
xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) this.itemHandle.getContainer( )
.getContainer( ) ).getReportItem( );
}
else if ( isSharedBinding( ) ) // Sharing xtab.
{
ReportItemHandle rih = ChartReportItemUtil.getReportItemReference( this.itemHandle );
if ( rih != null && rih instanceof ExtendedItemHandle )
{
xtabHandle = (CrosstabReportItemHandle) ( (ExtendedItemHandle) rih ).getReportItem( );
}
}
else if ( isInXTabNonAggrCell( ) && isInheritCube( ) )
{
// Inheriting from xtab.
xtabHandle = ChartCubeUtil.getXtabContainerCell( itemHandle, false )
.getCrosstab( );
}
}
catch ( ExtendedElementException e )
{
WizardBase.displayException( e );
}
catch ( BirtException e )
{
WizardBase.displayException( e );
}
if ( xtabHandle != null )
{
isUpdated = updateExpressionForConsumingXTab( xtabHandle,
exprType,
bindingMap );
}
}
else
{
// When chart share cube with other chart, the measure
// expression(value series expressions) doesn't contain
// level
// information, so here only update Y optional expression
// for
// sharing with crosstab case.
if ( !isChartReportItemHandle( ChartItemUtil.getReportItemReference( itemHandle ) ) )
{
for ( Iterator<SeriesDefinition> iter = ChartUIUtil.getAllOrthogonalSeriesDefinitions( context.getModel( ) )
.iterator( ); iter.hasNext( ); )
{
SeriesDefinition sd = iter.next( );
sd.getQuery( ).setDefinition( "" ); //$NON-NLS-1$
isUpdated = true;
}
}
}
}
ChartAdapter.endIgnoreNotifications( );
}
else if ( ChartUIConstants.QUERY_CATEGORY.equals( type )
&& value instanceof String )
{
EList<SeriesDefinition> baseSDs = ChartUtil.getBaseSeriesDefinitions( context.getModel( ) );
for ( SeriesDefinition sd : baseSDs )
{
EList<Query> dds = sd.getDesignTimeSeries( )
.getDataDefinition( );
Query q = dds.get( 0 );
if ( q.getDefinition( ) == null
|| "".equals( q.getDefinition( ).trim( ) ) ) //$NON-NLS-1$
{
q.setDefinition( (String) value );
}
}
}
else if ( ChartUIConstants.QUERY_OPTIONAL.equals( type )
&& value instanceof String )
{
List<SeriesDefinition> orthSDs = ChartUtil.getAllOrthogonalSeriesDefinitions( context.getModel( ) );
for ( SeriesDefinition sd : orthSDs )
{
Query q = sd.getQuery( );
if ( q == null )
{
sd.setQuery( QueryImpl.create( (String) value ) );
continue;
}
if ( q.getDefinition( ) == null
|| "".equals( q.getDefinition( ).trim( ) ) ) //$NON-NLS-1$
{
q.setDefinition( (String) value );
}
}
}
else if ( ChartUIConstants.UPDATE_CUBE_BINDINGS.equals( type ) )
{
isUpdated = updateCubeBindings( );
}
return isUpdated;
}
private boolean updateExpressionForConsumingXTab(
CrosstabReportItemHandle xtabHandle, String exprType,
Map<String, ComputedColumnHandle> bindingMap )
{
boolean isUpdated = false;
List<ComputedColumnHandle> rowChildren = new ArrayList<ComputedColumnHandle>( );
for ( int i = 0; i < xtabHandle.getDimensionCount( ICrosstabConstants.ROW_AXIS_TYPE ); i++ )
{
DimensionViewHandle dimensionHandle = xtabHandle.getDimension( ICrosstabConstants.ROW_AXIS_TYPE,
i );
ComputedColumnHandle cch = ChartCubeUtil.findDimensionBinding( exprCodec,
dimensionHandle.getCubeDimensionName( ),
dimensionHandle.getLevel( dimensionHandle.getLevelCount( ) - 1 )
.getCubeLevel( )
.getName( ),
bindingMap.values( ) );
rowChildren.add( cch );
}
if ( rowChildren.size( ) > 0 )
{
// then don't set category expression again.
Query query = ChartUIUtil.getBaseSeriesDefinitions( context.getModel( ) )
.get( 0 )
.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
String expr = query.getDefinition( );
boolean needUpdate = !isExistentBinding( expr, bindingMap, exprType );
if ( needUpdate )
{
setCategoryExpression( exprType, rowChildren.get( 0 ) );
}
}
List<ComputedColumnHandle> colChildren = new ArrayList<ComputedColumnHandle>( );
for ( int i = 0; i < xtabHandle.getDimensionCount( ICrosstabConstants.COLUMN_AXIS_TYPE ); i++ )
{
DimensionViewHandle dimensionHandle = xtabHandle.getDimension( ICrosstabConstants.COLUMN_AXIS_TYPE,
i );
ComputedColumnHandle cch = ChartCubeUtil.findDimensionBinding( exprCodec,
dimensionHandle.getCubeDimensionName( ),
dimensionHandle.getLevel( dimensionHandle.getLevelCount( ) - 1 )
.getCubeLevel( )
.getName( ),
bindingMap.values( ) );
colChildren.add( cch );
}
if ( colChildren.size( ) > 0 )
{
// If row children list is empty, it means related
// crosstab has no row, just use column expression
// to set category expression of chart.
if ( rowChildren.size( ) == 0 )
{
// then don't set category expression again.
Query query = ChartUIUtil.getBaseSeriesDefinitions( context.getModel( ) )
.get( 0 )
.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
String expr = query.getDefinition( );
boolean needUpdate = !isExistentBinding( expr,
bindingMap,
exprType );
if ( needUpdate )
{
setCategoryExpression( exprType, colChildren.get( 0 ) );
}
}
else
{
// If the existent optional Y expression is
Query query = ChartUIUtil.getAllOrthogonalSeriesDefinitions( context.getModel( ) )
.get( 0 )
.getQuery( );
String expr = query.getDefinition( );
boolean needUpdate = !isExistentBinding( expr,
bindingMap,
exprType );
if ( needUpdate )
{
isUpdated = setOptionalYExpression( exprType,
colChildren.get( 0 ) );
}
}
}
return isUpdated;
}
private boolean isExistentBinding(String expr,
Map<String, ComputedColumnHandle> bindingMap, String exprType )
{
if ( expr == null || "".equals( expr) )
{
return false;
}
boolean isExistent = false;
for ( ComputedColumnHandle cch : bindingMap.values( ) )
{
exprCodec.setBindingName( cch.getName( ),
true,
exprType );
if ( expr.indexOf( exprCodec.encode( ) ) >= 0 )
{
isExistent = true;
break;
}
}
return isExistent;
}
private boolean setOptionalYExpression( String exprType, ComputedColumnHandle cch )
{
boolean isUpdated = false;
for ( Iterator<SeriesDefinition> iter = ChartUIUtil.getAllOrthogonalSeriesDefinitions( context.getModel( ) )
.iterator( ); iter.hasNext( ); )
{
exprCodec.setBindingName( cch.getName( ),
true,
exprType );
Query query = iter.next( ).getQuery( );
query.setDefinition( exprCodec.encode( ) );
isUpdated = true;
}
return isUpdated;
}
private void setCategoryExpression( String exprType,
ComputedColumnHandle cch )
{
Query query = ChartUIUtil.getBaseSeriesDefinitions( context.getModel( ) )
.get( 0 )
.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
exprCodec.setBindingName( cch.getName( ), true, exprType );
query.setDefinition( exprCodec.encode( ) );
// Update X axis type in chart with axes
if ( context.getModel( ) instanceof ChartWithAxes )
{
Axis xAxis = ChartUIUtil.getAxisXForProcessing( (ChartWithAxes) context.getModel( ) );
xAxis.setType( ChartItemUtil.convertToAxisType( cch.getDataType( ) ) );
}
}
/**
* Updates cube bindings due to the change of cube set.
*
* @return
*/
@SuppressWarnings("unchecked")
protected boolean updateCubeBindings( )
{
boolean updated = false;
try
{
CubeHandle cubeHandle = itemHandle.getCube( );
if ( cubeHandle != null )
{
List<ComputedColumn> columnList = ChartXTabUIUtil.generateComputedColumns( itemHandle,
cubeHandle );
if ( columnList.size( ) > 0 )
{
List<String> bindingNameList = new ArrayList<String>( );
for ( Iterator<ComputedColumnHandle> iter = itemHandle.columnBindingsIterator( ); iter.hasNext( ); )
{
ComputedColumnHandle cch = iter.next( );
bindingNameList.add( cch.getName( ) );
}
for ( Iterator<ComputedColumn> iter = columnList.iterator( ); iter.hasNext( ); )
{
ComputedColumn cc = iter.next( );
if ( !bindingNameList.contains( cc.getName( ) ) )
{
DEUtil.addColumn( itemHandle, cc, false );
updated = true;
}
}
}
}
}
catch ( SemanticException e )
{
ChartWizard.showException( ChartWizard.RepDSProvider_Cube_ID,
e.getLocalizedMessage( ) );
}
return updated;
}
/**
* Check if the cube of current item handle has multiple dimensions.
*
* @return
* @since 2.3
*/
boolean hasMultiCubeDimensions( )
{
CubeHandle cube = ChartCubeUtil.getBindingCube( itemHandle );
if ( ChartCubeUtil.getDimensionCount( cube ) > 1 )
{
return true;
}
return false;
}
boolean isInXTabAggrCell( )
{
try
{
AggregationCellHandle cell = ChartCubeUtil.getXtabContainerCell( itemHandle );
if ( cell != null )
{
return ChartCubeUtil.isAggregationCell( cell );
}
}
catch ( BirtException e )
{
// Silent exception
}
return false;
}
boolean isInheritColumnsSet( )
{
PropertyHandle property = itemHandle.getPropertyHandle( ChartReportItemConstants.PROPERTY_INHERIT_COLUMNS );
return property != null && property.isSet( );
}
boolean isInheritColumnsOnly( )
{
return itemHandle.getDataSet( ) == null
&& ChartReportItemUtil.isContainerInheritable( itemHandle )
&& context.isInheritColumnsOnly( );
}
boolean isInheritColumnsGroups( )
{
return itemHandle.getDataSet( ) == null
&& ChartReportItemUtil.isContainerInheritable( itemHandle )
&& !context.isInheritColumnsOnly( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#getStates()
*/
public int getState( )
{
int states = 0;
if ( getDataSet( ) != null )
{
states |= HAS_DATA_SET;
}
if ( getDataCube( ) != null )
{
states |= HAS_CUBE;
}
if ( getInheritedDataSet( ) != null )
{
states |= INHERIT_DATA_SET;
}
if ( getInheritedCube( ) != null )
{
states |= INHERIT_CUBE;
}
if ( itemHandle.getDataBindingReference( ) != null )
{
states |= DATA_BINDING_REFERENCE;
}
if ( isInMultiView( ) )
{
states |= IN_MULTI_VIEWS;
}
if ( isSharedBinding( ) )
{
states |= SHARE_QUERY;
if ( isSharingChart( false ) )
{
states |= SHARE_CHART_QUERY;
}
if ( isSharingChart( true ) )
{
states |= SHARE_CHART_QUERY_RECURSIVELY;
}
if ( ChartCubeUtil.getBindingCube( itemHandle ) != null )
{
states |= SHARE_CROSSTAB_QUERY;
}
else if ( !isSharingChart( false ) )
{
states |= SHARE_TABLE_QUERY;
}
}
if ( isPartChart( ) )
{
states |= PART_CHART;
}
if ( hasMultiCubeDimensions( ) )
{
states |= MULTI_CUBE_DIMENSIONS;
}
if ( isInheritColumnsOnly( ) )
{
states |= INHERIT_COLUMNS_ONLY;
}
if ( isInheritColumnsGroups( ) )
{
states |= INHERIT_COLUMNS_GROUPS;
}
return states;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#checkState
* (int)
*/
public boolean checkState( int state )
{
return ( getState( ) & state ) == state;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider#checkData
* (String, java.lang.Object)
*/
public Object checkData( String checkType, Object data )
{
if ( ChartUIConstants.QUERY_OPTIONAL.equals( checkType )
|| ChartUIConstants.QUERY_CATEGORY.equals( checkType ) )
{
// Only check query for Cube/Crosstab sharing cases.
if ( checkState( IDataServiceProvider.INHERIT_CUBE )
|| checkState( IDataServiceProvider.HAS_CUBE )
|| checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
{
return Boolean.valueOf( ChartXTabUIUtil.checkQueryExpression( checkType,
data,
context.getModel( ),
itemHandle,
this ) );
}
}
return null;
}
private ListingHandle findListingInheritance( )
{
DesignElementHandle container = itemHandle.getContainer( );
while ( container != null )
{
if ( container instanceof ListingHandle
&& ( (ListingHandle) container ).getDataSet( ) != null )
{
return (ListingHandle) container;
}
container = container.getContainer( );
}
return null;
}
/**
* Calculate the number of expressions binded to category series, value
* series or y-optional grouping .
*
* @param expr
* @return count number
*/
int getNumberOfSameDataDefinition( String expr )
{
if ( expr == null )
{
return 0;
}
int count = 0;
Chart chart = context.getModel( );
String[] expres = ChartUtil.getCategoryExpressions( chart );
for ( String s : expres )
{
if ( expr.equals( s ) )
{
count++;
}
}
expres = ChartUtil.getValueSeriesExpressions( chart );
for ( String s : expres )
{
if ( expr.equals( s ) )
{
count++;
}
}
expres = ChartUtil.getYOptoinalExpressions( chart );
for ( String s : expres )
{
if ( expr.equals( s ) )
{
count++;
}
}
return count;
}
/**
* Check if current item handle is table shared binding reference. Check if
* current is sharing query with other chart.
*
* @param isRecursive
* <code>true</code> means it will be recursive to find out the
* shared chart case, else just check if the direct reference is
* a chart item.
* @return
*/
boolean isSharingChart( boolean isRecursive )
{
boolean isShare = isSharedBinding( );
if ( isRecursive )
{
return isShare
&& isChartReportItemHandle( ChartReportItemUtil.getReportItemReference( itemHandle ) );
}
else
{
return isShare
&& isChartReportItemHandle( itemHandle.getDataBindingReference( ) );
}
}
/**
* This method just calls a utility method to check if current handle holds
* a chart,and will be overridden for difference cases.
*
* @param referredHandle
* @return if current handle holds a chart
* @since 2.5.3
*/
public boolean isChartReportItemHandle( ReportItemHandle referredHandle )
{
return ChartReportItemUtil.isChartReportItemHandle( referredHandle );
}
/**
* This method just calls a utility method to get reference handle.
*
* @return reference handle
* @since 2.5.3
*/
public ExtendedItemHandle getChartReferenceItemHandle( )
{
return ChartReportItemUtil.getChartReferenceItemHandle( itemHandle );
}
/**
* @param target
* @since 2.5.1
*/
protected void copySeriesDefinition( Object target )
{
Chart targetCM = context.getModel( );
if ( target != null && target instanceof Chart )
{
targetCM = (Chart) target;
}
ExtendedItemHandle refHandle = getChartReferenceItemHandle( );
if ( refHandle != null )
{
Chart srcChart = ChartReportItemUtil.getChartFromHandle( refHandle );
ChartReportItemUtil.copyChartSeriesDefinition( srcChart, targetCM );
ChartReportItemUtil.copyChartSampleData( srcChart, targetCM );
}
}
public String[] getSeriesExpressionsFrom( Object obj, String type )
{
if ( !( obj instanceof Chart ) )
{
return new String[]{};
}
if ( ChartUIConstants.QUERY_CATEGORY.equals( type ) )
{
return ChartUtil.getCategoryExpressions( (Chart) obj );
}
else if ( ChartUIConstants.QUERY_OPTIONAL.equals( type ) )
{
return ChartUtil.getYOptoinalExpressions( (Chart) obj );
}
else if ( ChartUIConstants.QUERY_VALUE.equals( type ) )
{
return ChartUtil.getValueSeriesExpressions( (Chart) obj );
}
return new String[]{};
}
/**
* DummyEngineTask implementation for chart live preview.
*/
protected static class ChartDummyEngineTask extends DummyEngineTask
{
public ChartDummyEngineTask( ReportEngine engine,
IReportRunnable runnable, ModuleHandle moduleHandle )
{
super( engine, runnable, moduleHandle );
}
@Override
public void run( ) throws EngineException
{
parameterChanged = true;
usingParameterValues( );
// Initial report variables to make sure the report variables can be
// access in chart builder.
initReportVariable( );
loadDesign( );
}
}
}
|
package net.maizegenetics.analysis.data;
import net.maizegenetics.dna.snp.ExportUtils;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.gui.DialogUtils;
import net.maizegenetics.gui.GenotypeTableMask;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.taxa.distance.DistanceMatrix;
import net.maizegenetics.taxa.distance.WriteDistanceMatrix;
import net.maizegenetics.prefs.TasselPrefs;
import net.maizegenetics.tassel.TASSELMainFrame;
import net.maizegenetics.trait.Phenotype;
import net.maizegenetics.trait.PhenotypeUtils;
import net.maizegenetics.util.*;
import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URL;
/**
*
* @author terry
*/
public class ExportPlugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(ExportPlugin.class);
private FileLoadPlugin.TasselFileType myFileType = FileLoadPlugin.TasselFileType.Hapmap;
private String mySaveFile = null;
private boolean myIsDiploid = false;
private boolean myKeepDepth = true;
private final JFileChooser myFileChooserSave = new JFileChooser(TasselPrefs.getSaveDir());
/**
* Creates a new instance of ExportPlugin
*/
public ExportPlugin(Frame parentFrame, boolean isInteractive) {
super(parentFrame, isInteractive);
}
public DataSet performFunction(DataSet input) {
try {
if (input.getSize() != 1) {
String message = "Please select one and only one item.";
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
String filename = mySaveFile;
try {
Object data = input.getData(0).getData();
if (data instanceof GenotypeTable) {
filename = performFunctionForAlignment((GenotypeTable) data);
} else if (data instanceof Phenotype) {
filename = performFunctionForPhenotype((Phenotype) data);
} else if (data instanceof DistanceMatrix) {
filename = performFunctionForDistanceMatrix((DistanceMatrix) data);
} else if (data instanceof TableReport) {
filename = performFunctionForTableReport((TableReport) data);
} else if (data instanceof Report) {
filename = performFunctionForReport((Report) data);
} else {
String message = "Don't know how to export data type: " + data.getClass().getName();
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
} catch (Exception e) {
e.printStackTrace();
StringBuilder builder = new StringBuilder();
builder.append(Utils.shortenStrLineLen(ExceptionUtils.getExceptionCauses(e), 50));
String str = builder.toString();
if (isInteractive()) {
DialogUtils.showError(str, getParentFrame());
} else {
myLogger.error(str);
}
return null;
}
if (filename != null) {
myLogger.info("performFunction: wrote dataset: " + input.getData(0).getName() + " to file: " + filename);
return new DataSet(new Datum("Filename", filename, null), this);
} else {
return null;
}
} finally {
fireProgress(100);
}
}
public String performFunctionForDistanceMatrix(DistanceMatrix input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
try {
File theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
WriteDistanceMatrix.saveDelimitedDistanceMatrix(input, theFile);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForDistanceMatrix: Problem writing file: " + mySaveFile);
}
}
public String performFunctionForTableReport(TableReport input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
try {
File theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
TableReportUtils.saveDelimitedTableReport(input, "\t", theFile);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForTableReport: Problem writing file: " + mySaveFile);
}
}
public String performFunctionForPhenotype(Phenotype input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
File theFile = null;
FileWriter fw = null;
PrintWriter pw = null;
try {
theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
fw = new FileWriter(theFile);
pw = new PrintWriter(fw);
PhenotypeUtils.saveAs(input, pw);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForPhenotype: Problem writing file: " + mySaveFile);
} finally {
try {
pw.close();
fw.close();
} catch (Exception e) {
// do nothing
}
}
}
public String performFunctionForAlignment(GenotypeTable inputAlignment) {
if (isInteractive()) {
ExportPluginDialog theDialog = new ExportPluginDialog();
theDialog.setLocationRelativeTo(getParentFrame());
theDialog.setVisible(true);
if (theDialog.isCancel()) {
return null;
}
myFileType = theDialog.getTasselFileType();
myKeepDepth = theDialog.keepDepth();
theDialog.dispose();
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
String resultFile = mySaveFile;
if ((myFileType == FileLoadPlugin.TasselFileType.Hapmap) || (myFileType == FileLoadPlugin.TasselFileType.HapmapDiploid)) {
int n = 0;
DefaultMutableTreeNode node = null;
if (isInteractive()) {
DiploidOptionDialog diploidDialog = new DiploidOptionDialog();
diploidDialog.setLocationRelativeTo(getParentFrame());
diploidDialog.setVisible(true);
myIsDiploid = diploidDialog.getDiploid();
node = (DefaultMutableTreeNode) ((TASSELMainFrame) this.getParentFrame()).getDataTreePanel().getTree().getLastSelectedPathComponent();
n = node.getChildCount();
} else {
if (myFileType == FileLoadPlugin.TasselFileType.Hapmap) {
myIsDiploid = false;
} else if (myFileType == FileLoadPlugin.TasselFileType.HapmapDiploid) {
myIsDiploid = true;
}
}
boolean foundImputed = false;
if ((n == 0) || (!isInteractive())) {
resultFile = ExportUtils.writeToHapmap(inputAlignment, myIsDiploid, mySaveFile, '\t', this);
} else {
int i = 0;
while (i < n && !foundImputed) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) node.getChildAt(i);
Datum currentDatum = (Datum) currentNode.getUserObject();
Object currentMask = currentDatum.getData();
if (currentMask instanceof GenotypeTableMask) {
GenotypeTableMask.MaskType maskType = ((GenotypeTableMask) currentMask).getMaskType();
if (maskType == GenotypeTableMask.MaskType.imputed) {
ImputeDisplayOptionDialog imputeOptionDialog = new ImputeDisplayOptionDialog();
imputeOptionDialog.setLocationRelativeTo(getParentFrame());
imputeOptionDialog.setVisible(true);
if (imputeOptionDialog.getDisplayImputed()) {
//TODO emailed Terry about whether to keep
// resultFile = ExportUtils.writeToHapmap(inputAlignment, (GenotypeTableMask) currentMask, myIsDiploid, mySaveFile, '\t', this);
// foundImputed = true;
} else if (i == (n - 1)) {
resultFile = ExportUtils.writeToHapmap(inputAlignment, myIsDiploid, mySaveFile, '\t', this);
}
}
}
i++;
}
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Plink) {
resultFile = ExportUtils.writeToPlink(inputAlignment, mySaveFile, '\t');
} else if (myFileType == FileLoadPlugin.TasselFileType.Phylip_Seq) {
PrintWriter out = null;
try {
resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".phy");
out = new PrintWriter(new FileWriter(resultFile));
ExportUtils.printSequential(inputAlignment, out);
} catch (Exception e) {
throw new IllegalStateException("ExportPlugin: performFunction: Problem writing file: " + mySaveFile);
} finally {
out.flush();
out.close();
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Phylip_Inter) {
PrintWriter out = null;
try {
resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".phy");
out = new PrintWriter(new FileWriter(resultFile));
ExportUtils.printInterleaved(inputAlignment, out);
} catch (Exception e) {
throw new IllegalStateException("ExportPlugin: performFunction: Problem writing file: " + mySaveFile);
} finally {
out.flush();
out.close();
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Table) {
resultFile = ExportUtils.saveDelimitedAlignment(inputAlignment, "\t", mySaveFile);
} else if (myFileType == FileLoadPlugin.TasselFileType.Serial) {
resultFile = ExportUtils.writeAlignmentToSerialGZ(inputAlignment, mySaveFile);
} else if (myFileType == FileLoadPlugin.TasselFileType.HDF5) {
resultFile = ExportUtils.writeGenotypeHDF5(inputAlignment, mySaveFile, myKeepDepth);
} else if (myFileType == FileLoadPlugin.TasselFileType.VCF) {
resultFile = ExportUtils.writeToVCF(inputAlignment, mySaveFile, myKeepDepth);
} else {
throw new IllegalStateException("ExportPlugin: performFunction: Unknown Alignment File Format: " + myFileType);
}
return resultFile;
}
public String performFunctionForReport(Report input) {
if (isInteractive()) {
ReportOptionDialog theDialog = new ReportOptionDialog();
theDialog.setLocationRelativeTo(getParentFrame());
theDialog.setVisible(true);
if (theDialog.isCancel()) {
return null;
}
myFileType = theDialog.getTasselFileType();
theDialog.dispose();
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
String resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".txt");
if (myFileType == FileLoadPlugin.TasselFileType.Text) {
BufferedWriter writer = Utils.getBufferedWriter(resultFile);
try {
writer.append(input.toString());
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForReport: Problem writing file: " + resultFile);
} finally {
try {
writer.close();
} catch (Exception e) {
// do nothing
}
}
} else {
PrintWriter writer = null;
try {
writer = new PrintWriter(resultFile);
input.report(writer);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForReport: Problem writing file: " + resultFile);
} finally {
try {
writer.close();
} catch (Exception e) {
// do nothing
}
}
}
return resultFile;
}
/**
* Icon for this plugin to be used in buttons, etc.
*
* @return ImageIcon
*/
public ImageIcon getIcon() {
URL imageURL = ExportPlugin.class.getResource("/net/maizegenetics/analysis/images/Export16.gif");
if (imageURL == null) {
return null;
} else {
return new ImageIcon(imageURL);
}
}
/**
* Button name for this plugin to be used in buttons, etc.
*
* @return String
*/
public String getButtonName() {
return "Export";
}
/**
* Tool Tip Text for this plugin
*
* @return String
*/
public String getToolTipText() {
return "Export data to files on your computer.";
}
public String getSaveFile() {
return mySaveFile;
}
public void setSaveFile(String saveFile) {
mySaveFile = saveFile;
}
public void setSaveFile(File saveFile) {
if (saveFile == null) {
mySaveFile = null;
} else {
mySaveFile = saveFile.getPath();
}
}
public void setAlignmentFileType(FileLoadPlugin.TasselFileType type) {
myFileType = type;
}
public void setIsDiploid(boolean isDiploid) {
myIsDiploid = isDiploid;
}
private File getFileByChooser() {
myFileChooserSave.setMultiSelectionEnabled(false);
File result = null;
int returnVal = myFileChooserSave.showSaveDialog(getParentFrame());
if (returnVal == JFileChooser.SAVE_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) {
result = myFileChooserSave.getSelectedFile();
TasselPrefs.putSaveDir(myFileChooserSave.getCurrentDirectory().getPath());
}
return result;
}
class ExportPluginDialog extends JDialog {
private boolean myIsCancel = true;
private ButtonGroup myButtonGroup = new ButtonGroup();
private JRadioButton myHapMapRadioButton = new JRadioButton("Write Hapmap");
private JRadioButton myByteHDF5RadioButton = new JRadioButton("Write HDF5");
private JRadioButton myVCFRadioButton = new JRadioButton("Write VCF");
private JRadioButton myPlinkRadioButton = new JRadioButton("Write Plink");
private JRadioButton myPhylipRadioButton = new JRadioButton("Write Phylip (Sequential)");
private JRadioButton myPhylipInterRadioButton = new JRadioButton("Write Phylip (Interleaved)");
private JRadioButton myTabTableRadioButton = new JRadioButton("Write Tab Delimited");
private JCheckBox myKeepDepthCheck = new JCheckBox("Keep Depth (VCF or HDF5)",true);
public ExportPluginDialog() {
super((Frame) null, "Export...", true);
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() throws Exception {
setTitle("Export...");
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
setUndecorated(false);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
Container contentPane = getContentPane();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
JPanel main = getMain();
contentPane.add(main);
pack();
setResizable(false);
myButtonGroup.add(myHapMapRadioButton);
myButtonGroup.add(myByteHDF5RadioButton);
myButtonGroup.add(myVCFRadioButton);
myButtonGroup.add(myPlinkRadioButton);
myButtonGroup.add(myPhylipRadioButton);
myButtonGroup.add(myPhylipInterRadioButton);
myButtonGroup.add(myTabTableRadioButton);
myHapMapRadioButton.setSelected(true);
}
private JPanel getMain() {
JPanel inputs=new JPanel();
BoxLayout layout=new BoxLayout(inputs, BoxLayout.Y_AXIS);
inputs.setLayout(layout);
inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getLabel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getFileTypePanel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getOptionPanel());
inputs.add(Box.createRigidArea(new Dimension(1, 5)));
inputs.add(getButtons());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
return inputs;
}
private JPanel getLabel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
JLabel jLabel1 = new JLabel("Choose File Type to Export.");
jLabel1.setFont(new Font("Dialog", Font.BOLD, 18));
result.add(jLabel1);
return result;
}
private JPanel getFileTypePanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(myHapMapRadioButton);
result.add(myByteHDF5RadioButton);
result.add(myVCFRadioButton);
result.add(myPlinkRadioButton);
result.add(myPhylipRadioButton);
result.add(myPhylipInterRadioButton);
result.add(myTabTableRadioButton);
result.add(Box.createRigidArea(new Dimension(1, 20)));
return result;
}
private JPanel getOptionPanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(myKeepDepthCheck);
result.add(Box.createRigidArea(new Dimension(1, 10)));
return result;
}
private JPanel getButtons() {
JButton okButton = new JButton();
JButton cancelButton = new JButton();
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButton_actionPerformed(e);
}
});
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButton_actionPerformed(e);
}
});
JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER));
result.add(okButton);
result.add(cancelButton);
return result;
}
public FileLoadPlugin.TasselFileType getTasselFileType() {
if (myHapMapRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Hapmap;
}
if (myByteHDF5RadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.HDF5;
}
if (myVCFRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.VCF;
}
if (myPlinkRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Plink;
}
if (myPhylipRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Phylip_Seq;
}
if (myPhylipInterRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Phylip_Inter;
}
if (myTabTableRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Table;
}
return null;
}
public boolean keepDepth() {
return myKeepDepthCheck.isSelected();
}
private void okButton_actionPerformed(ActionEvent e) {
myIsCancel = false;
setVisible(false);
}
private void cancelButton_actionPerformed(ActionEvent e) {
myIsCancel = true;
setVisible(false);
}
public boolean isCancel() {
return myIsCancel;
}
}
}
class ImputeDisplayOptionDialog extends JDialog {
boolean displayImputed = true;
private JPanel mainPanel = new JPanel();
private JLabel lbl = new JLabel();
private JButton yesButton = new JButton();
private JButton noButton = new JButton();
private GridBagLayout gridBagLayout = new GridBagLayout();
public ImputeDisplayOptionDialog() {
super((Frame) null, "File Loader", true);
try {
initUI();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
void initUI() throws Exception {
lbl.setFont(new java.awt.Font("Dialog", 1, 12));
lbl.setText("Would you like Imputed data to be exported in lower case?");
mainPanel.setMinimumSize(new Dimension(480, 150));
mainPanel.setPreferredSize(new Dimension(480, 150));
mainPanel.setLayout(gridBagLayout);
yesButton.setMaximumSize(new Dimension(63, 27));
yesButton.setMinimumSize(new Dimension(63, 27));
yesButton.setText("Yes");
yesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
yesButton_actionPerformed(e);
}
});
noButton.setMaximumSize(new Dimension(63, 27));
noButton.setMinimumSize(new Dimension(63, 27));
noButton.setText("No");
noButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
noButton_actionPerformed(e);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
mainPanel.add(lbl, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
mainPanel.add(buttonPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.PAGE_END, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
this.add(mainPanel, BorderLayout.CENTER);
}
private void yesButton_actionPerformed(ActionEvent e) {
displayImputed = true;
setVisible(false);
}
private void noButton_actionPerformed(ActionEvent e) {
displayImputed = false;
setVisible(false);
}
public boolean getDisplayImputed() {
return displayImputed;
}
}
class DiploidOptionDialog extends JDialog {
boolean displayDiploid = true;
private JPanel mainPanel = new JPanel();
private JLabel lbl = new JLabel();
private JButton yesButton = new JButton();
private JButton noButton = new JButton();
private GridBagLayout gridBagLayout = new GridBagLayout();
public DiploidOptionDialog() {
super((Frame) null, "File Loader", true);
try {
initUI();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
void initUI() throws Exception {
lbl.setFont(new java.awt.Font("Dialog", 1, 12));
lbl.setText("Would you like SNPs to be exported as Diploids?");
mainPanel.setMinimumSize(new Dimension(480, 150));
mainPanel.setPreferredSize(new Dimension(480, 150));
mainPanel.setLayout(gridBagLayout);
yesButton.setMaximumSize(new Dimension(63, 27));
yesButton.setMinimumSize(new Dimension(63, 27));
yesButton.setText("Yes");
yesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
yesButton_actionPerformed(e);
}
});
noButton.setMaximumSize(new Dimension(63, 27));
noButton.setMinimumSize(new Dimension(63, 27));
noButton.setText("No");
noButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
noButton_actionPerformed(e);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
mainPanel.add(lbl, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
mainPanel.add(buttonPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.PAGE_END, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
this.add(mainPanel, BorderLayout.CENTER);
}
private void yesButton_actionPerformed(ActionEvent e) {
displayDiploid = true;
setVisible(false);
}
private void noButton_actionPerformed(ActionEvent e) {
displayDiploid = false;
setVisible(false);
}
public boolean getDiploid() {
return displayDiploid;
}
}
class ReportOptionDialog extends JDialog {
private boolean myIsCancel = true;
private ButtonGroup myButtonGroup = new ButtonGroup();
private JRadioButton myReportRadioButton = new JRadioButton("Write As Report");
private JRadioButton myTextRadioButton = new JRadioButton("Write As Text");
public ReportOptionDialog() {
super((Frame) null, "Export Report...", true);
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() throws Exception {
setTitle("Export Report...");
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
setUndecorated(false);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
Container contentPane = getContentPane();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
JPanel main = getMain();
contentPane.add(main);
pack();
setResizable(false);
myButtonGroup.add(myReportRadioButton);
myButtonGroup.add(myTextRadioButton);
myReportRadioButton.setSelected(true);
}
private JPanel getMain() {
JPanel inputs = new JPanel();
BoxLayout layout = new BoxLayout(inputs, BoxLayout.Y_AXIS);
inputs.setLayout(layout);
inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getLabel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getOptionPanel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getButtons());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
return inputs;
}
private JPanel getLabel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
JLabel jLabel1 = new JLabel("Choose File Type to Export.");
jLabel1.setFont(new Font("Dialog", Font.BOLD, 18));
result.add(jLabel1);
return result;
}
private JPanel getOptionPanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(myReportRadioButton);
result.add(myTextRadioButton);
result.add(Box.createRigidArea(new Dimension(1, 20)));
return result;
}
private JPanel getButtons() {
JButton okButton = new JButton();
JButton cancelButton = new JButton();
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButton_actionPerformed(e);
}
});
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButton_actionPerformed(e);
}
});
JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER));
result.add(okButton);
result.add(cancelButton);
return result;
}
public FileLoadPlugin.TasselFileType getTasselFileType() {
if (myTextRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Text;
}
return null;
}
private void okButton_actionPerformed(ActionEvent e) {
myIsCancel = false;
setVisible(false);
}
private void cancelButton_actionPerformed(ActionEvent e) {
myIsCancel = true;
setVisible(false);
}
public boolean isCancel() {
return myIsCancel;
}
}
|
package org.eclipse.birt.chart.reportitem;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.exception.GenerationException;
import org.eclipse.birt.chart.exception.PluginException;
import org.eclipse.birt.chart.exception.RenderingException;
import org.eclipse.birt.chart.factory.GeneratedChartState;
import org.eclipse.birt.chart.factory.Generator;
import org.eclipse.birt.chart.log.DefaultLoggerImpl;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.util.PluginSettings;
import org.eclipse.birt.report.engine.extension.DefaultReportItemPresentationImpl;
import org.eclipse.birt.report.engine.extension.Size;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.elements.ExtendedItem;
import org.eclipse.birt.report.model.extension.ExtendedElementException;
import org.eclipse.birt.report.model.extension.IReportItem;
public class ChartReportItemPresentationImpl extends DefaultReportItemPresentationImpl
{
private transient Chart cm = null;
private transient ExtendedItemHandle eih = null;
private transient File fChartImage = null;
private transient FileInputStream fis = null;
public ChartReportItemPresentationImpl()
{
super();
}
public final void initialize(HashMap hm)
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: initialize(...) - start");
super.initialize(hm);
cm = getModelFromWrapper(hm.get(MODEL_OBJ));
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: initialize(...) - end");
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getOutputType(java.lang.String, java.lang.String)
*/
public int getOutputType(String format, String mimeType)
{
return OUTPUT_AS_IMAGE;
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getSize()
*/
public Size getSize()
{
if (cm != null)
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: getSize(...) - start");
final Size sz = new Size();
sz.setWidth((float) cm.getBlock().getBounds().getWidth());
sz.setHeight((float) cm.getBlock().getBounds().getHeight());
sz.setUnit(Size.UNITS_PT);
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: getSize(...) - end");
return sz;
}
return super.getSize();
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#process()
*/
public Object process()
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: process(...) - start");
// SETUP A TEMP FILE FOR STREAMING
try {
fChartImage = File.createTempFile("chart", ".png");
DefaultLoggerImpl.instance().log(ILogger.INFORMATION, "Writing to PNG at " + fChartImage.getPath());
} catch (IOException ioex)
{
ioex.printStackTrace();
//throw new GenerationException(ioex);
}
// FETCH A HANDLE TO THE DEVICE RENDERER
IDeviceRenderer idr = null;
try {
idr = PluginSettings.instance().getDevice("dv.PNG24");
} catch (PluginException pex)
{
DefaultLoggerImpl.instance().log(pex);
//throw new GenerationException(ioex);
}
// BUILD THE CHART
final Bounds bo = cm.getBlock().getBounds();
DefaultLoggerImpl.instance().log(ILogger.ERROR, "Presentation uses bounds bo=" + bo);
final Generator gr = Generator.instance();
GeneratedChartState gcs = null;
try {
gcs = gr.build(
idr.getDisplayServer(),
cm, null,
bo,
null
);
} catch (GenerationException gex)
{
DefaultLoggerImpl.instance().log(gex);
//throw new GenerationException(ioex);
}
// WRITE TO THE PNG FILE
idr.setProperty(IDeviceRenderer.FILE_IDENTIFIER, fChartImage.getPath());
try {
gr.render(idr, gcs);
} catch (RenderingException rex)
{
DefaultLoggerImpl.instance().log(rex);
//throw new GenerationException(ioex);
}
// RETURN A STREAM HANDLE TO THE NEWLY CREATED IMAGE
try {
fis = new FileInputStream(fChartImage.getPath());
} catch (IOException ioex)
{
DefaultLoggerImpl.instance().log(ioex);
//throw new GenerationException(ioex);
}
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: process(...) - end");
return fis;
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#finish()
*/
public final void finish()
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: finish(...) - start");
// CLOSE THE TEMP STREAM PROVIDED TO THE CALLER
try {
fis.close();
} catch (IOException ioex)
{
DefaultLoggerImpl.instance().log(ioex);
//throw new GenerationException(ioex);
}
// DELETE THE TEMP CHART IMAGE FILE CREATED
if (!fChartImage.delete())
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "Could not delete temporary PNG file created at " + fChartImage.getPath());
}
else
{
DefaultLoggerImpl.instance().log(ILogger.INFORMATION, "Successfully deleted temporary PNG file created at " + fChartImage.getPath());
}
DefaultLoggerImpl.instance().log(ILogger.ERROR, "ChartReportItemPresentationImpl: finish(...) - end");
}
/**
*
* @param oReportItemImpl
* @return
*/
private final Chart getModelFromWrapper(Object oReportItemImpl)
{
eih = (ExtendedItemHandle) oReportItemImpl;
IReportItem item = ((ExtendedItem) eih.getElement()).getExtendedElement();
if (item == null)
{
try
{
eih.loadExtendedElement();
}
catch (ExtendedElementException eeex )
{
DefaultLoggerImpl.instance().log(eeex);
}
item = ((ExtendedItem) eih.getElement()).getExtendedElement();
if (item == null)
{
DefaultLoggerImpl.instance().log(ILogger.ERROR, "Unable to locate report item wrapper for chart object");
return null;
}
}
final ChartReportItemImpl crii = ((ChartReportItemImpl) item);
return crii.getModel();
}
}
|
/*
* TagsOnPhysMapHDF5
*/
package net.maizegenetics.gbs.maps;
import ch.systemsx.cisd.hdf5.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import net.maizegenetics.gbs.util.GBSHDF5Constants;
import org.apache.log4j.Logger;
/**
*
* TODO:
* <li> createFile - needs to deal with inputing just TAGS
* TODO: createFile that includes a Locus filter, only exports positions on the same locus and position range
*
*
* @author Ed, Terry
*/
public class TagsOnPhysMapHDF5 extends AbstractTagsOnPhysicalMap implements TOPMInterface {
private static final Logger myLogger = Logger.getLogger(TagsOnPhysMapHDF5.class);
private static final int NUM_UNITS_TO_CACHE_ON_GET = 64;
private static final int BITS_TO_SHIFT_FOR_CHUNK = 16;
private static final int CHUNK_SIZE = 1 << BITS_TO_SHIFT_FOR_CHUNK;
private static HDF5GenericStorageFeatures genoFeatures = HDF5GenericStorageFeatures.createDeflation(5); //used by mapping object
private static HDF5IntStorageFeatures vectorFeatures = HDF5IntStorageFeatures.createDeflation(5); //used by vectors
private int maxMapping = 4;
private IHDF5Writer myHDF5 = null;
private int cachedMappingIndex = -1;
private TagMappingInfo cachedTMI = null;
private int cachedMappingBlock = -1;
private TagMappingInfo[][] cachedTMIBlock = null;
private boolean cleanMap = true;
private boolean cacheAllMappingBlocks = false;
private HDF5CompoundType<TagMappingInfo> tmiType = null;
private boolean hasDetailedMapping=false;
public static void createFile(AbstractTagsOnPhysicalMap inTags, String newHDF5file, int maxMapping, int maxVariants) {
int tagLengthInLong = inTags.getTagSizeInLong();
int tagCount = inTags.getTagCount();
// tagCount=tagCount;
System.gc();
long[][] tags;
byte[] tagLength;
if(inTags instanceof AbstractTagsOnPhysicalMap) {
tags=((AbstractTagsOnPhysicalMap)inTags).getTagsArray();
tagLength=((AbstractTagsOnPhysicalMap)inTags).getTagLengthArray();
} else {
tags = new long[tagLengthInLong][tagCount];
tagLength = new byte[tagCount];
for (int i = 0; i < tagCount; i++) {
long[] ct = inTags.getTag(i);
for (int j = 0; j < tagLengthInLong; j++) {
tags[j][i] = ct[j];
}
tagLength[i] = (byte) inTags.getTagLength(i);
}
}
IHDF5Writer h5 = null;
try {
myLogger.info("Creating HDF5 File: " + newHDF5file);
System.out.println("Creating HDF5 File: " + newHDF5file);
IHDF5WriterConfigurator config = HDF5Factory.configure(new File(newHDF5file));
config.overwrite();
// config.dontUseExtendableDataTypes();
config.useUTF8CharacterEncoding();
h5 = config.writer();
h5.setIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.TAGCOUNT, tagCount);
h5.setIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.MAXVARIANTS, maxVariants);
h5.setIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.MAXMAPPING, maxMapping);
h5.setIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.TAGLENGTHINLONG, tagLengthInLong);
//create tag matrix
h5.createLongMatrix(GBSHDF5Constants.TAGS, inTags.getTagSizeInLong(), tagCount, inTags.getTagSizeInLong(), tagCount, vectorFeatures);
h5.writeLongMatrix(GBSHDF5Constants.TAGS, tags, vectorFeatures);
tags=null;
System.gc();
System.out.println("...Tags written");
h5.createByteArray(GBSHDF5Constants.TAGLENGTH, tagCount, vectorFeatures);
h5.writeByteArray(GBSHDF5Constants.TAGLENGTH, tagLength, vectorFeatures);
tagLength=null;
System.out.println("...Tags lengths written");
//need to create branch between instance of Tags and TOPM
//creating fast bestChr and bestPosition
byte[] mmOut=new byte[tagCount];
byte[] strandOut=new byte[tagCount];
int[] chrOut=new int[tagCount];
int[] posOut=new int[tagCount];
for (int i = 0; i < tagCount; i++) {
mmOut[i]=inTags.getMultiMaps(i);
strandOut[i]=inTags.getStrand(i);
chrOut[i]=inTags.getChromosome(i);
posOut[i]=inTags.getStartPosition(i);
}
h5.createByteArray(GBSHDF5Constants.MULTIMAPS, tagCount);
h5.writeByteArray(GBSHDF5Constants.MULTIMAPS, mmOut, vectorFeatures);
h5.createByteArray(GBSHDF5Constants.BEST_STRAND, tagCount);
h5.writeByteArray(GBSHDF5Constants.BEST_STRAND, strandOut, vectorFeatures);
h5.createIntArray(GBSHDF5Constants.BEST_CHR, tagCount, vectorFeatures);
h5.writeIntArray(GBSHDF5Constants.BEST_CHR, chrOut, vectorFeatures);
h5.createIntArray(GBSHDF5Constants.BEST_STARTPOS, tagCount, vectorFeatures);
h5.writeIntArray(GBSHDF5Constants.BEST_STARTPOS, posOut, vectorFeatures);
mmOut=null;
strandOut=null;
chrOut=null;
posOut=null;
System.gc();
System.out.println("...multimapping, strand, chr, position written");
HDF5CompoundType<TagMappingInfo> tmiType = h5.compounds().getInferredType(TagMappingInfo.class);
System.out.println("Chunk Size for Tags: " + CHUNK_SIZE);
int numOfChunks = tagsToChunks(tagCount);
System.out.println("Number of Chunks: " + numOfChunks);
int numTagsPadded = numOfChunks * CHUNK_SIZE;
for (int mi = 0; mi < 1; mi++) {
// for (int mi = 0; mi < maxMapping; mi++) {
// h5.compounds().createArray("map" + mi, tmiType, numTagsPadded, CHUNK_SIZE);
h5.compounds().createArray(GBSHDF5Constants.MAPBASE + mi, tmiType, numTagsPadded, CHUNK_SIZE);
TagMappingInfo[] thTMI = new TagMappingInfo[CHUNK_SIZE];
int block = 0;
for (int i = 0; i < numTagsPadded; i++) {
if ((mi == 0) && (i < tagCount)) {
thTMI[i % CHUNK_SIZE] = (new TagMappingInfo(inTags.getChromosome(i),
inTags.getStrand(i), inTags.getStartPosition(i),
inTags.getEndPosition(i), inTags.getDivergence(i)));
} else {
thTMI[i % CHUNK_SIZE] = new TagMappingInfo();
}
if ((i + 1) % CHUNK_SIZE == 0) {
// h5.compounds().writeArrayBlock("map" + mi, tmiType, thTMI, block);
h5.compounds().writeArrayBlock(GBSHDF5Constants.MAPBASE + mi, tmiType, thTMI, block);
thTMI = new TagMappingInfo[CHUNK_SIZE];
block++;
System.out.println("Tag locations written: " + (i + 1));
}
}
System.out.println("...map" + mi + " positions written");
}
h5.createByteMatrix(GBSHDF5Constants.VARIANTDEF, tagCount, maxVariants);
int numVariants = inTags.getMaxNumVariants();
if (numVariants > maxVariants) {
throw new IllegalArgumentException("TagsOnPhysMapHDF5: createFile: max variants can't be less than original TOPM Variant Defs: " + numVariants);
}
writeVariantsToHDF5(h5, inTags);
System.out.println("Variant offsets written");
} finally {
try {
h5.close();
} catch (Exception e) {
// do nothing
}
}
}
private static int tagsToChunks(long tags) {
return (int) (((tags - 1) >>> BITS_TO_SHIFT_FOR_CHUNK) + 1);
}
public TagsOnPhysMapHDF5(String filename) {
this(filename, true);
}
public TagsOnPhysMapHDF5(String theHDF5file, boolean cacheAllMappingBlocks) {
myMaxVariants = 16;
this.cacheAllMappingBlocks = cacheAllMappingBlocks;
System.out.println("Opening :" + theHDF5file);
myHDF5 = HDF5Factory.open(theHDF5file);
hasDetailedMapping=myHDF5.exists(GBSHDF5Constants.MAPBASE+"0");
myNumTags = myHDF5.getIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.TAGCOUNT);
this.tagLengthInLong = myHDF5.getIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.TAGLENGTHINLONG);
this.tags = myHDF5.readLongMatrix(GBSHDF5Constants.TAGS);
this.tagLength = myHDF5.readByteArray(GBSHDF5Constants.TAGLENGTH);
this.multimaps = myHDF5.readByteArray(GBSHDF5Constants.MULTIMAPS);
this.maxMapping = myHDF5.getIntAttribute(GBSHDF5Constants.ROOT, GBSHDF5Constants.MAXMAPPING);
tmiType = myHDF5.compounds().getInferredType(TagMappingInfo.class);
cachedTMIBlock = new TagMappingInfo[maxMapping][];
if(hasDetailedMapping) cacheMappingInfo(0);
if(!myHDF5.exists(GBSHDF5Constants.BEST_STRAND)) {populateBestMappings();}
else {
bestStrand=myHDF5.readByteArray("bestStrand");
bestChr= myHDF5.readIntArray("bestChr");
bestStartPos= myHDF5.readIntArray("bestStartPos");
}
loadVariantsIntoMemory();
System.out.println(theHDF5file + " read with tags:" + myNumTags);
populateChrAndVarPositions();
initPhysicalSort();
System.gc();
}
private boolean populateBestMappings() {
bestStrand=new byte[myNumTags];
bestChr=new int[myNumTags];
bestStartPos=new int[myNumTags];
if(myHDF5.exists(GBSHDF5Constants.MAPBASE+"0")==false) {
Arrays.fill(bestStrand, TOPMInterface.BYTE_MISSING);
Arrays.fill(bestChr, TOPMInterface.INT_MISSING);
Arrays.fill(bestStartPos, TOPMInterface.INT_MISSING);
return false;
}
for (int i = 0; i < myNumTags; i++) {
int[] posArray=getPositionArray(i);
// {cachedTMI.chromosome, cachedTMI.strand, cachedTMI.startPosition}
bestStrand[i]=(byte)posArray[1];
bestChr[i]=posArray[0];
bestStartPos[i]=posArray[2];
}
myHDF5.createByteArray(GBSHDF5Constants.BEST_STRAND, myNumTags);
myHDF5.writeByteArray(GBSHDF5Constants.BEST_STRAND, bestStrand, vectorFeatures);
myHDF5.createIntArray(GBSHDF5Constants.BEST_CHR, myNumTags, vectorFeatures);
myHDF5.writeIntArray(GBSHDF5Constants.BEST_CHR, bestChr, vectorFeatures);
myHDF5.createIntArray(GBSHDF5Constants.BEST_STARTPOS, myNumTags, vectorFeatures);
myHDF5.writeIntArray(GBSHDF5Constants.BEST_STARTPOS, bestStartPos, vectorFeatures);
return true;
}
private boolean loadVariantsIntoMemory() {
int howManyDef=0;
int readBlock=4096*16;
variantDefs=new byte[myNumTags][];
variantOffsets=new byte[myNumTags][];
if(!myHDF5.exists(GBSHDF5Constants.VARIANTDEF)) return false;
for (int blockStep = 0; blockStep < myNumTags; blockStep+=readBlock) {
int blockSize=(myNumTags-blockStep<readBlock)?myNumTags-blockStep:readBlock;
byte[][] vd=myHDF5.readByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTDEF,blockSize,myMaxVariants,blockStep,0);
// System.out.println(Arrays.toString(vd[0]));
byte[][] vo=myHDF5.readByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTPOSOFF,blockSize,myMaxVariants,blockStep,0);
for (int j = 0; j < blockSize; j++) {
int cnt=0;
for (byte bs : vd[j]) {if (bs!=TOPMInterface.BYTE_MISSING) cnt++;}
if(cnt==0) continue;
byte[] vdReDim=new byte[cnt];
byte[] voReDim=new byte[cnt];
for (int i = 0; i < cnt; i++) {
vdReDim[i]=vd[j][i];
voReDim[i]=vo[j][i];
howManyDef++;
}
variantDefs[blockStep+j]=vdReDim;
variantOffsets[blockStep+j]=voReDim;
}
//byte[] vd=myHDF5.readByteArrayBlockWithOffset(null, i, i)
}
System.out.println("Real Variant Defs:"+howManyDef);
return true;
}
private static boolean writeVariantsToHDF5(IHDF5Writer aHDF5, AbstractTagsOnPhysicalMap aTOPM) {
int howManyDef=0;
int readBlock=4096*16;
int myNumTags=aTOPM.myNumTags;
int myMaxVariants=aTOPM.myMaxVariants;
aHDF5.createByteMatrix(GBSHDF5Constants.VARIANTDEF, myNumTags, myMaxVariants);
aHDF5.createByteMatrix(GBSHDF5Constants.VARIANTPOSOFF, myNumTags, myMaxVariants);
// variantDefs=new byte[myNumTags][];
// variantOffsets=new byte[myNumTags][];
if(!aHDF5.exists(GBSHDF5Constants.VARIANTDEF)) return false;
byte[][] vd=new byte[readBlock][myMaxVariants];
byte[][] vo=new byte[readBlock][myMaxVariants];
for (int blockStep = 0; blockStep < myNumTags; blockStep+=readBlock) {
int blockSize=(myNumTags-blockStep<readBlock)?myNumTags-blockStep:readBlock;
vd=new byte[blockSize][myMaxVariants];
vo=new byte[blockSize][myMaxVariants];
for (int j = 0; j < blockSize; j++) {
for (int v = 0; v < vo[0].length; v++) {
vd[j][v]=aTOPM.getVariantDef(blockStep+j, v);
vo[j][v]=aTOPM.getVariantPosOff(blockStep+j, v);
}
}
aHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTDEF,vd,blockStep,0);
aHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTPOSOFF,vo,blockStep,0);
//byte[] vd=myHDF5.readByteArrayBlockWithOffset(null, i, i)
}
System.out.println("Real Variant Defs:"+howManyDef);
return true;
}
private void cacheMappingInfo(int index) {
if (index == cachedMappingIndex) {
return;
}
int block = index >> BITS_TO_SHIFT_FOR_CHUNK;
if (cachedMappingBlock != block) {
if (cleanMap == false) {
saveCacheBackToFile();
}
for (int mi = 0; mi < maxMapping; mi++) {
cachedTMIBlock[mi] = myHDF5.compounds().readArrayBlock(GBSHDF5Constants.MAPBASE+"0", tmiType, CHUNK_SIZE, block);
cachedMappingBlock = block;
if (cacheAllMappingBlocks == false) {
break;
}
}
}
this.cachedTMI = cachedTMIBlock[0][index % CHUNK_SIZE];
this.cachedMappingIndex = index;
}
private void saveCacheBackToFile() {
int block = cachedMappingIndex >> BITS_TO_SHIFT_FOR_CHUNK;
if (cachedMappingBlock != block) {
for (int mi = 0; mi < maxMapping; mi++) {
if (cleanMap == false) {
myHDF5.compounds().writeArrayBlock(GBSHDF5Constants.MAPBASE+"0", tmiType, cachedTMIBlock[mi], block);
}
if (cacheAllMappingBlocks == false) {
break;
}
}
if (cleanMap == false) {
myHDF5.writeByteArray("multimaps", multimaps);
} //this could be made more efficient by just writing the block
cleanMap = true;
}
}
public void getFileReadyForClosing() {
// writeCachedVariantDefs();
// writeCachedVariantOffsets();
// saveCacheBackToFile();
}
public TagMappingInfo getAlternateTagMappingInfo(int index, int mapIndex) {
if(hasDetailedMapping) return null;
if (cacheAllMappingBlocks == false) {
cacheMappingInfo(index);
}
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
return cachedTMIBlock[mapIndex][index % CHUNK_SIZE];
}
public void setAlternateTagMappingInfo(int index, int mapIndex, TagMappingInfo theTMI) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cacheAllMappingBlocks == false) {
cacheMappingInfo(index);
}
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
cachedTMIBlock[mapIndex][index % CHUNK_SIZE] = theTMI;
if (multimaps[index] >= mapIndex) {
multimaps[index] = (byte) (mapIndex + 1);
}
cleanMap = false;
}
public void swapTagMappingInfo(int index, int mapIndex, int mapIndex2) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cacheAllMappingBlocks == false) {
cacheMappingInfo(index);
}
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
TagMappingInfo tempTMI = cachedTMIBlock[mapIndex][index % CHUNK_SIZE];
cachedTMIBlock[mapIndex][index % CHUNK_SIZE] = cachedTMIBlock[mapIndex2][index % CHUNK_SIZE];
cachedTMIBlock[mapIndex2][index % CHUNK_SIZE] = tempTMI;
cleanMap = false;
}
@Override
public int addVariant(int tagIndex, byte offset, byte base) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public byte getDcoP(int index) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
return cachedTMI.dcoP;
}
@Override
public byte getDivergence(int index) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
return cachedTMI.divergence;
}
@Override
public int getEndPosition(int index) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
return cachedTMI.endPosition;
}
@Override
public byte getMapP(int index) {
if(!hasDetailedMapping) throw new IllegalStateException("Detailed mapping not present");
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
return cachedTMI.mapP;
}
@Override
public int[] getPositionArray(int index) {
if (cachedMappingIndex != index) {
cacheMappingInfo(index);
}
int[] r = {cachedTMI.chromosome, cachedTMI.strand, cachedTMI.startPosition};
return r;
}
@Override
public int getReadIndexForPositionIndex(int posIndex) {
return indicesOfSortByPosition[posIndex];
}
@Override
public int[] getUniquePositions(int chromosome) {
if(myUniquePositions==null) populateChrAndVarPositions();
return myUniquePositions[chromosome];
}
public void setMultimaps(int index, byte multimaps) {
this.multimaps[index] = multimaps;
}
@Override
public void setChromoPosition(int index, int chromosome, byte strand, int positionMin, int positionMax) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setDivergence(int index, byte divergence) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setMapP(int index, byte mapP) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setMapP(int index, double mapP) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public synchronized void setVariantDef(int tagIndex, int variantIndex, byte def) {
myHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTDEF, new byte[][]{{def},}, tagIndex, variantIndex);
variantDefs[tagIndex][variantIndex]=def;
}
@Override
public synchronized void setVariantPosOff(int tagIndex, int variantIndex, byte offset) {
myHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTPOSOFF, new byte[][]{{offset},}, tagIndex, variantIndex);
variantOffsets[tagIndex][variantIndex]=offset;
}
/**
* Preferred method for setting variant information
* @param tagIndex
* @param defAndOffset Two dimension [0=definition, 1=offset][upto 16 bytes for each SNP]
*/
public synchronized void setAllVariantInfo(int tagIndex, byte[][] defAndOffset) {
myHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTDEF, new byte[][]{defAndOffset[0]}, tagIndex, 0);
myHDF5.writeByteMatrixBlockWithOffset(GBSHDF5Constants.VARIANTPOSOFF, new byte[][]{defAndOffset[1]}, tagIndex, 0);
variantDefs[tagIndex]=defAndOffset[1];
variantOffsets[tagIndex]=defAndOffset[1];
}
@Override
public void clearVariants() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package org.apache.camel.component.hdfs.kerberos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.String.format;
public final class HdfsKerberosConfigurationFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(HdfsKerberosConfigurationFactory.class);
private static final String KERBEROS_5_SYS_ENV = "java.security.krb5.conf";
private HdfsKerberosConfigurationFactory() {
// factory class
}
public static void setKerberosConfigFile(String kerberosConfigFileLocation) throws FileNotFoundException {
if (!new File(kerberosConfigFileLocation).exists()) {
throw new FileNotFoundException(format("KeyTab file [%s] could not be found.", kerberosConfigFileLocation));
}
String krb5Conf = System.getProperty(KERBEROS_5_SYS_ENV);
if (krb5Conf == null || !krb5Conf.isEmpty()) {
System.setProperty(KERBEROS_5_SYS_ENV, kerberosConfigFileLocation);
} else if (!krb5Conf.equalsIgnoreCase(kerberosConfigFileLocation)) {
LOGGER.warn("[{}] was already configured with: [{}] config file", KERBEROS_5_SYS_ENV, krb5Conf);
}
}
}
|
package org.eclipse.imp.pdb.facts.impl;
import org.eclipse.imp.pdb.facts.IBool;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.INumber;
import org.eclipse.imp.pdb.facts.IRational;
import org.eclipse.imp.pdb.facts.IReal;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.visitors.IValueVisitor;
import org.eclipse.imp.pdb.facts.visitors.VisitorException;
public class RationalValue extends AbstractNumberValue implements IRational {
public static final Type RATIONAL_TYPE = TypeFactory.getInstance().rationalType();
protected final int PRECISION = 100;
protected final IInteger num;
protected final IInteger denom;
public RationalValue(IInteger num, IInteger denom) {
super(RATIONAL_TYPE);
if(denom.signum() < 0) {
num = num.negate();
denom = denom.negate();
}
// normalize infinites
if(denom.signum() == 0) {
if(num.signum() > 0)
num = intOne();
else if(num.signum() < 0)
num = intOne().negate();
else
throw new ArithmeticException("Illegal fraction 0/0");
}
else if(num.signum() == 0) {
denom = intOne();
}
else {
IInteger gcd = gcd(num, denom);
while(gcd.compare(intOne()) != 0) {
num = num.divide(gcd);
denom = denom.divide(gcd);
gcd = gcd(num, denom);
}
}
this.num = num;
this.denom = denom;
}
public IRational add(IRational other) {
// (num*other.denom + denom*other.num) / denom*other.denom
return toRational(
num.multiply(other.denominator()).add(denom.multiply(other.numerator())),
denom.multiply(other.denominator()));
}
public IReal add(IReal other) {
return toReal().add(other);
}
public INumber add(IInteger other) {
return toRational(num.add(other.multiply(denom)), denom);
}
public IRational subtract(IRational other) {
// (num*other.denom - denom*other.num) / denom*other.denom
return toRational(
num.multiply(other.denominator()).subtract(denom.multiply(other.numerator())),
denom.multiply(other.denominator()));
}
public INumber subtract(IReal other) {
return toReal().subtract(other);
}
public INumber subtract(IInteger other) {
return toRational(num.subtract(other.multiply(denom)), denom);
}
public IRational multiply(IRational other) {
return toRational(num.multiply(other.numerator()),
denom.multiply(other.denominator()));
}
public IReal multiply(IReal other) {
return toReal().add(other);
}
public INumber multiply(IInteger other) {
return toRational(num.multiply(other), denom);
}
// TODO: should we perhaps drop this and only have the other divide?
// or vice-versa?
public IRational divide(IRational other) {
return toRational(num.multiply(other.denominator()),
denom.multiply(other.numerator()));
}
public IReal divide(IReal other, int precision) {
return toReal().divide(other, precision);
}
public IRational divide(IInteger other, int precision) {
return divide(other); // forget precision
}
public IRational divide(IInteger other) {
return toRational(num, denom.multiply(other));
}
public INumber divide(IRational other, int precision) {
return toRational(num.multiply(other.denominator()),
denom.multiply(other.numerator()));
}
public IBool less(IRational other) {
return BoolValue.getBoolValue(compare(other) < 0);
}
public IBool less(IReal other) {
return other.greater(this);
}
public IBool less(IInteger other) {
return less(other.toRational());
}
public IBool greater(IRational other) {
return BoolValue.getBoolValue(compare(other) > 0);
}
public IBool greater(IReal other) {
return other.lessEqual(this);
}
public IBool greater(IInteger other) {
return greater(other.toRational());
}
public IBool equal(IRational other) {
return BoolValue.getBoolValue(compare(other) == 0);
}
public IBool equal(IReal other) {
return other.equal(this);
}
public IBool equal(IInteger other) {
return equal(other.toRational());
}
public IBool lessEqual(IRational other) {
return BoolValue.getBoolValue(compare(other) <= 0);
}
public IBool lessEqual(IReal other) {
return other.greaterEqual(this);
}
public IBool lessEqual(IInteger other) {
return lessEqual(other.toRational());
}
public IBool greaterEqual(IRational other) {
return BoolValue.getBoolValue(compare(other) >= 0);
}
public IBool greaterEqual(IReal other) {
return other.less(this);
}
public IBool greaterEqual(IInteger other) {
return greaterEqual(other.toRational());
}
public boolean isEqual(IValue other) {
return equals(other);
}
public boolean equals(Object o) {
if(o == null) return false;
if(o == this) return true;
if(o.getClass() == getClass()){
RationalValue other = (RationalValue) o;
return num.equals(other.num) && denom.equals(other.denom);
}
return false;
}
public int compare(INumber other) {
if(other.getType().isIntegerType()) {
IInteger div = num.divide(denom);
IInteger rem = num.remainder(denom);
if(div.compare(other) != 0)
return div.compare(other);
else
return rem.signum();
}
else if(other.getType().isRationalType()){
IRational diff = subtract((IRational)other);
return diff.signum();
}
else
return toReal().compare(other);
}
public Type getType() {
return RATIONAL_TYPE;
}
public <T> T accept(IValueVisitor<T> v) throws VisitorException {
return v.visitRational(this);
}
public IRational negate() {
return toRational(num.negate(), denom);
}
public IReal toReal() {
IReal r1 = num.toReal();
IReal r2 = denom.toReal();
r1 = r1.divide(r2, PRECISION);
return r1;
}
public IInteger toInteger() {
return num.divide(denom);
}
public String getStringRepresentation() {
return num.getStringRepresentation() + "r" + (denom.equals(intOne()) ? "" : denom.getStringRepresentation());
}
public int compare(IRational other) {
IRational diff = subtract(other);
return diff.signum();
}
public int signum() {
return num.signum();
}
public IRational abs() {
return toRational(num.abs(), denom);
}
public IInteger floor() {
return num.divide(denom);
}
public IInteger round() {
return toReal().round().toInteger();
}
public IRational toRational() {
return this;
}
public IRational toRational(IInteger n, IInteger d) {
return new RationalValue(n, d);
}
public IRational remainder(IRational other) {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((denom == null) ? 0 : denom.hashCode());
result = prime * result + ((num == null) ? 0 : num.hashCode());
return result;
}
public IInteger numerator() {
return num;
}
public IInteger denominator() {
return denom;
}
public IInteger remainder() {
return num.remainder(denom);
}
protected IInteger gcd(IInteger n, IInteger d) {
n = n.abs();
d = d.abs();
while(d.signum() > 0) {
IInteger tmp = d;
d = n.mod(d);
n = tmp;
}
return n;
}
protected IInteger intOne() {
return IntegerValue.INTEGER_ONE;
}
public double doubleValue() {
return num.doubleValue() / denom.doubleValue();
}
}
|
package org.ensembl.healthcheck.util;
import java.util.logging.*;
import java.util.*;
import org.ensembl.healthcheck.*;
/**
* Logging handler that takes makes a callback to a particular method when a log record is created.
*/
public class CallbackHandler extends Handler {
CallbackTarget callbackTarget;
/** Creates a new instance of CallbackHandler
* @param ct The object on which to call the callback method.
* @param formatter The formatter object to use.
*/
public CallbackHandler(CallbackTarget ct, Formatter formatter) {
callbackTarget = ct;
setFormatter(formatter);
}
/** Close the Handler. Currently a no-op.
* @throws SecurityException N/A.
*/
public void close() throws java.lang.SecurityException {
}
/**
* Flush. Currently a no-op.
*/
public void flush() {
}
/**
* Implementation of the Handler interface publish() method. Called each time a log record is produced.
* In this Handler, the <code>callback</code> method of the CallbackTarget it called with the log message.
* @param logRecord The logRecord to deal with.
*/
public void publish(LogRecord logRecord) {
try {
callbackTarget.callback(logRecord);
} catch (Exception e) {
e.printStackTrace();
}
} // publish
} // CallbackHandler
|
package org.esupportail.smsu.business;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.esupportail.commons.services.database.DatabaseUtils;
import org.esupportail.commons.services.i18n.I18nService;
import org.esupportail.commons.services.ldap.LdapUser;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
import org.esupportail.portal.ws.client.PortalGroup;
import org.esupportail.portal.ws.client.PortalGroupHierarchy;
import org.esupportail.smsu.business.beans.CustomizedMessage;
import org.esupportail.smsu.dao.DaoService;
import org.esupportail.smsu.dao.beans.Account;
import org.esupportail.smsu.dao.beans.BasicGroup;
import org.esupportail.smsu.dao.beans.CustomizedGroup;
import org.esupportail.smsu.dao.beans.Mail;
import org.esupportail.smsu.dao.beans.MailRecipient;
import org.esupportail.smsu.dao.beans.Message;
import org.esupportail.smsu.dao.beans.Person;
import org.esupportail.smsu.dao.beans.Recipient;
import org.esupportail.smsu.dao.beans.Service;
import org.esupportail.smsu.dao.beans.Template;
import org.esupportail.smsu.domain.beans.mail.MailStatus;
import org.esupportail.smsu.domain.beans.message.MessageStatus;
import org.esupportail.smsu.exceptions.BackOfficeUnrichableException;
import org.esupportail.smsu.exceptions.CreateMessageException;
import org.esupportail.smsu.exceptions.InsufficientQuotaException;
import org.esupportail.smsu.exceptions.UnknownIdentifierApplicationException;
import org.esupportail.smsu.exceptions.CreateMessageException.EmptyGroup;
import org.esupportail.smsu.exceptions.ldap.LdapUserNotFoundException;
import org.esupportail.smsu.groups.pags.SmsuPersonAttributesGroupStore;
import org.esupportail.smsu.groups.pags.SmsuPersonAttributesGroupStore.GroupDefinition;
import org.esupportail.smsu.services.client.SendSmsClient;
import org.esupportail.smsu.services.ldap.LdapUtils;
import org.esupportail.smsu.services.scheduler.SchedulerUtils;
import org.esupportail.smsu.services.smtp.SmtpServiceUtils;
import org.esupportail.smsu.web.beans.GroupRecipient;
import org.esupportail.smsu.web.beans.MailToSend;
import org.esupportail.smsu.web.beans.UiRecipient;
/**
* @author xphp8691
*
*/
public class SendSmsManager {
/**
* {@link DaoService}.
*/
private DaoService daoService;
/**
* {@link I18nService}.
*/
private I18nService i18nService;
/**
* link to access to the sms client layer.
*/
private SendSmsClient sendSmsClient;
/**
* the max SMS number before the message has to be validated.
*/
private Integer nbMaxSmsBeforeSupervising;
/**
* the default Supervisor login when the max SMS number is reach.
*/
private String defaultSupervisorLogin;
/**
* {@link SmtpServiceUtils}.
*/
private SmtpServiceUtils smtpServiceUtils;
/**
* {@link LdapUtils}.
*/
private LdapUtils ldapUtils;
/**
* Used to launch task.
*/
private SchedulerUtils schedulerUtils;
/**
* The SMS max size.
*/
private Integer smsMaxSize;
/**
* The default account.
*/
private String defaultAccount;
/**
* used to customize the content.
*/
private ContentCustomizationManager customizer;
/**
* the LDAP Email attribute.
*/
private String userEmailAttribute;
/**
* The pager attributeName.
*/
private String userPagerAttribute;
/**
* The key used to represent the CG in the ldap (up1terms).
*/
private String cgKeyName;
private SmsuPersonAttributesGroupStore smsuPersonAttributesGroupStore;
/**
* attribut used to get user's services
*/
private String userTermsOfUseAttribute;
/**
* Log4j logger.
*/
private final Logger logger = new LoggerImpl(getClass());
// Constructors
/**
* Bean constructor.
*/
public SendSmsManager() {
super();
}
// Pricipal methods
/**
* @param uiRecipients
* @param login
* @param content
* @param smsTemplate
* @param userGroup
* @param serviceId
* @param mailToSend
* @return a message.
* @throws CreateMessageException
*/
public Message createMessage(final List<UiRecipient> uiRecipients,
final String login, final String content, final String smsTemplate,
final String userGroup, final Integer serviceId,
final MailToSend mailToSend) throws CreateMessageException {
Service service = getService(serviceId);
Set<Recipient> recipients = getRecipients(uiRecipients, service);
BasicGroup groupRecipient = getGroupRecipient(uiRecipients);
BasicGroup groupSender = getGroupSender(userGroup);
MessageStatus messageStatus = getWorkflowState(recipients.size(), groupSender, groupRecipient);
Person sender = getSender(login);
// test if customizeExpContent raises a CreateMessageException
customizer.customizeExpContent(content, groupSender.getLabel(), sender.getLogin());
Message message = new Message();
message.setContent(content);
if (smsTemplate != null) message.setTemplate(getMessageTemplate(smsTemplate));
message.setSender(sender);
message.setAccount(getAccount(userGroup));
message.setService(service);
message.setGroupSender(groupSender);
message.setRecipients(recipients);
message.setGroupRecipient(groupRecipient);
message.setStateAsEnum(messageStatus);
message.setSupervisors(mayGetSupervisorsOrNull(message));
if (mailToSend != null) message.setMail(getMail(message, mailToSend));
return message;
}
private Set<Person> mayGetSupervisorsOrNull(Message message) {
if (MessageStatus.WAITING_FOR_APPROVAL.equals(message.getStateAsEnum())) {
logger.debug("Supervisors needed");
return getSupervisors(message);
} else {
logger.debug("No supervisors needed");
return null;
}
}
/**
* @param message
* @return null or an error message (key into i18n properties)
* @throws BackOfficeUnrichableException
* @throws LdapUserNotFoundException
* @throws UnknownIdentifierApplicationException
* @throws InsufficientQuotaException
*/
public String treatMessage(final Message message) {
try {
if (message.getStateAsEnum().equals(MessageStatus.NO_RECIPIENT_FOUND))
return null;
else if (message.getStateAsEnum().equals(MessageStatus.WAITING_FOR_APPROVAL))
// envoi du mail
sendMailsToSupervisors(message.getSupervisors());
else
maySendMessageInBackground(message);
return null;
} catch (UnknownIdentifierApplicationException e) {
message.setStateAsEnum(MessageStatus.WS_ERROR);
daoService.updateMessage(message);
logger.error("Application unknown", e);
return "WS.ERROR.APPLICATION";
} catch (InsufficientQuotaException e) {
message.setStateAsEnum(MessageStatus.WS_QUOTA_ERROR);
daoService.updateMessage(message);
logger.error("Quota error", e);
return "WS.ERROR.QUOTA";
} catch (BackOfficeUnrichableException e) {
message.setStateAsEnum(MessageStatus.WS_ERROR);
daoService.updateMessage(message);
logger.error("Unable connect to the back office", e);
return "WS.ERROR.MESSAGE";
}
}
/**
* Used to send message in state waiting_for_sending.
*/
public void sendWaitingForSendingMessage() {
// get all message ready to be sent
final List<Message> messageList = daoService.getMessagesByState(MessageStatus.WAITING_FOR_SENDING);
if (logger.isDebugEnabled()) {
logger.debug("Found " + messageList.size() + " message(s) to send to the back office");
}
for (Message message : messageList) {
if (logger.isDebugEnabled()) {
logger.debug("Start managment of message with id : " + message.getId());
}
// get the associated customized group
final String groupLabel = message.getGroupSender().getLabel();
final CustomizedGroup cGroup = getRecurciveCustomizedGroupByLabel(groupLabel);
// send the customized messages
for (CustomizedMessage customizedMessage : getCustomizedMessages(message)) {
sendCustomizedMessages(customizedMessage);
cGroup.setConsumedSms(cGroup.getConsumedSms() + 1);
daoService.updateCustomizedGroup(cGroup);
}
// update the message status in DB
message.setStateAsEnum(MessageStatus.SENT);
// force commit to database. do not allow rollback otherwise the message will be sent again!
DatabaseUtils.commit();
DatabaseUtils.begin();
//Deal with the emails
if (message.getMail() != null) {
sendMails(message);
}
daoService.updateMessage(message);
if (logger.isDebugEnabled()) {
logger.debug("End of managment of message with id : " + message.getId());
}
}
}
// Private tools methods
/**
* send mail based on supervisors.
* @param supervisors
* @return
*/
private void sendMailsToSupervisors(final Set<Person> supervisors) {
if (supervisors == null) return;
logger.debug("supervisors not null");
final List<String> uids = new LinkedList<String>();
for (Person supervisor : supervisors) {
uids.add(supervisor.getLogin());
}
List <LdapUser> ldapUsers = ldapUtils.getUsersByUids(uids);
final List<String> toList = new LinkedList<String>();
for (LdapUser ldapUser : ldapUsers) {
if (logger.isDebugEnabled()) {
logger.debug("supervisor login is :" + ldapUser.getId());
}
String mail = ldapUser.getAttribute(userEmailAttribute);
if (mail != null) {
if (logger.isDebugEnabled()) {
logger.debug("mail added to list :" + mail);
}
toList.add(mail);
}
}
String subject = getI18nService().getString("MSG.SUBJECT.MAIL.TO.APPROVAL",
getI18nService().getDefaultLocale());
String textBody = getI18nService().getString("MSG.TEXTBOX.MAIL.TO.APPROVAL",
getI18nService().getDefaultLocale());
smtpServiceUtils.sendMessage(toList, null, subject, textBody);
}
private void maySendMessageInBackground(final Message message) throws BackOfficeUnrichableException, UnknownIdentifierApplicationException, InsufficientQuotaException {
checkBackOfficeQuotas(message);
// message is ready to be sent to the back office
if (logger.isDebugEnabled()) {
logger.debug("Setting to state WAINTING_FOR_SENDING message with ID : " + message.getId());
}
message.setStateAsEnum(MessageStatus.WAITING_FOR_SENDING);
daoService.updateMessage(message);
// launch ASAP the task witch manage the sms sending
schedulerUtils.launchSuperviseSmsSending();
}
/**
* @param message
* @param mailToSend
* @return the mail to apply to a message
*/
private Mail getMail(final Message message, final MailToSend mailToSend) {
String subject = mailToSend.getMailSubject();
logger.debug("create the mail to store SUBJECT : " + subject);
String content = mailToSend.getMailContent();
logger.debug("create the mail to store CONTENT : " + content);
Template template = null;
String idTemplate = mailToSend.getMailTemplate();
if (idTemplate != null) {
logger.debug("create the mail to store TEMPLATE : " + idTemplate);
template = daoService.getTemplateById(Integer.parseInt(idTemplate));
}
Set<MailRecipient> mailRecipients = getMailRecipients(message, mailToSend);
if (mailRecipients.size() == 0) {
return null;
} else {
Mail mail = new Mail();
mail.setSubject(subject);
mail.setContent(content);
mail.setTemplate(template);
mail.setStateAsEnum(MailStatus.WAITING);
mail.setMailRecipients(mailRecipients);
return mail;
}
}
private Set<MailRecipient> getMailRecipients(final Message message, final MailToSend mailToSend) {
final Set<MailRecipient> mailRecipients = new HashSet<MailRecipient>();
if (mailToSend.getIsMailToRecipients()) {
final List<String> uids = new LinkedList<String>();
for (Recipient recipient : message.getRecipients()) {
uids.add(recipient.getLogin());
}
// get all the ldap information in one request
List <LdapUser> ldapUsers = ldapUtils.getUsersByUids(uids);
for (LdapUser ldapUser : ldapUsers) {
String login = ldapUser.getId();
String addresse = ldapUser.getAttribute(userEmailAttribute);
MailRecipient mailRecipient = daoService.getMailRecipientByAddress(addresse);
if (mailRecipient == null) {
mailRecipient = new MailRecipient(null, addresse, login);
} else {
// cas tordu d'un destinataire sans login remont.
if (mailRecipient.getLogin() == null) {
mailRecipient.setLogin(login);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Add mail recipient from sms recipients: " + login + " [" + addresse + "]");
}
mailRecipients.add(mailRecipient);
}
}
for (String otherAdresse : mailToSend.getMailOtherRecipientsList()) {
MailRecipient mailRecipient = daoService.getMailRecipientByAddress(otherAdresse);
if (mailRecipient == null) {
mailRecipient = new MailRecipient(null, otherAdresse, null);
}
if (logger.isDebugEnabled()) {
logger.debug("Add mail recipient from other recipients: [" + otherAdresse + "]");
}
mailRecipients.add(mailRecipient);
}
return mailRecipients;
}
/**
* @param message
*/
public void sendMails(final Message message) {
final Mail mail = message.getMail();
if (logger.isDebugEnabled()) {
logger.debug("sendMails");
}
if (mail == null) return;
if (logger.isDebugEnabled()) {
logger.debug("sendMails mail not null");
}
//retrieve all informations from message (EXP_NOM, ...)
final Set<MailRecipient> recipients = mail.getMailRecipients();
final String expGroupName = message.getGroupSender().getLabel();
final String expUid = message.getSender().getLogin();
final String mailSubject = mail.getSubject();
//the original content
final String originalContent = mail.getContent();
try {
final String contentWithoutExpTags = customizer.customizeExpContent(
originalContent, expGroupName, expUid );
if (logger.isDebugEnabled()) {
logger.debug("sendMails contentWithoutExpTags: "
+ contentWithoutExpTags);
}
for (MailRecipient recipient : recipients) {
//the recipient uid
final String destUid = recipient.getLogin();
//the message is customized with user informations
String customizedContentMail = customizer.customizeDestContent(
contentWithoutExpTags, destUid);
if (logger.isDebugEnabled()) {
logger.debug("sendMails customizedContentMail: "
+ customizedContentMail);
}
String mailAddress = recipient.getAddress();
if (mailAddress != null) {
logger.debug("Mail sent to : " + mailAddress);
smtpServiceUtils.sendOneMessage(mailAddress, mailSubject, customizedContentMail);
}
}
message.getMail().setStateAsEnum(MailStatus.SENT);
} catch (CreateMessageException e) {
logger.error("discarding message with " + e + " (this should not happen, the message should have been checked first!)");
message.getMail().setStateAsEnum(MailStatus.ERROR);
}
}
/**
* @param message
* @return a supervisor list
*/
private Set<Person> getSupervisors(final Message message) {
Set<Person> supervisors = new HashSet<Person>();
if (message.getGroupRecipient() != null) {
String label = message.getGroupRecipient().getLabel();
CustomizedGroup customizedGroup = getSupervisorCustomizedGroupByLabel(label);
if (customizedGroup != null) {
if (logger.isDebugEnabled()) {
logger.debug("Supervisor found from group : [" + customizedGroup.getLabel() + "]");
}
supervisors.addAll(customizedGroup.getSupervisors());
} else {
if (logger.isDebugEnabled()) {
logger.debug("No supervisor found from groups. Use the default supervisor : [" + defaultSupervisorLogin + "]");
}
Person admin = daoService.getPersonByLogin(defaultSupervisorLogin);
if (admin == null) {
admin = new Person(null, defaultSupervisorLogin);
}
supervisors.add(admin);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Supervisor needed without a group. Use the default supervisor : [" + defaultSupervisorLogin + "]");
}
Person admin = daoService.getPersonByLogin(defaultSupervisorLogin);
if (admin == null) {
admin = new Person(null, defaultSupervisorLogin);
}
supervisors.add(admin);
}
return supervisors;
}
/**
* @param groupLabel
* @return the current customized group if it has supervisors or the first parent with supervisors.
*/
private CustomizedGroup getSupervisorCustomizedGroupByLabel(final String groupLabel) {
if (logger.isDebugEnabled()) {
logger.debug("getSupervisorCustomizedGroupByLabel for group [" + groupLabel + "]");
}
CustomizedGroup customizedGroup = getRecurciveCustomizedGroupByLabel(groupLabel);
if (customizedGroup != null) {
if (customizedGroup.getSupervisors().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Customized group without supervisor found : [" + customizedGroup.getLabel() + "]");
}
String portalGroupId = customizedGroup.getLabel();
String parentGroup = ldapUtils.getParentGroupIdByGroupId(portalGroupId);
if (parentGroup != null) {
customizedGroup = getRecurciveCustomizedGroupByLabel(parentGroup);
} else {
// if no parent group is found, a null customized group is returned.
customizedGroup = null;
}
}
}
return customizedGroup;
}
/**
* @param uiRecipients
* @return the recipients list.
* @throws EmptyGroup
*/
private Set<Recipient> getRecipients(final List<UiRecipient> uiRecipients, final Service service) throws EmptyGroup {
Set<Recipient> recipients = new HashSet<Recipient>();
// determines all the recipients.
for (UiRecipient uiRecipient : uiRecipients) {
// single users and phone numbers can be directly added to the message.
if (!uiRecipient.getClass().equals(GroupRecipient.class)) {
// check if the recipient is already in the database.
Recipient recipient = daoService.getRecipientByPhone(uiRecipient.getPhone());
if (recipient == null) {
recipient = new Recipient(null, uiRecipient.getPhone(), uiRecipient.getLogin());
daoService.addRecipient(recipient);
}
recipients.add(recipient);
} else {
String serviceKey = service != null ? service.getKey() : null;
// Group users are search from the portal.
String groupName = uiRecipient.getDisplayName();
List<LdapUser> groupUsers = getUsersByGroup(groupName,serviceKey);
// users are filtered to keep only service compliant ones.
List<LdapUser> filteredUsers = filterUsers(groupUsers, serviceKey);
if (filteredUsers.isEmpty())
throw new CreateMessageException.EmptyGroup(groupName);
//users are added to the recipient list.
for (LdapUser ldapUser : filteredUsers) {
String phone = ldapUser.getAttribute(userPagerAttribute);
Recipient recipient = daoService.getRecipientByPhone(phone);
if (recipient == null) {
recipient = new Recipient(null, phone,
ldapUser.getId());
daoService.addRecipient(recipient);
}
recipients.add(recipient);
}
}
}
return recipients;
}
/**
* @param groupName
* @param serviceKey
* @return the user list.
*/
public List<LdapUser> getUsersByGroup(final String groupName, String serviceKey) {
if (logger.isDebugEnabled()) {
logger.debug("Search users for group [" + groupName + "]");
}
//get the recipient group hierarchy
PortalGroupHierarchy groupHierarchy = ldapUtils.getPortalGroupHierarchyByGroupName(groupName);
//get all users from the group hierarchy
List<LdapUser> members = getMembers(groupHierarchy, serviceKey);
logger.info("Found " + members.size() + " ldap users in group " + groupName);
return members;
}
/**
* @param groupHierarchy
* @param serviceKey
* @return the list of the unique sub-members of a group (recursive)
*/
private List<LdapUser> getMembers(final PortalGroupHierarchy groupHierarchy, String serviceKey) {
final PortalGroup currentGroup = groupHierarchy.getGroup();
if (logger.isDebugEnabled()) {
logger.debug("Search users for subgroup [" + currentGroup.getName()
+ "] [" + currentGroup.getId() + "]");
}
List<LdapUser> members = getMembersNonRecursive(currentGroup, serviceKey);
List<PortalGroupHierarchy> childs = groupHierarchy.getSubHierarchies();
if (childs != null) {
for (PortalGroupHierarchy child : childs)
members = mergeUserLists(members, getMembers(child, serviceKey));
}
return members;
}
private List<LdapUser> getMembersNonRecursive(final PortalGroup currentGroup, String serviceKey) {
List<LdapUser> members = new LinkedList<LdapUser>();
//get the corresponding ldap group to extract members
try {
String idFromPortal = currentGroup.getId();
String groupStoreId = StringUtils.split(idFromPortal,".")[1];
GroupDefinition gd = smsuPersonAttributesGroupStore.getGroupDefinition(groupStoreId);
if (gd != null) {
if (logger.isDebugEnabled()) {
logger.debug("search members");
}
members = ldapUtils.getMembers(gd, userTermsOfUseAttribute, serviceKey);
} else {
if (logger.isDebugEnabled()) {
logger.debug("No group definition found");
}
}
} catch (Throwable e) {
logger.debug(e.getMessage());
}
return members;
}
/**
* @param source
* @param toMerge
* @return the merged list
*/
private List<LdapUser> mergeUserLists(final List<LdapUser> source, final List<LdapUser> toMerge) {
final List<LdapUser> finalList = source;
for (LdapUser sToMerge : toMerge) {
if (!finalList.contains(sToMerge)) {
finalList.add(sToMerge);
if (logger.isDebugEnabled()) {
logger.debug("Element [" + sToMerge + "] merged to the source list");
}
}
}
return finalList;
}
/**
* @param service
* @return the filtered list of users
*/
private List<LdapUser> filterUsers(final List<LdapUser> users, final String service) {
if (logger.isDebugEnabled()) logger.debug("Filtering users for service [" + service + "]");
List<LdapUser> filteredUsers = new ArrayList<LdapUser>();
for (LdapUser user : users) {
List<String> userTermsOfUse = user.getAttributes(userTermsOfUseAttribute);
if (userTermsOfUse.contains(cgKeyName)) {
if (service != null) {
if (logger.isDebugEnabled()) logger.debug("Service filter activated");
if (userTermsOfUse.contains(service)) {
filteredUsers.add(user);
}
} else {
if (logger.isDebugEnabled()) logger.debug("No service filter");
filteredUsers.add(user);
}
} else {
if (logger.isDebugEnabled()) logger.debug("CG not validated, user : " + user.getId());
}
}
if (logger.isDebugEnabled()) logger.debug("Number of filtered users : " + filteredUsers.size());
return filteredUsers;
}
/**
* get the message template.
*/
private Template getMessageTemplate(final String strTemplate) {
Integer iTemplate = Integer.parseInt(strTemplate);
return daoService.getTemplateById(iTemplate);
}
/**
* get the message sender.
*/
private Person getSender(final String strLogin) {
Person sender = daoService.getPersonByLogin(strLogin);
if (sender == null) {
sender = new Person();
sender.setLogin(strLogin);
}
return sender;
}
/**
* @return the message workflow state.
* @throws CreateMessageException
*/
private MessageStatus getWorkflowState(final Integer nbRecipients, BasicGroup groupSender, BasicGroup groupRecipient) throws CreateMessageException {
if (logger.isDebugEnabled()) logger.debug("get workflow state");
if (logger.isDebugEnabled()) logger.debug("nbRecipients: " + nbRecipients);
final CustomizedGroup cGroup = getRecurciveCustomizedGroupByLabel(groupSender.getLabel());
if (nbRecipients.equals(0)) {
return MessageStatus.NO_RECIPIENT_FOUND;
} else if (!checkFrontOfficeQuota(nbRecipients, cGroup, groupSender)) {
throw new CreateMessageException.GroupQuotaException();
} else if (!checkMaxSmsGroupQuota(nbRecipients, cGroup, groupSender)) {
throw new CreateMessageException.GroupMaxSmsPerMessage();
} else if (nbRecipients >= nbMaxSmsBeforeSupervising || groupRecipient != null) {
return MessageStatus.WAITING_FOR_APPROVAL;
} else {
return MessageStatus.IN_PROGRESS;
}
}
/**
* @param uiRecipients
* @return the recipient group, or null.
*/
private BasicGroup getGroupRecipient(final List<UiRecipient> uiRecipients) {
if (logger.isDebugEnabled()) logger.debug("get recipient group");
for (UiRecipient uiRecipient : uiRecipients) {
if (uiRecipient.getClass().equals(GroupRecipient.class)) {
String label = uiRecipient.getDisplayName();
PortalGroup pGroup = ldapUtils.getPortalGroupByName(label);
String portalId = pGroup.getId();
BasicGroup groupRecipient = daoService.getGroupByLabel(portalId);
if (groupRecipient == null) {
groupRecipient = new BasicGroup();
groupRecipient.setLabel(portalId);
}
return groupRecipient;
}
}
return null;
}
/**
* Customized the messages.
* @param message
* @return
*/
private List<CustomizedMessage> getCustomizedMessages(final Message message) {
final Set<Recipient> recipients = message.getRecipients();
final String senderUid = message.getSender().getLogin();
String contentWithoutExpTags = null;
try {
contentWithoutExpTags = customizer.customizeExpContent(message.getContent(),
message.getGroupSender().getLabel(), senderUid);
if (logger.isDebugEnabled()) logger.debug("contentWithoutExpTags: " + contentWithoutExpTags);
} catch (CreateMessageException e) {
logger.error("discarding message with error " + e + " (this should not happen, the message should have been checked first!)");
}
final List<CustomizedMessage> customizedMessageList = new ArrayList<CustomizedMessage>();
if (contentWithoutExpTags != null) {
for (Recipient recipient : recipients) {
CustomizedMessage c = getCustomizedMessage(message, contentWithoutExpTags, recipient);
customizedMessageList.add(c);
}
}
return customizedMessageList;
}
private CustomizedMessage getCustomizedMessage(final Message message,
final String contentWithoutExpTags, Recipient recipient) {
//the message is customized with user informations
String msgContent = customizer.customizeDestContent(contentWithoutExpTags, recipient.getLogin());
if (msgContent.length() > smsMaxSize) {
msgContent = msgContent.substring(0, smsMaxSize);
}
// create the final message with all data needed to send it
final CustomizedMessage customizedMessage = new CustomizedMessage();
customizedMessage.setMessageId(message.getId());
customizedMessage.setSenderId(message.getSender().getId());
customizedMessage.setGroupSenderId(message.getGroupSender().getId());
customizedMessage.setServiceId(message.getService() != null ? message.getService().getId() : null);
customizedMessage.setUserAccountLabel(message.getAccount().getLabel());
customizedMessage.setRecipiendPhoneNumber(recipient.getPhone());
customizedMessage.setMessage(msgContent);
return customizedMessage;
}
/**
* Send the customized message to the back office.
* @param customizedMessage
*/
private void sendCustomizedMessages(final CustomizedMessage customizedMessage) {
final Integer messageId = customizedMessage.getMessageId();
final Integer senderId = customizedMessage.getSenderId();
final Integer groupSenderId = customizedMessage.getGroupSenderId();
final Integer serviceId = customizedMessage.getServiceId();
final String recipiendPhoneNumber = customizedMessage.getRecipiendPhoneNumber();
final String userLabelAccount = customizedMessage.getUserAccountLabel();
final String message = customizedMessage.getMessage();
if (logger.isDebugEnabled()) {
logger.debug("Sending to back office message with : " +
" - message id = " + messageId +
" - sender id = " + senderId +
" - group sender id = " + groupSenderId +
" - service id = " + serviceId +
" - recipient phone number = " + recipiendPhoneNumber +
" - user label account = " + userLabelAccount +
" - message = " + message);
}
// send the message to the back office
sendSmsClient.sendSMS(messageId, senderId, groupSenderId, serviceId,
recipiendPhoneNumber, userLabelAccount, message);
}
private Boolean checkMaxSmsGroupQuota(final Integer nbToSend, final CustomizedGroup cGroup, final BasicGroup groupSender) {
final Long quotaOrder = cGroup.getQuotaOrder();
if (nbToSend <= quotaOrder) {
return true;
} else {
final String mess =
"Erreur de nombre maximum de sms par envoi pour le groupe d'envoi [" +
groupSender.getLabel() +
"] et groupe associ [" + cGroup.getLabel() +
"]. Essai d'envoi de " + nbToSend + " message(s), nombre max par envoi = " + quotaOrder;
logger.warn(mess);
return false;
}
}
/**
* @return true if the quota is OK
*/
private Boolean checkFrontOfficeQuota(final Integer nbToSend, final CustomizedGroup cGroup, final BasicGroup groupSender) {
if (logger.isDebugEnabled()) {
final String mess =
"Vrification du quota front office pour le groupe d'envoi [" +
groupSender.getLabel() +
"] et groupe associ [" + cGroup.getLabel() +
"]. Essai d'envoi de " + nbToSend + " message(s), quota = " + cGroup.getQuotaSms() +
" , consomm = " + cGroup.getConsumedSms();
logger.warn(mess);
}
if (cGroup.checkQuotaSms(nbToSend)) {
logger.debug("checkFrontOfficeQuota : ok");
return true;
} else {
final String mess =
"Erreur de quota pour le groupe d'envoi [" + groupSender.getLabel() +
"] et groupe associ [" + cGroup.getLabel() + "]. Essai d'envoi de " + nbToSend +
" message(s), quota = " + cGroup.getQuotaSms() + " , consomm = " + cGroup.getConsumedSms();
logger.warn(mess);
return false;
}
}
/**
* @return quotasOk
*/
private void checkBackOfficeQuotas(final Message message)
throws BackOfficeUnrichableException, UnknownIdentifierApplicationException,
InsufficientQuotaException {
/////check the quotas with the back office/////
Integer nbToSend = message.getRecipients().size();
String accountLabel = message.getAccount().getLabel();
checkBackOfficeQuotas(nbToSend, accountLabel);
}
private void checkBackOfficeQuotas(final Integer nbToSend, final String accountLabel)
throws BackOfficeUnrichableException, UnknownIdentifierApplicationException,
InsufficientQuotaException {
try {
if (logger.isDebugEnabled()) {
logger.debug("Request for WS SendSms method isQuotaOk with parameters \n"
+ "nbToSend = " + nbToSend + "\n"
+ "accountLabel = " + accountLabel);
}
sendSmsClient.mayCreateAccountCheckQuotaOk(nbToSend, accountLabel);
if (logger.isDebugEnabled()) {
logger.debug("checkQuotaOk: quota is ok to send all our messages");
}
} catch (UnknownIdentifierApplicationException e) {
throw new UnknownIdentifierApplicationException(e.getMessage());
} catch (InsufficientQuotaException e) {
throw new InsufficientQuotaException(e.getMessage());
} catch (Exception e) {
logger.error("Unable to connect to the back office : ", e);
throw new BackOfficeUnrichableException();
}
}
/**
* @param userGroup
* @return the sender group.
*/
private BasicGroup getGroupSender(final String userGroup) {
// the sender group is set
BasicGroup basicGroupSender = daoService.getGroupByLabel(userGroup);
if (basicGroupSender == null) {
basicGroupSender = new BasicGroup();
basicGroupSender.setLabel(userGroup);
}
return basicGroupSender;
}
/**
* @param userGroup
* @return an account.
*/
private Account getAccount(final String userGroup) {
CustomizedGroup groupSender = getRecurciveCustomizedGroupByLabel(userGroup);
Account count;
if (groupSender == null) {
//Default account
logger.warn("No account found. The default account is used : " + defaultAccount);
count = daoService.getAccountByLabel(defaultAccount);
} else {
count = groupSender.getAccount();
}
// the account is set
return count;
}
/**
* @param groupId
* @return the customized group corresponding to a group
*/
private CustomizedGroup getRecurciveCustomizedGroupByLabel(final String portalGroupId) {
if (logger.isDebugEnabled()) {
logger.debug("Search the cutomised group associated to the group : [" + portalGroupId + "]");
}
//search the customized group from the data base
CustomizedGroup groupSender = daoService.getCustomizedGroupByLabel(portalGroupId);
if (groupSender == null) {
if (logger.isDebugEnabled()) {
logger.debug("Customized group not found : " + portalGroupId);
}
//get the parent group
String parentGroup = ldapUtils.getParentGroupIdByGroupId(portalGroupId);
if (parentGroup != null) {
//if a parent group is found, search the corresponding customized group
groupSender = getRecurciveCustomizedGroupByLabel(parentGroup);
}
}
return groupSender;
}
/**
* @param id
* @return the service.
*/
private Service getService(final Integer id) {
if (id != null)
return daoService.getServiceById(id);
else
return null;
}
// Getter and Setter of smsMaxSize
/**
* @param smsMaxSize
*/
public void setSmsMaxSize(final Integer smsMaxSize) {
this.smsMaxSize = smsMaxSize;
}
/**
* @return smsMaxSize
*/
public Integer getSmsMaxSize() {
return smsMaxSize;
}
// setters for spring objects
/**
* @param sendSmsClient
*/
public void setSendSmsClient(final SendSmsClient sendSmsClient) {
this.sendSmsClient = sendSmsClient;
}
/**
* Standard setter used by spring.
* @param schedulerUtils
*/
public void setSchedulerUtils(final SchedulerUtils schedulerUtils) {
this.schedulerUtils = schedulerUtils;
}
/**
* Standard setter used by spring.
* @param smtpServiceUtils
*/
public void setSmtpServiceUtils(final SmtpServiceUtils smtpServiceUtils) {
this.smtpServiceUtils = smtpServiceUtils;
}
/**
* Standard setter used by spring.
* @param ldapUtils
*/
public void setLdapUtils(final LdapUtils ldapUtils) {
this.ldapUtils = ldapUtils;
}
// Getter and Setter of i18nService
/**
* Set the i18nService.
* @param i18nService
*/
public void setI18nService(final I18nService i18nService) {
this.i18nService = i18nService;
}
/**
* @return the i18nService.
*/
public I18nService getI18nService() {
return i18nService;
}
// Getter and Setter of defaultSupervisorLogin
/**
* @return the defaultSupervisorLogin.
*/
public String getDefaultSupervisorLogin() {
return defaultSupervisorLogin;
}
/**
* @param defaultSupervisorLogin
*/
public void setDefaultSupervisorLogin(final String defaultSupervisorLogin) {
this.defaultSupervisorLogin = defaultSupervisorLogin;
}
// Getter and Setter of daoService
/**
* @return the daoService.
*/
public DaoService getDaoService() {
return daoService;
}
/**
* @param daoService
*/
public void setDaoService(final DaoService daoService) {
this.daoService = daoService;
}
// Getter and Setter of nbMaxSmsBeforeSupervising
/**
* @return nbMaxSmsBeforeSupervising
*/
public Integer getNbMaxSmsBeforeSupervising() {
return nbMaxSmsBeforeSupervising;
}
/**
* @param nbMaxSmsBeforeSupervising
*/
public void setNbMaxSmsBeforeSupervising(final Integer nbMaxSmsBeforeSupervising) {
this.nbMaxSmsBeforeSupervising = nbMaxSmsBeforeSupervising;
}
// Getter and Setter of customizer
/**
* @param customizer
*/
public void setCustomizer(final ContentCustomizationManager customizer) {
this.customizer = customizer;
}
/**
* @return the ContentCustomizationManager
*/
public ContentCustomizationManager getCustomizer() {
return customizer;
}
// Setter of defaultAccount
/**
* @param defaultAccount
*/
public void setDefaultAccount(final String defaultAccount) {
this.defaultAccount = defaultAccount;
}
/**
* @return userEmailAttribute
*/
public String getUserEmailAttribute() {
return userEmailAttribute;
}
/**
* @param userEmailAttribute
*/
public void setUserEmailAttribute(final String userEmailAttribute) {
this.userEmailAttribute = userEmailAttribute;
}
public void setSmsuPersonAttributesGroupStore(
final SmsuPersonAttributesGroupStore smsuPersonAttributesGroupStore) {
this.smsuPersonAttributesGroupStore = smsuPersonAttributesGroupStore;
}
public SmsuPersonAttributesGroupStore getSmsuPersonAttributesGroupStore() {
return smsuPersonAttributesGroupStore;
}
/**
* @return the cg Key Name
*/
public String getCgKeyName() {
return cgKeyName;
}
/**
* @param cgKeyName
*/
public void setCgKeyName(final String cgKeyName) {
this.cgKeyName = cgKeyName;
}
public void setUserPagerAttribute(final String userPagerAttribute) {
this.userPagerAttribute = userPagerAttribute;
}
public String getUserPagerAttribute() {
return userPagerAttribute;
}
/**
* @param userTermsOfUseAttribute to set
*/
public void setUserTermsOfUseAttribute(final String userTermsOfUseAttribute) {
this.userTermsOfUseAttribute = userTermsOfUseAttribute;
}
}
|
package org.eclipse.birt.data.engine.olap.data.impl.facttable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.olap.OLAPException;
import javax.olap.cursor.CubeCursor;
import javax.olap.cursor.EdgeCursor;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.DataEngine;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.impl.DataEngineImpl;
import org.eclipse.birt.data.engine.impl.StopSign;
import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults;
import org.eclipse.birt.data.engine.olap.api.IPreparedCubeQuery;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IDimensionDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IEdgeDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IHierarchyDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IMeasureDefinition;
import org.eclipse.birt.data.engine.olap.data.api.cube.DocManagerMap;
import org.eclipse.birt.data.engine.olap.data.api.cube.DocManagerReleaser;
import org.eclipse.birt.data.engine.olap.data.api.cube.IDatasetIterator;
import org.eclipse.birt.data.engine.olap.data.api.cube.IHierarchy;
import org.eclipse.birt.data.engine.olap.data.api.cube.ILevelDefn;
import org.eclipse.birt.data.engine.olap.data.document.DocumentManagerFactory;
import org.eclipse.birt.data.engine.olap.data.document.IDocumentManager;
import org.eclipse.birt.data.engine.olap.data.impl.Cube;
import org.eclipse.birt.data.engine.olap.data.impl.dimension.Dimension;
import org.eclipse.birt.data.engine.olap.data.impl.dimension.DimensionFactory;
import org.eclipse.birt.data.engine.olap.data.impl.dimension.LevelDefinition;
import org.eclipse.birt.data.engine.olap.data.util.DataType;
import org.eclipse.birt.data.engine.olap.impl.query.CubeQueryDefinition;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.*;
public class TestTimeDimension {
private static final String OUTPUT_FOLDER = "DtETestTempDataoutput";
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
/*
* @see TestCase#tearDown()
*/
private static String[] distinct( String[] sValues )
{
Arrays.sort( sValues );
List tempList = new ArrayList( );
tempList.add( sValues[0] );
for ( int i = 1; i < sValues.length; i++ )
{
if ( !sValues[i].equals( sValues[i - 1] ) )
{
tempList.add( sValues[i] );
}
}
String[] result = new String[tempList.size( )];
for ( int i = 0; i < result.length; i++ )
{
result[i] = (String)tempList.get( i );
}
return result;
}
@Ignore("Ignoring since TimeDimension is not currently used if the product is used in a normal way")
@Test
public void testTimeDimension( ) throws Exception
{
String cubeName = "cube";
DataEngineImpl engine = (DataEngineImpl)DataEngine.newDataEngine( createPresentationContext( ) );
IDocumentManager documentManager = DocumentManagerFactory
.createFileDocumentManager(engine.getSession().getTempDir());
DocManagerMap.getDocManagerMap( )
.set( String.valueOf( engine.hashCode( ) ),
engine.getSession( ).getTempDir( )
+ engine.getSession( ).getEngine( ).hashCode( ),
documentManager );
engine.addShutdownListener( new DocManagerReleaser( engine ) );
createCube( documentManager );
ICubeQueryDefinition cqd = new CubeQueryDefinition( cubeName );
IEdgeDefinition columnEdge = cqd.createEdge( ICubeQueryDefinition.COLUMN_EDGE );
IEdgeDefinition rowEdge = cqd.createEdge( ICubeQueryDefinition.ROW_EDGE );
IDimensionDefinition dim1 = columnEdge.createDimension( "dimension1" );
IHierarchyDefinition hier1 = dim1.createHierarchy( "dimension1" );
hier1.createLevel( "l1" );
IDimensionDefinition dim2 = rowEdge.createDimension( "dimension2" );
IHierarchyDefinition hier2 = dim2.createHierarchy( "dimension2" );
hier2.createLevel( "year" );
hier2.createLevel( "month" );
hier2.createLevel( "day" );
IMeasureDefinition measure = cqd.createMeasure( "m1" );
measure.setAggrFunction( "SUM" );
IBinding binding1 = new Binding( "edge1level1" );
binding1.setExpression( new ScriptExpression( "dimension[\"dimension1\"][\"l1\"]" ) );
cqd.addBinding( binding1 );
IBinding binding2 = new Binding( "edge2level1" );
binding2.setExpression( new ScriptExpression( "dimension[\"dimension2\"][\"year\"]" ) );
cqd.addBinding( binding2 );
IBinding binding4 = new Binding( "edge2level2" );
binding4.setExpression( new ScriptExpression( "dimension[\"dimension2\"][\"month\"]" ) );
cqd.addBinding( binding4 );
IBinding binding41 = new Binding( "edge2level3" );
binding41.setExpression( new ScriptExpression( "dimension[\"dimension2\"][\"day\"]" ) );
cqd.addBinding( binding41 );
IBinding binding5 = new Binding( "measure1" );
binding5.setExpression( new ScriptExpression( "measure[\"m1\"]" ) );
cqd.addBinding( binding5 );
IFilterDefinition filter = new FilterDefinition( new ConditionalExpression( "dimension[\"dimension2\"][\"day\"]",
IConditionalExpression.OP_LE,
"13" ) );
cqd.addFilter( filter );
IPreparedCubeQuery pcq = engine.prepare( cqd, null );
ICubeQueryResults queryResults = pcq.execute( null, null );
CubeCursor cursor = queryResults.getCubeCursor( );
List columnEdgeBindingNames = new ArrayList( );
columnEdgeBindingNames.add( "edge1level1" );
List rowEdgeBindingNames = new ArrayList( );
rowEdgeBindingNames.add( "edge2level1" );
rowEdgeBindingNames.add( "edge2level2" );
rowEdgeBindingNames.add( "edge2level3" );
this.printCube( cursor,
columnEdgeBindingNames,
rowEdgeBindingNames,
"measure1" );
engine.shutdown( );
documentManager.close( );
}
protected static String getTempDir()
{
return getOutputFolder( ).getAbsolutePath( ) + File.separator + "DataEngineSessionTemp" + File.separator;
}
/** return output folder */
protected static File getOutputFolder()
{
return new File( new File(System.getProperty("java.io.tmpdir")),
OUTPUT_FOLDER );
}
private DataEngineContext createPresentationContext( ) throws BirtException
{
DataEngineContext context = DataEngineContext.newInstance( DataEngineContext.DIRECT_PRESENTATION,
null,
null,
null );
context.setTmpdir( this.getTempDir( ) );
return context;
}
private void createCube( IDocumentManager documentManager ) throws IOException, BirtException
{
Dimension[] dimensions = new Dimension[2];
ILevelDefn[] levelDefs = new ILevelDefn[1];
IDatasetIterator iterator = new Dataset2( );
levelDefs[0] = new LevelDefinition( "l1", new String[]{"l1"}, null );
dimensions[0] = (Dimension) DimensionFactory.createDimension( "dimension1", documentManager, iterator, levelDefs, false, new StopSign() );
IHierarchy hierarchy = dimensions[0].getHierarchy( );
assertEquals( hierarchy.getName( ), "dimension1" );
iterator = new Dataset2( );
levelDefs[0] = new LevelDefinition( "l2", new String[]{"l2"}, null );
dimensions[1] = (Dimension) DimensionFactory.createDimension( "dimension2", documentManager, iterator, levelDefs, true, new StopSign() );
hierarchy = dimensions[1].getHierarchy( );
assertEquals( hierarchy.getName( ), "dimension2" );
Cube cube = new Cube( "cube", documentManager );
cube.create( new String[][]{ new String[]{ "l1" }, new String[]{ "l2" } },
dimensions,
new Dataset2( ),
new String[]{ "m1" },
new StopSign( ) );
cube.close( );
documentManager.flush( );
}
private void printCube( CubeCursor cursor, List columnEdgeBindingNames,
List rowEdgeBindingNames, String measureBindingNames )
throws Exception
{
this.printCube( cursor,
columnEdgeBindingNames,
rowEdgeBindingNames,
measureBindingNames,
null,
null,
null );
}
private void printCube( CubeCursor cursor, List columnEdgeBindingNames,
List rowEdgeBindingNames, String measureBindingNames,
String columnAggr, String rowAggr, String overallAggr )
throws Exception
{
this.printCube( cursor, columnEdgeBindingNames,
rowEdgeBindingNames, measureBindingNames,
columnAggr, rowAggr, overallAggr, true );
}
private void printCube( CubeCursor cursor, List columnEdgeBindingNames,
List rowEdgeBindingNames, String measureBindingNames,
String columnAggr, String rowAggr, String overallAggr, boolean checkOutput )
throws Exception
{
String output = getOutputFromCursor( cursor,
columnEdgeBindingNames,
rowEdgeBindingNames,
measureBindingNames,
columnAggr,
rowAggr,
overallAggr );
System.out.println( output );
close( cursor );
}
private void close( CubeCursor dataCursor ) throws OLAPException
{
for ( int i = 0; i < dataCursor.getOrdinateEdge( ).size( ); i++ )
{
EdgeCursor edge = (EdgeCursor) ( dataCursor.getOrdinateEdge( ).get( i ) );
edge.close( );
}
dataCursor.close( );
}
private void printCube( CubeCursor cursor, List columnEdgeBindingNames,
List rowEdgeBindingNames, String measureBindingName,
String[] columnAggrs)
throws Exception
{
String output = getOutputFromCursor(
cursor,
columnEdgeBindingNames,
rowEdgeBindingNames,
measureBindingName,
columnAggrs);
}
private String getOutputFromCursor( CubeCursor cursor,
List columnEdgeBindingNames, List rowEdgeBindingNames,
String measureBindingName, String[] columnAggrs
) throws OLAPException
{
EdgeCursor edge1 = (EdgeCursor) ( cursor.getOrdinateEdge( ).get( 0 ) );
EdgeCursor edge2 = (EdgeCursor) ( cursor.getOrdinateEdge( ).get( 1 ) );
String[] lines = new String[columnEdgeBindingNames.size( )];
for ( int i = 0; i < columnEdgeBindingNames.size( ); i++ )
{
lines[i] = " ";
}
while ( edge1.next( ) )
{
for ( int i = 0; i < columnEdgeBindingNames.size( ); i++ )
{
lines[i] += cursor.getObject( columnEdgeBindingNames.get( i )
.toString( ) )
+ " ";
}
}
String output = "";
for ( int i = 0; i < lines.length; i++ )
{
output += "\n" + lines[i];
}
while ( edge2.next( ) )
{
String line = "";
for ( int i = 0; i < rowEdgeBindingNames.size( ); i++ )
{
line += cursor.getObject( rowEdgeBindingNames.get( i )
.toString( ) ).toString( )
+ " ";
}
edge1.beforeFirst( );
while ( edge1.next( ) )
{
line += cursor.getObject( measureBindingName ) + " ";
}
output += "\n" + line;
}
String line = "total" + " ";
edge1.beforeFirst( );
edge2.first( );
while( edge1.next( ) )
{
line+= cursor.getObject( "total" )+ " ";
}
output +="\n" + line;
line = "maxTotal1" + " ";
edge1.beforeFirst( );
edge2.first( );
while (edge1.next( ))
{
line+= cursor.getObject( "maxTotal1" )+ " ";
}
output +="\n" + line;
line = "maxTotal2" + " ";
edge1.beforeFirst( );
edge2.first( );
while (edge1.next( ))
{
line+= cursor.getObject( "maxTotal2" )+ " ";
}
output +="\n" + line;
line = "sumTotal1" + " ";
edge1.beforeFirst( );
edge2.first( );
while( edge1.next( ) )
{
line+= cursor.getObject( "sumTotal1" )+ " ";
}
output +="\n" + line;
line = "sumTotal2" + " ";
edge1.beforeFirst( );
edge2.first( );
while( edge1.next( ) )
{
line+= cursor.getObject( "sumTotal2" )+ " ";
}
output +="\n" + line;
line = "sumSumTotal1" + " ";
edge1.beforeFirst( );
edge2.first( );
while( edge1.next( ) )
{
line+= cursor.getObject( "sumSumTotal1" )+ " ";
}
output +="\n" + line + "";
return output;
}
private String getOutputFromCursor( CubeCursor cursor,
List columnEdgeBindingNames, List rowEdgeBindingNames,
String measureBindingNames, String columnAggr, String rowAggr,
String overallAggr ) throws OLAPException
{
EdgeCursor edge1 = (EdgeCursor) ( cursor.getOrdinateEdge( ).get( 0 ) );
EdgeCursor edge2 = (EdgeCursor) ( cursor.getOrdinateEdge( ).get( 1 ) );
String[] lines = new String[columnEdgeBindingNames.size( )];
for ( int i = 0; i < columnEdgeBindingNames.size( ); i++ )
{
lines[i] = " ";
}
while ( edge1.next( ) )
{
for ( int i = 0; i < columnEdgeBindingNames.size( ); i++ )
{
lines[i] += cursor.getObject( columnEdgeBindingNames.get( i )
.toString( ) )
+ " ";
}
}
if ( rowAggr != null )
lines[lines.length - 1] += "Total";
String output = "";
for ( int i = 0; i < lines.length; i++ )
{
output += "\n" + lines[i];
}
while ( edge2.next( ) )
{
String line = "";
for ( int i = 0; i < rowEdgeBindingNames.size( ); i++ )
{
line += cursor.getObject( rowEdgeBindingNames.get( i )
.toString( ) ).toString( )
+ " ";
}
edge1.beforeFirst( );
while ( edge1.next( ) )
{
line += cursor.getObject( measureBindingNames ) + " ";
}
if ( rowAggr != null )
line += cursor.getObject( rowAggr );
output += "\n" + line;
}
if ( columnAggr != null )
{
String line = "Total" + " ";
edge1.beforeFirst( );
while ( edge1.next( ) )
{
line += cursor.getObject( columnAggr ) + " ";
}
if ( overallAggr != null )
line += cursor.getObject( overallAggr );
output += "\n" + line;
}
return output;
}
}
class Dataset2 implements IDatasetIterator
{
int ptr = -1;
static int[] L1Col = {
1, 1, 2, 2, 3, 3
};
static Date[] L2Col = {
(new java.util.GregorianCalendar(1998, 10 ,13)).getTime(),
(new java.util.GregorianCalendar(1999, 10 ,14)).getTime(),
(new java.util.GregorianCalendar(1999, 10 ,11)).getTime(),
(new java.util.GregorianCalendar(1999, 11 ,1)).getTime(),
(new java.util.GregorianCalendar(2000, 12 ,8)).getTime(),
(new java.util.GregorianCalendar(2000, 1 ,9)).getTime()
};
public void close( ) throws BirtException
{
// TODO Auto-generated method stub
}
public Boolean getBoolean( int fieldIndex ) throws BirtException
{
// TODO Auto-generated method stub
return null;
}
public Date getDate( int fieldIndex ) throws BirtException
{
// TODO Auto-generated method stub
return null;
}
public Double getDouble( int fieldIndex ) throws BirtException
{
// TODO Auto-generated method stub
return null;
}
public int getFieldIndex( String name ) throws BirtException
{
if ( name.equals( "l1" ) )
{
return 0;
}
else if ( name.equals( "l2" ) )
{
return 1;
}
else if ( name.equals( "m1" ) )
{
return 2;
}
return -1;
}
public int getFieldType( String name ) throws BirtException
{
if ( name.equals( "l1" ) )
{
return DataType.INTEGER_TYPE;
}
else if ( name.equals( "l2" ) )
{
return DataType.DATE_TYPE;
}
else if ( name.equals( "m1" ) )
{
return DataType.INTEGER_TYPE;
}
return -1;
}
public Integer getInteger( int fieldIndex ) throws BirtException
{
// TODO Auto-generated method stub
return null;
}
public String getString( int fieldIndex ) throws BirtException
{
// TODO Auto-generated method stub
return null;
}
public Object getValue( int fieldIndex ) throws BirtException
{
if ( fieldIndex == 0 )
{
return new Integer( L1Col[ptr] );
}
else if ( fieldIndex == 1 )
{
return L2Col[ptr];
}
else if ( fieldIndex == 2 )
{
return L1Col[ptr] + 1;
}
return null;
}
public boolean next( ) throws BirtException
{
ptr++;
if ( ptr >= L1Col.length )
{
return false;
}
return true;
}
}
|
package org.gamefolk.roomfullofcats;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import com.adsdk.sdk.IdentifierUtility;
import com.arcadeoftheabsurd.absurdengine.DeviceUtility;
import com.arcadeoftheabsurd.absurdengine.GameActivity;
import com.arcadeoftheabsurd.absurdengine.SoundManager;
import com.arcadeoftheabsurd.absurdengine.Sprite;
public class CatsGameActivity extends GameActivity
{
private LinearLayout contentView;
private CatsGame gameView;
private CatsAd adView;
private Thread loaderThread;
private class SplashView extends View
{
private Sprite logo;
public SplashView(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
}
@Override
protected void onSizeChanged(int newWidth, int newHeight, int oldWidth, int oldHeight) {
logo = Sprite.fromResource(getResources(), R.drawable.gamefolklogo, newWidth, newWidth);
logo.setLocation(0, (newHeight - logo.getHeight()) / 2);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (logo != null) {
logo.draw(canvas);
}
super.onDraw(canvas);
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
final CatsMenu catsMenu = new CatsMenu(this, new OnClickListener() {
public void onClick(View arg0) {
try {
loaderThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
startGame();
}
}, null);
SplashView splashView = new SplashView(this);
splashView.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setContentView(catsMenu);
loadGame();
}
});
setContentView(splashView);
}
private void loadGame() {
System.out.println("checking ad services");
IdentifierUtility.requireAdService(this);
System.out.println("ad services available");
System.out.println("getting device info...");
DeviceUtility.setUserAgent(this);
loaderThread = new Thread(new Runnable() {
public void run() {
SoundManager.initializeSound(getAssets(), CatsGame.NUM_CHANNELS);
DeviceUtility.setLocalIp();
try {
IdentifierUtility.setAdId();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
loaderThread.start();
}
protected CatsGame initializeGame() {
gameView = new CatsGame(this, this);
return gameView;
}
@SuppressWarnings("deprecation")
protected LinearLayout initializeContentView() {
adView = new CatsAd(this);
contentView = new LinearLayout(this);
contentView.setOrientation(LinearLayout.VERTICAL);
contentView.addView(gameView.scoreView, new LayoutParams(LayoutParams.FILL_PARENT, 0, .05f));
contentView.addView(gameView, new LayoutParams(LayoutParams.FILL_PARENT, 0, .80f));
contentView.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, 0, .15f));
return contentView;
}
private void startGame() {
System.out.println("finished loading!");
System.out.println("ip: " + DeviceUtility.getLocalIp());
System.out.println("ad id: " + IdentifierUtility.getAdId());
System.out.println("user agent: " + DeviceUtility.getUserAgent());
// call initializeGame and initializeContentView on the main thread, starting the game
loadContent();
}
}
|
//$HeadURL$
package org.deegree.commons.processors;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.commons.annotations.PackageLoggingNotes;
import org.deegree.commons.utils.io.RollbackPrintWriter;
import org.slf4j.Logger;
/**
* <code>LoggingAnnotationProcessor</code>
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@SupportedAnnotationTypes(value = { "org.deegree.commons.annotations.PackageLoggingNotes",
"org.deegree.commons.annotations.LoggingNotes" })
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedOptions({ "log4j.outputdir" })
public class LoggingAnnotationProcessor extends AbstractProcessor {
private static final Logger LOG = getLogger( LoggingAnnotationProcessor.class );
private String outDir;
private int width = 120;
@Override
public void init( ProcessingEnvironment env ) {
super.init( env );
outDir = env.getOptions().get( "log4j.outputdir" );
if ( outDir == null ) {
outDir = System.getProperty( "java.io.tmpdir" ) + "/log4j/";
LOG.info( "Outputting log4j snippets to '{}'.", outDir );
}
File parentFile = new File( outDir );
if ( !parentFile.exists() && !parentFile.mkdirs() ) {
LOG.warn( "Target directory could not be created: {}", parentFile );
}
}
// breaks the lines at max width
String format( String str ) {
StringBuilder res = new StringBuilder();
outer: while ( str.length() > ( width - 3 ) ) {
int len = 3;
res.append( "
while ( len < width && str.length() > 0 ) {
int idx = str.indexOf( " " );
if ( idx == -1 ) {
if ( len > 3 ) {
res.append( "\n
}
res.append( str );
str = "";
} else {
if ( len + idx + 1 > width ) {
res.append( "\n" );
continue outer;
}
res.append( str.substring( 0, idx + 1 ) );
str = str.substring( idx + 1 );
len += idx + 1;
}
}
if ( !str.isEmpty() ) {
res.append( "\n" );
}
}
if ( !str.isEmpty() ) {
res.append( "## " + str );
}
return res.toString();
}
private void find( Element e, Tree root ) {
LoggingNotes notes = e.getAnnotation( LoggingNotes.class );
PackageLoggingNotes pnotes = e.getAnnotation( PackageLoggingNotes.class );
// the #toString apparently yields the qname, is there another way?
String qname = e.toString();
if ( notes != null || pnotes != null ) {
root.insert( qname, pnotes, notes );
}
for ( Element e2 : e.getEnclosedElements() ) {
find( e2, root );
}
}
void block( String text, RollbackPrintWriter out, boolean big ) {
if ( big ) {
out.print( "
for ( int i = 0; i < width - 2; ++i ) {
out.print( "=" );
}
out.println();
}
int odd = text.length() % 2;
int len = ( width - text.length() - 4 ) / 2;
out.print( "
for ( int i = 0; i < len; ++i ) {
out.print( "=" );
}
out.print( " " + text + " " );
for ( int i = 0; i < len + odd; ++i ) {
out.print( "=" );
}
out.println();
if ( big ) {
out.print( "
for ( int i = 0; i < width - 2; ++i ) {
out.print( "=" );
}
out.println();
}
out.println();
}
@Override
public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv ) {
try {
Tree tree = new Tree();
for ( Element e : roundEnv.getRootElements() ) {
find( e, tree );
}
if ( tree.children.isEmpty() ) {
return true;
}
FileOutputStream fos = new FileOutputStream( new File( outDir, "error" ) );
PrintWriter pw = new PrintWriter( new OutputStreamWriter( fos, "UTF-8" ) );
RollbackPrintWriter out = new RollbackPrintWriter( pw );
tree.print( out, "", true, false, false, false, false );
out.close();
pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( new File( outDir, "warn" ) ), "UTF-8" ) );
out = new RollbackPrintWriter( pw );
tree.print( out, "", false, true, false, false, false );
out.close();
pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( new File( outDir, "info" ) ), "UTF-8" ) );
out = new RollbackPrintWriter( pw );
tree.print( out, "", false, false, true, false, false );
out.close();
pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( new File( outDir, "debug" ) ), "UTF-8" ) );
out = new RollbackPrintWriter( pw );
tree.print( out, "", false, false, false, true, false );
out.close();
pw = new PrintWriter( new OutputStreamWriter( new FileOutputStream( new File( outDir, "trace" ) ), "UTF-8" ) );
out = new RollbackPrintWriter( pw );
tree.print( out, "", false, false, false, false, true );
out.close();
return true;
} catch ( UnsupportedEncodingException e ) {
e.printStackTrace();
} catch ( FileNotFoundException e ) {
e.printStackTrace();
}
return false;
}
class Tree {
PackageLoggingNotes pnotes;
LoggingNotes notes;
TreeMap<String, Tree> children = new TreeMap<String, Tree>();
void insert( String qname, PackageLoggingNotes pnotes, LoggingNotes notes ) {
LinkedList<String> pkgs = new LinkedList<String>( Arrays.asList( qname.split( "\\." ) ) );
Tree node = this;
while ( true ) {
String next = pkgs.poll();
Tree nextNode = node.children.get( next );
if ( nextNode == null ) {
nextNode = new Tree();
// nextNode.segment = next;
node.children.put( next, nextNode );
}
node = nextNode;
if ( pkgs.isEmpty() ) {
node.notes = notes;
node.pnotes = pnotes;
break;
}
}
}
void print( RollbackPrintWriter out, String qname, boolean error, boolean warn, boolean info, boolean debug,
boolean trace ) {
if ( notes != null ) {
handleNotes( out, qname, error, warn, info, debug, trace );
}
if ( pnotes != null ) {
handlePackageNotes( out, qname, error, warn, info, debug, trace );
}
for ( Entry<String, Tree> entry : children.entrySet() ) {
entry.getValue().print( out, qname + ( qname.isEmpty() ? "" : "." ) + entry.getKey(), error, warn,
info, debug, trace );
}
out.rollback();
}
private void handleNotes( RollbackPrintWriter out, String qname, boolean error, boolean warn, boolean info,
boolean debug, boolean trace ) {
handleNote( out, error, notes.error(), qname, "ERROR" );
handleNote( out, warn, notes.warn(), qname, "WARN" );
handleNote( out, info, notes.info(), qname, "INFO" );
handleNote( out, debug, notes.debug(), qname, "DEBUG" );
handleNote( out, trace, notes.trace(), qname, "TRACE" );
}
private void handlePackageNotes( RollbackPrintWriter out, String qname, boolean error, boolean warn,
boolean info, boolean debug, boolean trace ) {
String title = pnotes.title();
boolean isSubsystem = qname.replaceAll( "[^\\.]", "" ).length() == 2;
if ( !title.isEmpty() ) {
block( title, out, isSubsystem );
}
handleNote( out, error, pnotes.error(), qname, "ERROR" );
handleNote( out, warn, pnotes.warn(), qname, "WARN" );
handleNote( out, info, pnotes.info(), qname, "INFO" );
handleNote( out, debug, pnotes.debug(), qname, "DEBUG" );
handleNote( out, trace, pnotes.trace(), qname, "TRACE" );
}
private void handleNote( RollbackPrintWriter out, boolean level, String note, String qname, String levelName ) {
if ( !note.isEmpty() && level ) {
out.println( format( note ) );
out.println( "#log4j.logger." + qname + " = " + levelName );
out.println();
out.flush();
}
}
}
}
|
package org.helioviewer.jhv.base.scale;
import org.helioviewer.jhv.astronomy.Position;
import org.helioviewer.jhv.math.MathUtils;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
public interface GridTransform {
Vec2 transform(Position viewpoint, Vec3 pt, GridScale scale);
Vec3 transformInverse(Quat frame, Vec2 pt);
GridTransform transformpolar = new GridTransformPolar();
GridTransform transformlatitudinal = new GridTransformLatitudinal();
class GridTransformPolar implements GridTransform {
@Override
public Vec2 transform(Position viewpoint, Vec3 pt, GridScale scale) {
Quat q = new Quat(viewpoint.lat, 0);
pt = q.rotateInverseVector(pt);
double r = Math.sqrt(pt.x * pt.x + pt.y * pt.y);
double theta = Math.atan2(-pt.x, -pt.y);
theta += 2 * Math.PI;
theta %= 2 * Math.PI;
double scaledr = scale.getYValueInv(r);
double scaledtheta = scale.getXValueInv(theta * MathUtils.radeg);
return new Vec2(scaledtheta, scaledr);
}
@Override
public Vec3 transformInverse(Quat frame, Vec2 pt) {
double r = pt.y;
double theta = -pt.x * MathUtils.degra;
double y = r * Math.cos(theta);
double x = r * Math.sin(theta);
double z = Math.sqrt(Math.max(0, 1 - x * x - y * y));
return frame.rotateInverseVector(new Vec3(x, y, z));
}
}
class GridTransformLatitudinal implements GridTransform {
@Override
public Vec2 transform(Position viewpoint, Vec3 pt, GridScale scale) {
double theta = Math.asin(-pt.y);
double phi = Math.atan2(pt.x, pt.z);
double scaledphi = scale.getXValueInv(phi * MathUtils.radeg);
double scaledtheta = scale.getYValueInv(theta * MathUtils.radeg);
return new Vec2(scaledphi, scaledtheta);
}
@Override
public Vec3 transformInverse(Quat frame, Vec2 pt) {
double phi = MathUtils.mapToMinus180To180(pt.x) * MathUtils.degra;
double theta = pt.y * MathUtils.degra;
return frame.rotateInverseVector(new Vec3(Math.cos(theta) * Math.sin(phi), Math.sin(theta), Math.cos(theta) * Math.cos(phi)));
}
}
}
|
package org.jitsi.videobridge;
import java.beans.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.media.rtp.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.CandidateType;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
import org.ice4j.*;
import org.ice4j.ice.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.socket.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.transform.dtls.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.util.Logger;
import org.jitsi.videobridge.eventadmin.*;
import org.osgi.framework.*;
/**
* Implements the Jingle ICE-UDP transport.
*
* @author Lyubomir Marinov
* @author Pawel Domas
* @author Boris Grozev
*/
public class IceUdpTransportManager
extends TransportManager
{
/**
* The name default of the single <tt>IceStream</tt> that this
* <tt>TransportManager</tt> will create/use.
*/
private static final String DEFAULT_ICE_STREAM_NAME = "stream";
/**
* Contains the name of the property flag that may indicate that AWS address
* harvesting should be explicitly disabled.
*/
private static final String DISABLE_AWS_HARVESTER
= "org.jitsi.videobridge.DISABLE_AWS_HARVESTER";
/**
* The name of the property which disables the use of a
* <tt>MultiplexingTcpHostHarvester</tt>.
*/
private static final String DISABLE_TCP_HARVESTER
= "org.jitsi.videobridge.DISABLE_TCP_HARVESTER";
/**
* The name of the property which controls the port number used for
* <tt>SinglePortUdpHarvester</tt>s.
*/
private static final String SINGLE_PORT_HARVESTER_PORT
= "org.jitsi.videobridge.SINGLE_PORT_HARVESTER_PORT";
/**
* Contains the name of the property flag that may indicate that AWS address
* harvesting should be forced without first trying to auto detect it.
*/
private static final String FORCE_AWS_HARVESTER
= "org.jitsi.videobridge.FORCE_AWS_HARVESTER";
/**
* The <tt>Logger</tt> used by the <tt>IceUdpTransportManager</tt> class and
* its instances to print debug information.
*/
private static final Logger logger
= Logger.getLogger(IceUdpTransportManager.class);
/**
* Contains the name of the property that would tell us if we should use
* address mapping as one of our NAT traversal options as well as the local
* address that we should be mapping.
*/
private static final String NAT_HARVESTER_LOCAL_ADDRESS
= "org.jitsi.videobridge.NAT_HARVESTER_LOCAL_ADDRESS";
/**
* Contains the name of the property that would tell us if we should use
* address mapping as one of our NAT traversal options as well as the public
* address that we should be using in addition to our local one.
*/
private static final String NAT_HARVESTER_PUBLIC_ADDRESS
= "org.jitsi.videobridge.NAT_HARVESTER_PUBLIC_ADDRESS";
/**
* The default port that the <tt>MultiplexingTcpHostHarvester</tt> will
* bind to.
*/
private static final int TCP_DEFAULT_PORT = 443;
/**
* The port on which the <tt>MultiplexingTcpHostHarvester</tt> will bind to
* if no port is specifically configured, and binding to
* <tt>DEFAULT_TCP_PORT</tt> fails (for example, if the process doesn't have
* the required privileges to bind to a port below 1024).
*/
private static final int TCP_FALLBACK_PORT = 4443;
/**
* The name of the property which specifies an additional port to be
* advertised by the TCP harvester.
*/
private static final String TCP_HARVESTER_MAPPED_PORT
= "org.jitsi.videobridge.TCP_HARVESTER_MAPPED_PORT";
/**
* The name of the property which controls the port to which the
* <tt>MultiplexingTcpHostHarvester</tt> will bind.
*/
private static final String TCP_HARVESTER_PORT
= "org.jitsi.videobridge.TCP_HARVESTER_PORT";
/**
* The name of the property which controls the use of ssltcp candidates by
* <tt>MultiplexingTcpHostHarvester</tt>.
*/
private static final String TCP_HARVESTER_SSLTCP
= "org.jitsi.videobridge.TCP_HARVESTER_SSLTCP";
/**
* The default value of the <tt>TCP_HARVESTER_SSLTCP</tt> property.
*/
private static final boolean TCP_HARVESTER_SSLTCP_DEFAULT = true;
/**
* The single <tt>MultiplexingTcpHostHarvester</tt> instance for the
* application.
*/
private static MultiplexingTcpHostHarvester tcpHostHarvester = null;
/**
* The <tt>SinglePortUdpHarvester</tt>s which will be appended to ICE
* <tt>Agent</tt>s managed by <tt>IceUdpTransportManager</tt> instances.
*/
private static List<SinglePortUdpHarvester> singlePortHarvesters = null;
/**
* The flag which indicates whether application-wide harvesters, stored
* in the static fields {@link #tcpHostHarvester} and
* {@link #singlePortHarvesters} have been initialized.
*/
private static boolean staticHarvestersInitialized = false;
/**
* The "mapped port" added to {@link #tcpHostHarvester}, or -1.
*/
private static int tcpHostHarvesterMappedPort = -1;
/**
* Logs a specific <tt>String</tt> at debug level.
*
* @param s the <tt>String</tt> to log at debug level
*/
private static void logd(String s)
{
logger.info(s);
}
/**
* The single (if any) <tt>Channel</tt> instance, whose sockets are
* currently configured to accept DTLS packets.
*/
private Channel channelForDtls = null;
/**
* Whether this <tt>TransportManager</tt> has been closed.
*/
private boolean closed = false;
/**
* The <tt>Conference</tt> object that this <tt>TransportManager</tt> is
* associated with.
*/
private final Conference conference;
/**
* The <tt>Thread</tt> used by this <tt>TransportManager</tt> to wait until
* {@link #iceAgent} has established a connection.
*/
private Thread connectThread;
/**
* Used to synchronize access to {@link #connectThread}.
*/
private final Object connectThreadSyncRoot = new Object();
/**
* The <tt>DtlsControl</tt> that this <tt>TransportManager</tt> uses.
*/
private final DtlsControlImpl dtlsControl;
/**
* The <tt>AbstractRTPConnector</tt> which this transport manager creates
* for the purposes of DTLS.
*/
private AbstractRTPConnector rtpConnector;
/**
* The <tt>Agent</tt> which implements the ICE protocol and which is used
* by this instance to implement the Jingle ICE-UDP transport.
*/
private Agent iceAgent;
/**
* The <tt>PropertyChangeListener</tt> which is (to be) notified about
* changes in the <tt>state</tt> of {@link #iceAgent}.
*/
private final PropertyChangeListener iceAgentStateChangeListener
= new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent ev)
{
iceAgentStateChange(ev);
}
};
/**
* Whether ICE connectivity has been established.
*/
private boolean iceConnected = false;
/**
* The <tt>IceMediaStream</tt> of {@link #iceAgent} associated with the
* <tt>Channel</tt> of this instance.
*/
private final IceMediaStream iceStream;
/**
* The <tt>PropertyChangeListener</tt> which is (to be) notified about
* changes in the properties of the <tt>CandidatePair</tt>s of
* {@link #iceStream}.
*/
private final PropertyChangeListener iceStreamPairChangeListener
= new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent ev)
{
iceStreamPairChange(ev);
}
};
/**
* Whether this <tt>IceUdpTransportManager</tt> will serve as the the
* controlling or controlled ICE agent.
*/
private final boolean isControlling;
/**
* The number of {@link org.ice4j.ice.Component}-s to create in
* {@link #iceStream}.
*/
private int numComponents;
/**
* Whether we're using rtcp-mux or not.
*/
private boolean rtcpmux = false;
/**
* The <tt>SctpConnection</tt> instance, if any, added as a <tt>Channel</tt>
* to this <tt>IceUdpTransportManager</tt>.
*
* Currently we support a single <tt>SctpConnection</tt> in one
* <tt>IceUdpTransportManager</tt> and if it exists, it will receive all
* DTLS packets.
*/
private SctpConnection sctpConnection = null;
/**
* Initializes a new <tt>IceUdpTransportManager</tt> instance.
*
* @param conference the <tt>Conference</tt> which created this
* <tt>TransportManager</tt>.
* @param isControlling whether the new instance is to server as a
* controlling or controlled ICE agent.
* @throws IOException
*/
public IceUdpTransportManager(Conference conference,
boolean isControlling)
throws IOException
{
this(conference, isControlling, 2, DEFAULT_ICE_STREAM_NAME);
}
public IceUdpTransportManager(Conference conference,
boolean isControlling,
int numComponents)
throws IOException
{
this(conference, isControlling, numComponents, DEFAULT_ICE_STREAM_NAME);
}
public IceUdpTransportManager(Conference conference,
boolean isControlling,
int numComponents,
String iceStreamName)
throws IOException
{
super();
this.conference = conference;
this.numComponents = numComponents;
this.rtcpmux = numComponents == 1;
this.isControlling = isControlling;
this.dtlsControl = new DtlsControlImpl(false);
dtlsControl.registerUser(this);
iceAgent = createIceAgent(isControlling, iceStreamName, rtcpmux);
iceAgent.addStateChangeListener(iceAgentStateChangeListener);
iceStream = iceAgent.getStream(iceStreamName);
iceStream.addPairChangeListener(iceStreamPairChangeListener);
EventAdmin eventAdmin
= conference.getVideobridge().getEventAdmin();
if (eventAdmin != null)
{
eventAdmin.sendEvent(EventFactory.transportCreated(this));
}
}
public IceUdpTransportManager(Conference conference,
boolean isControlling,
String iceStreamName)
throws IOException
{
this(conference, isControlling, 2, iceStreamName);
}
/**
* {@inheritDoc}
*
* Assures that no more than one <tt>SctpConnection</tt> is added. Keeps
* {@link #sctpConnection} and {@link #channelForDtls} up to date.
*/
@Override
public boolean addChannel(Channel channel)
{
if (closed)
return false;
if (channel instanceof SctpConnection
&& sctpConnection != null
&& sctpConnection != channel)
{
logd("Not adding a second SctpConnection to TransportManager.");
return false;
}
if (!super.addChannel(channel))
return false;
if (channel instanceof SctpConnection)
{
// When an SctpConnection is added, it automatically replaces
// channelForDtls, because it needs DTLS packets for the application
// data inside them.
sctpConnection = (SctpConnection) channel;
if (channelForDtls != null)
{
/*
* channelForDtls is necessarily an RtpChannel, because we don't
* add more than one SctpConnection. The SctpConnection socket
* will automatically accept DTLS.
*/
RtpChannel rtpChannelForDtls = (RtpChannel) channelForDtls;
rtpChannelForDtls.getDatagramFilter(false).setAcceptNonRtp(
false);
rtpChannelForDtls.getDatagramFilter(true).setAcceptNonRtp(
false);
}
channelForDtls = sctpConnection;
}
else if (channelForDtls == null)
{
channelForDtls = channel;
RtpChannel rtpChannel = (RtpChannel) channel;
// The new channelForDtls will always accept DTLS packets on its
// RTP socket.
rtpChannel.getDatagramFilter(false).setAcceptNonRtp(true);
// If we use rtcpmux, we don't want to accept DTLS packets on the
// RTCP socket, because they will be duplicated from the RTP socket,
// because both sockets are actually filters on the same underlying
// socket.
rtpChannel.getDatagramFilter(true).setAcceptNonRtp(!rtcpmux);
}
if (iceConnected)
channel.transportConnected();
EventAdmin eventAdmin
= conference.getVideobridge().getEventAdmin();
if (eventAdmin != null)
{
eventAdmin.sendEvent(EventFactory.transportChannelAdded(channel));
}
return true;
}
/**
* Adds to <tt>iceAgent</tt> videobridge specific candidate harvesters such
* as an Amazon AWS EC2 specific harvester.
*
* @param iceAgent the {@link Agent} that we'd like to append new harvesters
* to.
* @param rtcpmux whether rtcp will be used by this
* <tt>IceUdpTransportManager</tt>.
*/
private void appendVideobridgeHarvesters(Agent iceAgent,
boolean rtcpmux)
{
boolean enableDynamicHostHarvester = true;
if (rtcpmux)
{
initializeStaticHarvesters();
if (tcpHostHarvester != null)
iceAgent.addCandidateHarvester(tcpHostHarvester);
if (singlePortHarvesters != null)
{
for (CandidateHarvester harvester : singlePortHarvesters)
{
iceAgent.addCandidateHarvester(harvester);
enableDynamicHostHarvester = false;
}
}
}
// Use dynamic ports iff we're not sing "single port".
iceAgent.setUseHostHarvester(enableDynamicHostHarvester);
AwsCandidateHarvester awsHarvester = null;
//does this look like an Amazon AWS EC2 machine?
if(AwsCandidateHarvester.smellsLikeAnEC2())
awsHarvester = new AwsCandidateHarvester();
ConfigurationService cfg
= ServiceUtils.getService(
getBundleContext(),
ConfigurationService.class);
//if no configuration is found then we simply log and bail
if (cfg == null)
{
logger.info("No configuration found. "
+ "Will continue without custom candidate harvesters");
return;
}
//now that we have a conf service, check if AWS use is forced and
//comply if necessary.
if (awsHarvester == null
&& cfg.getBoolean(FORCE_AWS_HARVESTER, false))
{
//ok. this doesn't look like an EC2 machine but since you
//insist ... we'll behave as if it is.
logger.info("Forcing use of AWS candidate harvesting.");
awsHarvester = new AwsCandidateHarvester();
}
//append the AWS harvester for AWS machines.
if( awsHarvester != null
&& !cfg.getBoolean(DISABLE_AWS_HARVESTER, false))
{
logger.info("Appending an AWS harvester to the ICE agent.");
iceAgent.addCandidateHarvester(awsHarvester);
}
//if configured, append a mapping harvester.
String localAddressStr = cfg.getString(NAT_HARVESTER_LOCAL_ADDRESS);
String publicAddressStr = cfg.getString(NAT_HARVESTER_PUBLIC_ADDRESS);
if (localAddressStr == null || publicAddressStr == null)
return;
TransportAddress localAddress;
TransportAddress publicAddress;
try
{
// port 9 is "discard", but the number here seems to be ignored.
localAddress
= new TransportAddress(localAddressStr, 9, Transport.UDP);
publicAddress
= new TransportAddress(publicAddressStr, 9, Transport.UDP);
logger.info("Will append a NAT harvester for " +
localAddress + "=>" + publicAddress);
}
catch(Exception exc)
{
logger.info("Failed to create a NAT harvester for"
+ " local address=" + localAddressStr
+ " and public address=" + publicAddressStr);
return;
}
MappingCandidateHarvester natHarvester
= new MappingCandidateHarvester(publicAddress, localAddress);
iceAgent.addCandidateHarvester(natHarvester);
}
/**
* Determines whether at least one <tt>LocalCandidate</tt> of a specific ICE
* <tt>Component</tt> can reach (in the terms of the ice4j library) a
* specific <tt>RemoteCandidate</tt>
*
* @param component the ICE <tt>Component</tt> which contains the
* <tt>LocalCandidate</tt>s to check whether at least one of them can reach
* the specified <tt>remoteCandidate</tt>
* @param remoteCandidate the <tt>RemoteCandidate</tt> to check whether at
* least one of the <tt>LocalCandidate</tt>s of the specified
* <tt>component</tt> can reach it
* @return <tt>true</tt> if at least one <tt>LocalCandidate</tt> of the
* specified <tt>component</tt> can reach the specified
* <tt>remoteCandidate</tt>
*/
private boolean canReach(
Component component,
RemoteCandidate remoteCandidate)
{
for (LocalCandidate localCandidate : component.getLocalCandidates())
{
if (localCandidate.canReach(remoteCandidate))
return true;
}
return false;
}
/**
* {@inheritDoc}
* TODO: in the case of multiple <tt>Channel</tt>s in one TransportManager
* it is not clear how to handle changes to the 'initiator' property
* from individual channels.
*/
@Override
protected void channelPropertyChange(PropertyChangeEvent ev)
{
super.channelPropertyChange(ev);
/*
if (Channel.INITIATOR_PROPERTY.equals(ev.getPropertyName())
&& (iceAgent != null))
{
Channel channel = (Channel) ev.getSource();
iceAgent.setControlling(channel.isInitiator());
}
*/
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void close()
{
if (!closed)
{
// Set this early to prevent double closing when the last channel
// is removed.
closed = true;
for (Channel channel : getChannels())
close(channel);
if (dtlsControl != null)
{
dtlsControl.start(null); //stop
dtlsControl.cleanup(this);
}
if (rtpConnector != null)
{
rtpConnector.close();
rtpConnector = null;
}
//DatagramSocket[] datagramSockets = getStreamConnectorSockets();
if (iceStream != null)
{
iceStream.removePairStateChangeListener(
iceStreamPairChangeListener);
}
if (iceAgent != null)
{
iceAgent.removeStateChangeListener(iceAgentStateChangeListener);
iceAgent.free();
iceAgent = null;
}
/*
* It seems that the ICE agent takes care of closing these
if (datagramSockets != null)
{
if (datagramSockets[0] != null)
datagramSockets[0].close();
if (datagramSockets[1] != null)
datagramSockets[1].close();
}
*/
synchronized (connectThreadSyncRoot)
{
if (connectThread != null)
connectThread.interrupt();
}
super.close();
}
}
/**
* {@inheritDoc}
*
* Keeps {@link #sctpConnection} and {@link #channelForDtls} up to date.
*/
@Override
public boolean close(Channel channel)
{
boolean removed = super.close(channel);
if (removed)
{
if (channel == sctpConnection)
{
sctpConnection = null;
}
if (channel == channelForDtls)
{
if (sctpConnection != null)
{
channelForDtls = sctpConnection;
}
else if (channel instanceof RtpChannel)
{
RtpChannel newChannelForDtls = null;
for (Channel c : getChannels())
{
if (c instanceof RtpChannel)
newChannelForDtls = (RtpChannel) c;
}
if (newChannelForDtls != null)
{
newChannelForDtls.getDatagramFilter(false)
.setAcceptNonRtp(true);
newChannelForDtls.getDatagramFilter(true)
.setAcceptNonRtp(!rtcpmux);
}
channelForDtls = newChannelForDtls;
}
if (channel instanceof RtpChannel)
{
RtpChannel rtpChannel = (RtpChannel) channel;
rtpChannel.getDatagramFilter(false).setAcceptNonRtp(false);
rtpChannel.getDatagramFilter(true).setAcceptNonRtp(false);
}
}
try
{
StreamConnector connector = channel.getStreamConnector();
if (connector != null)
{
DatagramSocket datagramSocket = connector.getDataSocket();
if (datagramSocket != null)
datagramSocket.close();
datagramSocket = connector.getControlSocket();
if (datagramSocket != null)
datagramSocket.close();
Socket socket = connector.getDataTCPSocket();
if (socket != null)
socket.close();
socket = connector.getControlTCPSocket();
if (socket != null)
socket.close();
}
}
catch (IOException ioe)
{
logd(
"Failed to close sockets when closing a channel:"
+ ioe);
}
EventAdmin eventAdmin
= conference.getVideobridge().getEventAdmin();
if (eventAdmin != null)
{
eventAdmin.sendEvent(
EventFactory.transportChannelRemoved(channel));
}
channel.transportClosed();
}
if (getChannels().isEmpty())
close();
return removed;
}
/**
* Initializes a new <tt>Agent</tt> instance which implements the ICE
* protocol and which is to be used by this instance to implement the Jingle
* ICE-UDP transport.
*
* @return a new <tt>Agent</tt> instance which implements the ICE protocol
* and which is to be used by this instance to implement the Jingle ICE-UDP
* transport
* @throws IOException if initializing a new <tt>Agent</tt> instance for the
* purposes of this <tt>TransportManager</tt> fails
*/
private Agent createIceAgent(boolean isControlling,
String iceStreamName,
boolean rtcpmux)
throws IOException
{
NetworkAddressManagerService nams
= ServiceUtils.getService(
getBundleContext(), NetworkAddressManagerService.class);
Agent iceAgent = nams.createIceAgent();
//add videobridge specific harvesters such as a mapping and an Amazon
//AWS EC2 harvester
appendVideobridgeHarvesters(iceAgent, rtcpmux);
iceAgent.setControlling(isControlling);
iceAgent.setPerformConsentFreshness(true);
PortTracker portTracker
= JitsiTransportManager.getPortTracker(null);
int portBase = portTracker.getPort();
IceMediaStream iceStream
= nams.createIceStream(
numComponents,
portBase,
iceStreamName,
iceAgent);
// Attempt to minimize subsequent bind retries.
try
{
portTracker.setNextPort(
1 + iceStream.getComponent(
numComponents > 1 ? Component.RTCP : Component.RTP)
.getLocalCandidates()
.get(0).getTransportAddress().getPort());
}
catch (Throwable t)
{
if (t instanceof InterruptedException)
Thread.currentThread().interrupt();
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
else
portTracker.setNextPort(numComponents + portBase);
}
return iceAgent;
}
/**
* {@inheritDoc}
*/
@Override
protected void describe(IceUdpTransportPacketExtension pe)
{
if (!closed)
{
pe.setPassword(iceAgent.getLocalPassword());
pe.setUfrag(iceAgent.getLocalUfrag());
for (Component component : iceStream.getComponents())
{
List<LocalCandidate> candidates
= component.getLocalCandidates();
if ((candidates != null) && !candidates.isEmpty())
{
for (LocalCandidate candidate : candidates)
{
if (candidate.getTransport() == Transport.TCP
&& tcpHostHarvesterMappedPort != -1
&& (candidate.getTransportAddress().getPort()
!= tcpHostHarvesterMappedPort))
{
// In case we use a mapped port with the TCP
// harvester, do not advertise the candidates with
// the actual port that we listen on.
continue;
}
describe(candidate, pe);
}
}
}
if (rtcpmux)
pe.addChildExtension(new RtcpmuxPacketExtension());
describeDtlsControl(pe);
}
}
/**
* Adds a new <tt>CandidatePacketExtension</tt> to <tt>pe</tt>, sets the
* values of its properties to the values of the respective properties of
* <tt>candidate</tt>.
*
* @param candidate the <tt>LocalCandidate</tt> from which to take the values
* of the properties to set.
* @param pe the <tt>IceUdpTransportPacketExtension</tt> to which to add a
* new <tt>CandidatePacketExtension</tt>.
*/
private void describe(
LocalCandidate candidate,
IceUdpTransportPacketExtension pe)
{
CandidatePacketExtension candidatePE = new CandidatePacketExtension();
org.ice4j.ice.Component component = candidate.getParentComponent();
candidatePE.setComponent(component.getComponentID());
candidatePE.setFoundation(candidate.getFoundation());
candidatePE.setGeneration(
component.getParentStream().getParentAgent().getGeneration());
candidatePE.setID(generateCandidateID(candidate));
candidatePE.setNetwork(0);
candidatePE.setPriority(candidate.getPriority());
// Advertise 'tcp' candidates for which SSL is enabled as 'ssltcp'
// (although internally their transport protocol remains "tcp")
Transport transport = candidate.getTransport();
if (transport == Transport.TCP
&& candidate.isSSL())
{
transport = Transport.SSLTCP;
}
candidatePE.setProtocol(transport.toString());
if (transport == Transport.TCP || transport == Transport.SSLTCP)
{
candidatePE.setTcpType(candidate.getTcpType());
}
candidatePE.setType(
CandidateType.valueOf(candidate.getType().toString()));
TransportAddress transportAddress = candidate.getTransportAddress();
candidatePE.setIP(transportAddress.getHostAddress());
candidatePE.setPort(transportAddress.getPort());
TransportAddress relatedAddress = candidate.getRelatedAddress();
if (relatedAddress != null)
{
candidatePE.setRelAddr(relatedAddress.getHostAddress());
candidatePE.setRelPort(relatedAddress.getPort());
}
pe.addChildExtension(candidatePE);
}
/**
* Sets the values of the properties of a specific
* <tt>IceUdpTransportPacketExtension</tt> to the values of the
* respective properties of {@link #dtlsControl}
*
* @param transportPE the <tt>IceUdpTransportPacketExtension</tt> on which
* to set the values of the properties of <tt>dtlsControl</tt>
*/
private void describeDtlsControl(IceUdpTransportPacketExtension transportPE)
{
String fingerprint = dtlsControl.getLocalFingerprint();
String hash = dtlsControl.getLocalFingerprintHashFunction();
DtlsFingerprintPacketExtension fingerprintPE
= transportPE.getFirstChildOfType(
DtlsFingerprintPacketExtension.class);
if (fingerprintPE == null)
{
fingerprintPE = new DtlsFingerprintPacketExtension();
transportPE.addChildExtension(fingerprintPE);
}
fingerprintPE.setFingerprint(fingerprint);
fingerprintPE.setHash(hash);
}
/**
* Sets up {@link #dtlsControl} according to <tt>transport</tt>,
* adds all (supported) remote candidates from <tt>transport</tt>
* to {@link #iceAgent} and starts {@link #iceAgent} if it isn't already
* started.
*/
private synchronized void doStartConnectivityEstablishment(
IceUdpTransportPacketExtension transport)
{
if (closed)
return;
if (transport.isRtcpMux())
{
rtcpmux = true;
if (channelForDtls != null && channelForDtls instanceof RtpChannel)
{
((RtpChannel) channelForDtls)
.getDatagramFilter(true).setAcceptNonRtp(false);
}
}
List<DtlsFingerprintPacketExtension> dfpes
= transport.getChildExtensionsOfType(
DtlsFingerprintPacketExtension.class);
if (!dfpes.isEmpty())
{
Map<String, String> remoteFingerprints
= new LinkedHashMap<String, String>();
for (DtlsFingerprintPacketExtension dfpe : dfpes)
{
remoteFingerprints.put(
dfpe.getHash(),
dfpe.getFingerprint());
}
dtlsControl.setRemoteFingerprints(remoteFingerprints);
}
IceProcessingState state = iceAgent.getState();
if (IceProcessingState.COMPLETED.equals(state)
|| IceProcessingState.TERMINATED.equals(state))
{
// Adding candidates to a completed Agent is unnecessary and has
// been observed to cause problems.
return;
}
/*
* If ICE is running already, we try to update the checklists with the
* candidates. Note that this is a best effort.
*/
boolean iceAgentStateIsRunning
= IceProcessingState.RUNNING.equals(state);
int remoteCandidateCount = 0;
if (rtcpmux)
{
Component rtcpComponent = iceStream.getComponent(Component.RTCP);
if (rtcpComponent != null)
iceStream.removeComponent(rtcpComponent);
}
// Different stream may have different ufrag/password
String ufrag = transport.getUfrag();
if (ufrag != null)
iceStream.setRemoteUfrag(ufrag);
String password = transport.getPassword();
if (password != null)
iceStream.setRemotePassword(password);
List<CandidatePacketExtension> candidates
= transport.getChildExtensionsOfType(
CandidatePacketExtension.class);
if (iceAgentStateIsRunning && (candidates.size() == 0))
return;
// Sort the remote candidates (host < reflexive < relayed) in order
// to create first the host, then the reflexive, the relayed
// candidates and thus be able to set the relative-candidate
// matching the rel-addr/rel-port attribute.
Collections.sort(candidates);
int generation = iceAgent.getGeneration();
for (CandidatePacketExtension candidate : candidates)
{
/*
* Is the remote candidate from the current generation of the
* iceAgent?
*/
if (candidate.getGeneration() != generation)
continue;
if (rtcpmux && Component.RTCP == candidate.getComponent())
{
logger.warn("Received an RTCP candidate, but we're using"
+ " rtcp-mux. Ignoring.");
continue;
}
Component component
= iceStream.getComponent(candidate.getComponent());
String relAddr;
int relPort;
TransportAddress relatedAddress = null;
if (((relAddr = candidate.getRelAddr()) != null)
&& ((relPort = candidate.getRelPort()) != -1))
{
relatedAddress
= new TransportAddress(
relAddr,
relPort,
Transport.parse(candidate.getProtocol()));
}
RemoteCandidate relatedCandidate
= component.findRemoteCandidate(relatedAddress);
RemoteCandidate remoteCandidate
= new RemoteCandidate(
new TransportAddress(
candidate.getIP(),
candidate.getPort(),
Transport.parse(
candidate.getProtocol())),
component,
org.ice4j.ice.CandidateType.parse(
candidate.getType().toString()),
candidate.getFoundation(),
candidate.getPriority(),
relatedCandidate);
/*
* XXX IceUdpTransportManager harvests host candidates only and
* the ICE Components utilize the UDP protocol/transport only at
* the time of this writing. The ice4j library will, of course,
* check the theoretical reachability between the local and the
* remote candidates. However, we would like (1) to not mess
* with a possibly running iceAgent and (2) to return a
* consistent return value.
*/
if (!canReach(component, remoteCandidate))
continue;
if (iceAgentStateIsRunning)
component.addUpdateRemoteCandidates(remoteCandidate);
else
component.addRemoteCandidate(remoteCandidate);
remoteCandidateCount++;
}
if (iceAgentStateIsRunning)
{
if (remoteCandidateCount == 0)
{
/*
* XXX Effectively, the check above but realizing that all
* candidates were ignored: iceAgentStateIsRunning
* && (candidates.size() == 0).
*/
return;
}
else
{
// update all components of all streams
for (IceMediaStream stream : iceAgent.getStreams())
{
for (Component component : stream.getComponents())
component.updateRemoteCandidates();
}
}
}
else if (remoteCandidateCount != 0)
{
/*
* Once again because the ICE Agent does not support adding
* candidates after the connectivity establishment has been started
* and because multiple transport-info JingleIQs may be used to send
* the whole set of transport candidates from the remote peer to the
* local peer, do not really start the connectivity establishment
* until we have at least one remote candidate per ICE Component.
*/
for (IceMediaStream stream : iceAgent.getStreams())
{
for (Component component : stream.getComponents())
{
if (component.getRemoteCandidateCount() < 1)
{
remoteCandidateCount = 0;
break;
}
}
if (remoteCandidateCount == 0)
break;
}
if (remoteCandidateCount != 0)
iceAgent.startConnectivityEstablishment();
}
else
{
if (iceStream.getRemoteUfrag() != null &&
iceStream.getRemotePassword() != null)
{
// We don't have any remote candidates, but we already know the
// remote ufrag and password, so we can start ICE.
logger.info("Starting ICE agent without remote candidates.");
iceAgent.startConnectivityEstablishment();
}
}
}
/**
* Generates an ID to be set on a <tt>CandidatePacketExtension</tt> to
* represent a specific <tt>LocalCandidate</tt>.
*
* @param candidate the <tt>LocalCandidate</tt> whose ID is to be generated
* @return an ID to be set on a <tt>CandidatePacketExtension</tt> to
* represent the specified <tt>candidate</tt>
*/
private String generateCandidateID(LocalCandidate candidate)
{
StringBuilder candidateID = new StringBuilder();
candidateID.append(conference.getID());
candidateID.append(Long.toHexString(hashCode()));
Agent iceAgent
= candidate.getParentComponent().getParentStream().getParentAgent();
candidateID.append(Long.toHexString(iceAgent.hashCode()));
candidateID.append(Long.toHexString(iceAgent.getGeneration()));
candidateID.append(Long.toHexString(candidate.hashCode()));
return candidateID.toString();
}
/**
* Gets the <tt>Conference</tt> object that this <tt>TransportManager</tt>
* is associated with.
*/
public Conference getConference()
{
return conference;
}
/**
* Gets the number of {@link org.ice4j.ice.Component}-s to create in
* {@link #iceStream}.
*/
public int getNumComponents()
{
return numComponents;
}
/**
* Gets the <tt>Agent</tt> which implements the ICE protocol and which is
* used by this instance to implement the Jingle ICE-UDP transport.
*/
public Agent getAgent()
{
return iceAgent;
}
/**
* Gets the <tt>IceMediaStream</tt> of {@link #iceAgent} associated with the
* <tt>Channel</tt> of this instance.
*/
public IceMediaStream getIceStream()
{
return iceStream;
}
/**
* Returns a boolean value determining whether this
* <tt>IceUdpTransportManager</tt> will serve as the the controlling or
* the controlled ICE agent.
*/
public boolean isControlling()
{
return isControlling;
}
/**
* Gets the <tt>BundleContext</tt> associated with the <tt>Channel</tt>
* that this {@link net.java.sip.communicator.service.protocol.media
* .TransportManager} is servicing. The method is a
* convenience which gets the <tt>BundleContext</tt> associated with the
* XMPP component implementation in which the <tt>Videobridge</tt>
* associated with this instance is executing.
*
* @return the <tt>BundleContext</tt> associated with this
* <tt>IceUdpTransportManager</tt>
*/
public BundleContext getBundleContext()
{
return conference != null ? conference.getBundleContext() : null;
}
/**
* {@inheritDoc}
*/
@Override
public DtlsControl getDtlsControl(Channel channel)
{
return dtlsControl;
}
/**
* Gets the <tt>IceSocketWrapper</tt> from the selected pair (if any)
* from a specific {@link org.ice4j.ice.Component}.
* @param component the <tt>Component</tt> from which to get a socket.
* @return the <tt>IceSocketWrapper</tt> from the selected pair (if any)
* from a specific {@link org.ice4j.ice.Component}.
*/
private IceSocketWrapper getSocketForComponent(Component component)
{
CandidatePair selectedPair = component.getSelectedPair();
if (selectedPair != null)
{
return selectedPair.getIceSocketWrapper();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public StreamConnector getStreamConnector(Channel channel)
{
if (!getChannels().contains(channel))
return null;
IceSocketWrapper[] iceSockets = getStreamConnectorSockets();
IceSocketWrapper iceSocket0;
if (iceSockets == null || (iceSocket0 = iceSockets[0]) == null)
return null;
if (channel instanceof SctpConnection)
{
DatagramSocket udpSocket = iceSocket0.getUDPSocket();
if (udpSocket != null)
{
if (udpSocket instanceof MultiplexingDatagramSocket)
{
MultiplexingDatagramSocket multiplexing
= (MultiplexingDatagramSocket) udpSocket;
try
{
DatagramSocket dtlsSocket
= multiplexing.getSocket(new DTLSDatagramFilter());
return new DefaultStreamConnector(dtlsSocket, null);
}
catch (IOException ioe)
{
logger.warn("Failed to create DTLS socket: " + ioe);
}
}
}
else
{
Socket tcpSocket = iceSocket0.getTCPSocket();
if (tcpSocket != null
&& tcpSocket instanceof MultiplexingSocket)
{
MultiplexingSocket multiplexing
= (MultiplexingSocket) tcpSocket;
try
{
Socket dtlsSocket
= multiplexing.getSocket(new DTLSDatagramFilter());
return new DefaultTCPStreamConnector(dtlsSocket, null);
}
catch(IOException ioe)
{
logger.warn("Failed to create DTLS socket: " + ioe);
}
}
}
return null;
}
if (! (channel instanceof RtpChannel))
return null;
DatagramSocket udpSocket0;
IceSocketWrapper iceSocket1 = iceSockets[1];
RtpChannel rtpChannel = (RtpChannel) channel;
if ((udpSocket0 = iceSocket0.getUDPSocket()) != null)
{
DatagramSocket udpSocket1
= (iceSocket1 == null) ? null : iceSocket1.getUDPSocket();
return
getUDPStreamConnector(
rtpChannel,
new DatagramSocket[] { udpSocket0, udpSocket1 });
}
else
{
Socket tcpSocket0 = iceSocket0.getTCPSocket();
Socket tcpSocket1
= (iceSocket1 == null) ? null : iceSocket1.getTCPSocket();
return
getTCPStreamConnector(
rtpChannel,
new Socket[]{tcpSocket0, tcpSocket1});
}
}
/**
* Gets the <tt>IceSocketWrapper</tt>s from the selected
* <tt>CandidatePair</tt>(s) of the ICE agent.
* TODO cache them in this instance?
* @return the <tt>IceSocketWrapper</tt>s from the selected
* <tt>CandidatePair</tt>(s) of the ICE agent.
*/
private IceSocketWrapper[] getStreamConnectorSockets()
{
IceSocketWrapper[] streamConnectorSockets
= new IceSocketWrapper[2];
Component rtpComponent = iceStream.getComponent(Component.RTP);
if (rtpComponent != null)
{
streamConnectorSockets[0 /* RTP */]
= getSocketForComponent(rtpComponent);
}
if (numComponents > 1 && !rtcpmux)
{
Component rtcpComponent = iceStream.getComponent(Component.RTCP);
if (rtcpComponent != null)
{
streamConnectorSockets[1 /* RTCP */]
= getSocketForComponent(rtcpComponent);
}
}
return streamConnectorSockets;
}
private MediaStreamTarget getStreamTarget()
{
MediaStreamTarget streamTarget = null;
InetSocketAddress[] streamTargetAddresses
= new InetSocketAddress[2];
int streamTargetAddressCount = 0;
Component rtpComponent = iceStream.getComponent(Component.RTP);
if (rtpComponent != null)
{
CandidatePair selectedPair = rtpComponent.getSelectedPair();
if (selectedPair != null)
{
InetSocketAddress streamTargetAddress
= selectedPair
.getRemoteCandidate()
.getTransportAddress();
if (streamTargetAddress != null)
{
streamTargetAddresses[0] = streamTargetAddress;
streamTargetAddressCount++;
}
}
}
if (numComponents > 1 && !rtcpmux)
{
Component rtcpComponent = iceStream.getComponent(Component.RTCP);
if (rtcpComponent != null)
{
CandidatePair selectedPair = rtcpComponent.getSelectedPair();
if (selectedPair != null)
{
InetSocketAddress streamTargetAddress
= selectedPair
.getRemoteCandidate()
.getTransportAddress();
if (streamTargetAddress != null)
{
streamTargetAddresses[1] = streamTargetAddress;
streamTargetAddressCount++;
}
}
}
}
if (rtcpmux)
{
streamTargetAddresses[1] = streamTargetAddresses[0];
streamTargetAddressCount++;
}
if (streamTargetAddressCount > 0)
{
streamTarget
= new MediaStreamTarget(
streamTargetAddresses[0 /* RTP */],
streamTargetAddresses[1 /* RTCP */]);
}
return streamTarget;
}
/**
* {@inheritDoc}
*/
@Override
public MediaStreamTarget getStreamTarget(Channel channel)
{
return getStreamTarget();
}
/**
* Creates and returns a TCP <tt>StreamConnector</tt> to be used by a
* specific <tt>RtpChannel</tt>, using <tt>iceSockets</tt> as the
* underlying <tt>Socket</tt>s.
*
* Does not use <tt>iceSockets</tt> directly, but creates
* <tt>MultiplexedSocket</tt> instances on top of them.
*
* @param rtpChannel the <tt>RtpChannel</tt> which is to use the created
* <tt>StreamConnector</tt>.
* @param iceSockets the <tt>Socket</tt>s which are to be used by the
* created <tt>StreamConnector</tt>.
* @return a TCP <tt>StreamConnector</tt> with the <tt>Socket</tt>s
* given in <tt>iceSockets</tt> to be used by a specific
* <tt>RtpChannel</tt>.
*/
private StreamConnector getTCPStreamConnector(RtpChannel rtpChannel,
Socket[] iceSockets)
{
StreamConnector connector = null;
if (iceSockets != null)
{
Socket iceSocket0 = iceSockets[0];
Socket channelSocket0 = null;
if (iceSocket0 != null && iceSocket0 instanceof MultiplexingSocket)
{
MultiplexingSocket multiplexing
= (MultiplexingSocket) iceSocket0;
try
{
channelSocket0
= multiplexing.getSocket(
rtpChannel.getDatagramFilter(false /* RTP */));
}
catch (SocketException se) // never thrown
{}
}
Socket iceSocket1 = rtcpmux ? iceSocket0 : iceSockets[1];
Socket channelSocket1 = null;
if (iceSocket1 != null && iceSocket1 instanceof MultiplexingSocket)
{
MultiplexingSocket multiplexing
= (MultiplexingSocket) iceSocket1;
try
{
channelSocket1
= multiplexing.getSocket(
rtpChannel.getDatagramFilter(true /* RTCP */));
}
catch (SocketException se) // never thrown
{}
}
if (channelSocket0 != null || channelSocket1 != null)
{
connector
= new DefaultTCPStreamConnector(
channelSocket0,
channelSocket1,
rtcpmux);
}
}
return connector;
}
/**
* Creates and returns a UDP <tt>StreamConnector</tt> to be used by a
* specific <tt>RtpChannel</tt>, using <tt>iceSockets</tt> as the
* underlying <tt>DatagramSocket</tt>s.
*
* Does not use <tt>iceSockets</tt> directly, but creates
* <tt>MultiplexedDatagramSocket</tt> instances on top of them.
*
* @param rtpChannel the <tt>RtpChannel</tt> which is to use the created
* <tt>StreamConnector</tt>.
* @param iceSockets the <tt>DatagramSocket</tt>s which are to be used by the
* created <tt>StreamConnector</tt>.
* @return a UDP <tt>StreamConnector</tt> with the <tt>DatagramSocket</tt>s
* given in <tt>iceSockets</tt> to be used by a specific
* <tt>RtpChannel</tt>.
*/
private StreamConnector getUDPStreamConnector(RtpChannel rtpChannel,
DatagramSocket[] iceSockets)
{
StreamConnector connector = null;
if (iceSockets != null)
{
DatagramSocket iceSocket0 = iceSockets[0];
DatagramSocket channelSocket0 = null;
if (iceSocket0 != null
&& iceSocket0 instanceof MultiplexingDatagramSocket)
{
MultiplexingDatagramSocket multiplexing
= (MultiplexingDatagramSocket) iceSocket0;
try
{
channelSocket0
= multiplexing.getSocket(
rtpChannel.getDatagramFilter(false /* RTP */));
}
catch (SocketException se) // never thrown
{}
}
DatagramSocket iceSocket1 = rtcpmux ? iceSocket0 : iceSockets[1];
DatagramSocket channelSocket1 = null;
if (iceSocket1 != null
&& iceSocket1 instanceof MultiplexingDatagramSocket)
{
MultiplexingDatagramSocket multiplexing
= (MultiplexingDatagramSocket) iceSocket1;
try
{
channelSocket1
= multiplexing.getSocket(
rtpChannel.getDatagramFilter(true /* RTCP */));
}
catch (SocketException se) // never thrown
{}
}
if (channelSocket0 != null || channelSocket1 != null)
{
connector
= new DefaultStreamConnector(
channelSocket0,
channelSocket1,
rtcpmux);
}
}
return connector;
}
/**
* {@inheritDoc}
*/
@Override
public String getXmlNamespace()
{
return IceUdpTransportPacketExtension.NAMESPACE;
}
/**
* Notifies this instance about a change of the value of the <tt>state</tt>
* property of {@link #iceAgent}.
*
* @param ev a <tt>PropertyChangeEvent</tt> which specifies the old and new
* values of the <tt>state</tt> property of {@link #iceAgent}.
*/
private void iceAgentStateChange(PropertyChangeEvent ev)
{
/*
* Log the changes in the ICE processing state of this
* IceUdpTransportManager for the purposes of debugging.
*/
boolean interrupted = false;
try
{
IceProcessingState oldState = (IceProcessingState) ev.getOldValue();
IceProcessingState newState = (IceProcessingState) ev.getNewValue();
StringBuilder s = new StringBuilder("ICE processing state of ")
.append(getClass().getSimpleName()).append("
.append(Integer.toHexString(hashCode()))
.append(" (for channels");
for (Channel channel : getChannels())
s.append(" ").append(channel.getID());
s.append(") of conference ").append(conference.getID())
.append(" changed from ").append(oldState)
.append(" to ").append(newState).append(".");
logd(s.toString());
EventAdmin eventAdmin
= conference.getVideobridge().getEventAdmin();
if (eventAdmin != null)
{
eventAdmin.sendEvent(EventFactory.transportStateChanged(
this, oldState, newState));
}
}
catch (Throwable t)
{
if (t instanceof InterruptedException)
interrupted = true;
else if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
finally
{
if (interrupted)
Thread.currentThread().interrupt();
}
}
/**
* Notifies this instance about a change of the value of a property of a
* <tt>CandidatePair</tt> of {@link #iceStream}.
*
* @param ev a <tt>PropertyChangeEvent</tt> which specifies the
* <tt>CandidatePair</tt>, the name of the <tt>CandidatePair</tt> property,
* and its old and new values
*/
private void iceStreamPairChange(PropertyChangeEvent ev)
{
if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals(
ev.getPropertyName()))
{
// TODO we might not necessarily want to keep all channels alive by
// the ICE connection.
for (Channel channel : getChannels())
channel.touch();
}
}
/**
* Initializes the static <tt>Harvester</tt> instances used by all
* <tt>IceUdpTransportManager</tt> instances, that is
* {@link #tcpHostHarvester} and {@link #singlePortHarvesters}.
*/
private void initializeStaticHarvesters()
{
synchronized (IceUdpTransportManager.class)
{
if (staticHarvestersInitialized)
return;
staticHarvestersInitialized = true;
ConfigurationService cfg =
conference.getVideobridge().getConfigurationService();
int singlePort = -1;
if ((singlePort = cfg.getInt(SINGLE_PORT_HARVESTER_PORT, -1)) != -1)
{
singlePortHarvesters
= SinglePortUdpHarvester.createHarvesters(singlePort);
if (singlePortHarvesters.isEmpty())
{
singlePortHarvesters = null;
logger.info("No single-port harvesters created.");
}
}
if (!cfg.getBoolean(DISABLE_TCP_HARVESTER, false))
{
int port = cfg.getInt(TCP_HARVESTER_PORT, -1);
boolean fallback = false;
boolean ssltcp = cfg.getBoolean(TCP_HARVESTER_SSLTCP,
TCP_HARVESTER_SSLTCP_DEFAULT);
if (port == -1)
{
port = TCP_DEFAULT_PORT;
fallback = true;
}
try
{
tcpHostHarvester
= new MultiplexingTcpHostHarvester(port, ssltcp);
}
catch (IOException ioe)
{
logger.warn(
"Failed to initialize TCP harvester on port " + port
+ ": " + ioe
+ (fallback
? ". Retrying on port " + TCP_FALLBACK_PORT
: "")
+ ".");
// If no fallback is allowed, the method will return.
}
if (tcpHostHarvester == null)
{
// If TCP_HARVESTER_PORT specified a port, then fallback was
// disabled. However, if the binding on the port (above)
// fails, then the method should return.
if (!fallback)
return;
port = TCP_FALLBACK_PORT;
try
{
tcpHostHarvester
= new MultiplexingTcpHostHarvester(port, ssltcp);
}
catch (IOException ioe)
{
logger.warn(
"Failed to initialize TCP harvester on fallback"
+ " port " + port + ": " + ioe);
return;
}
}
if (logger.isInfoEnabled())
{
logger.info("Initialized TCP harvester on port " + port
+ ", using SSLTCP:" + ssltcp);
}
String localAddressStr
= cfg.getString(NAT_HARVESTER_LOCAL_ADDRESS);
String publicAddressStr
= cfg.getString(NAT_HARVESTER_PUBLIC_ADDRESS);
if (localAddressStr != null && publicAddressStr != null)
{
try
{
tcpHostHarvester.addMappedAddress(
InetAddress.getByName(publicAddressStr),
InetAddress.getByName(localAddressStr));
}
catch (UnknownHostException uhe)
{
logger.warn("Failed to add mapped address for "
+ publicAddressStr + " -> " + localAddressStr
+ ": " + uhe);
}
}
int mappedPort = cfg.getInt(TCP_HARVESTER_MAPPED_PORT, -1);
if (mappedPort != -1)
{
tcpHostHarvesterMappedPort = mappedPort;
tcpHostHarvester.addMappedPort(mappedPort);
}
if (AwsCandidateHarvester.smellsLikeAnEC2())
{
TransportAddress localAddress
= AwsCandidateHarvester.getFace();
TransportAddress publicAddress
= AwsCandidateHarvester.getMask();
if (localAddress != null && publicAddress != null)
{
tcpHostHarvester.addMappedAddress(
publicAddress.getAddress(),
localAddress.getAddress());
}
}
}
}
}
/**
* Notifies all channels of this <tt>TransportManager</tt> that connectivity
* has been established (and they can now obtain valid values through
* {@link #getStreamConnector(Channel)} and
* {@link #getStreamTarget(Channel)}.
*/
private void onIceConnected()
{
iceConnected = true;
EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin();
if (eventAdmin != null)
eventAdmin.sendEvent(EventFactory.transportConnected(this));
for (Channel channel : getChannels())
{
channel.transportConnected();
}
}
/**
* {@inheritDoc}
*/
@Override
public void startConnectivityEstablishment(
IceUdpTransportPacketExtension transport)
{
doStartConnectivityEstablishment(transport);
synchronized (connectThreadSyncRoot)
{
if (connectThread == null)
{
connectThread = new Thread()
{
@Override
public void run()
{
try
{
wrapupConnectivityEstablishment();
}
catch (OperationFailedException ofe)
{
logd("Failed to connect IceUdpTransportManager: "
+ ofe);
synchronized (connectThreadSyncRoot)
{
connectThread = null;
return;
}
}
IceProcessingState state = iceAgent.getState();
if (IceProcessingState.COMPLETED.equals(state)
|| IceProcessingState.TERMINATED.equals(state))
{
startDtls();
onIceConnected();
}
else
{
logger.warn("Failed to establish ICE connectivity,"
+ " state: " + state);
}
}
};
connectThread.setDaemon(true);
connectThread.setName("IceUdpTransportManager connect thread");
connectThread.start();
}
}
}
/**
* Sets up {@link #dtlsControl} with a proper target (the remote sockets
* from the pair(s) selected by the ICE agent) and starts it.
*/
private void startDtls()
{
dtlsControl.setSetup(
isControlling
? DtlsControl.Setup.PASSIVE
: DtlsControl.Setup.ACTIVE);
dtlsControl.setRtcpmux(rtcpmux);
// Setup the connector
IceSocketWrapper[] iceSockets = getStreamConnectorSockets();
if (iceSockets == null || iceSockets[0] == null)
{
logd("Cannot start DTLS, no sockets from ICE.");
return;
}
StreamConnector streamConnector;
if (rtpConnector != null)
{
rtpConnector.close();
logger.warn("More than one RTPConnector. Closing the old one.");
}
DatagramSocket udpSocket = iceSockets[0].getUDPSocket();
if (udpSocket != null)
{
streamConnector
= new DefaultStreamConnector(
udpSocket,
iceSockets[1] == null ? null : iceSockets[1].getUDPSocket(),
rtcpmux);
rtpConnector = new RTPConnectorUDPImpl(streamConnector);
}
else
{
//Assume/try TCP
streamConnector
= new DefaultTCPStreamConnector(
iceSockets[0].getTCPSocket(),
iceSockets[1] == null ? null : iceSockets[1].getTCPSocket(),
rtcpmux);
rtpConnector = new RTPConnectorTCPImpl(streamConnector);
}
MediaStreamTarget target = getStreamTarget();
if (target != null)
{
try
{
rtpConnector.addTarget(
new SessionAddress(target.getDataAddress().getAddress(),
target.getDataAddress().getPort()));
}
catch (IOException ioe)
{
logger.warn("Failed to add target to DTLS connector: " + ioe);
// But do go on, because it is not necessary in all cases
}
}
dtlsControl.setConnector(rtpConnector);
dtlsControl.registerUser(this);
// For DTLS, the media type doesn't matter (as long as it's not
// null).
dtlsControl.start(MediaType.AUDIO);
}
/**
* Waits until {@link #iceAgent} exits the RUNNING or WAITING state.
*/
private void wrapupConnectivityEstablishment()
throws OperationFailedException
{
final Object syncRoot = new Object();
PropertyChangeListener propertyChangeListener
= new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent ev)
{
Object newValue = ev.getNewValue();
if (IceProcessingState.COMPLETED.equals(newValue)
|| IceProcessingState.FAILED.equals(newValue)
|| IceProcessingState.TERMINATED.equals(newValue))
{
Agent iceAgent = (Agent) ev.getSource();
iceAgent.removeStateChangeListener(this);
if (iceAgent == IceUdpTransportManager.this.iceAgent)
{
synchronized (syncRoot)
{
syncRoot.notify();
}
}
}
}
};
Agent iceAgent = this.iceAgent;
if (iceAgent == null)
{
// The TransportManager has been closed, so we should return and
// let the thread finish.
return;
}
iceAgent.addStateChangeListener(propertyChangeListener);
// Wait for the connectivity checks to finish if they have been started.
boolean interrupted = false;
IceProcessingState state = iceAgent.getState();
synchronized (syncRoot)
{
while (IceProcessingState.RUNNING.equals(state)
|| IceProcessingState.WAITING.equals(state))
{
try
{
syncRoot.wait(1000);
}
catch (InterruptedException ie)
{
interrupted = true;
}
finally
{
state = iceAgent.getState();
if (this.iceAgent == null)
break;
}
}
}
if (interrupted)
Thread.currentThread().interrupt();
/*
* Make sure stateChangeListener is removed from iceAgent in case its
* #propertyChange(PropertyChangeEvent) has never been executed.
*/
iceAgent.removeStateChangeListener(propertyChangeListener);
// Check the state of ICE processing and throw an exception if failed.
if (this.iceAgent == null)
{
throw new OperationFailedException(
"TransportManager closed",
OperationFailedException.GENERAL_ERROR);
}
else if (IceProcessingState.FAILED.equals(state))
{
throw new OperationFailedException(
"ICE failed",
OperationFailedException.GENERAL_ERROR);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isConnected()
{
return iceConnected;
}
/**
* Extends
* <tt>net.java.sip.communicator.service.protocol.media.TransportManager</tt>
* in order to get access to certain protected static methods and thus avoid
* duplicating their implementations here.
*
* @author Lyubomir Marinov
*/
private static class JitsiTransportManager
extends
net.java.sip.communicator.service.protocol.media.TransportManager
<MediaAwareCallPeer<?,?,?>>
{
public static PortTracker getPortTracker(MediaType mediaType)
{
return
net.java.sip.communicator.service.protocol.media.TransportManager
.getPortTracker(mediaType);
}
public static void initializePortNumbers()
{
net.java.sip.communicator.service.protocol.media.TransportManager
.initializePortNumbers();
}
private JitsiTransportManager(MediaAwareCallPeer<?,?,?> callPeer)
{
super(callPeer);
}
@Override
public long getHarvestingTime(String arg0)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getICECandidateExtendedType(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICELocalHostAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICELocalReflexiveAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICELocalRelayedAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICERemoteHostAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICERemoteReflexiveAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public InetSocketAddress getICERemoteRelayedAddress(String arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getICEState()
{
// TODO Auto-generated method stub
return null;
}
@Override
protected InetAddress getIntendedDestination(
MediaAwareCallPeer<?,?,?> arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getNbHarvesting()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public int getNbHarvesting(String arg0)
{
// TODO Auto-generated method stub
return 0;
}
@Override
public long getTotalHarvestingTime()
{
// TODO Auto-generated method stub
return 0;
}
}
}
|
package org.commcare.adapters;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import org.commcare.CommCareApplication;
import org.commcare.activities.CommCareActivity;
import org.commcare.core.process.CommCareInstanceInitializer;
import org.commcare.dalvik.R;
import org.commcare.logging.AndroidLogger;
import org.commcare.logging.XPathErrorLogger;
import org.commcare.models.AndroidSessionWrapper;
import org.commcare.preferences.DeveloperPreferences;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.Entry;
import org.commcare.suite.model.Menu;
import org.commcare.suite.model.MenuDisplayable;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Suite;
import org.commcare.util.CommCarePlatform;
import org.commcare.utils.MediaUtil;
import org.commcare.views.UserfacingErrorHandling;
import org.commcare.views.media.AudioButton;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.File;
import java.util.Hashtable;
import java.util.Vector;
/**
* Load module menu items
*
* @author wspride
*/
public class MenuAdapter implements ListAdapter {
private final AndroidSessionWrapper asw;
private Exception loadError;
private String errorXpathException = "";
final Context context;
MenuDisplayable[] displayableData;
public MenuAdapter(Context context, CommCarePlatform platform, String menuID) {
this.context = context;
Vector<MenuDisplayable> items = new Vector<>();
Hashtable<String, Entry> map = platform.getMenuMap();
asw = CommCareApplication._().getCurrentSessionWrapper();
for (Suite s : platform.getInstalledSuites()) {
for (Menu m : s.getMenus()) {
errorXpathException = "";
try {
if (menuIsRelevant(m)) {
if (m.getId().equals(menuID)) {
addRelevantCommandEntries(m, items, map);
} else {
addUnaddedMenu(menuID, m, items);
}
}
} catch (CommCareInstanceInitializer.FixtureInitializationException
| XPathSyntaxException | XPathException xpe) {
loadError = xpe;
displayableData = new MenuDisplayable[0];
return;
}
}
}
displayableData = new MenuDisplayable[items.size()];
items.copyInto(displayableData);
}
public void showAnyLoadErrors(CommCareActivity activity) {
if (loadError != null) {
String errorMessage = loadError.getMessage();
if (loadError instanceof XPathSyntaxException) {
XPathErrorLogger.INSTANCE.logErrorToCurrentApp(errorXpathException, loadError.getMessage());
errorMessage = Localization.get("app.menu.display.cond.bad.xpath", new String[]{errorXpathException, loadError.getMessage()});
} else if (loadError instanceof XPathException) {
XPathErrorLogger.INSTANCE.logErrorToCurrentApp((XPathException)loadError);
errorMessage = Localization.get("app.menu.display.cond.xpath.err", new String[]{errorXpathException, loadError.getMessage()});
}
UserfacingErrorHandling.createErrorDialog(activity, errorMessage, true);
}
}
private boolean menuIsRelevant(Menu m) throws XPathSyntaxException {
XPathExpression relevance = m.getMenuRelevance();
if (m.getMenuRelevance() != null) {
errorXpathException = m.getMenuRelevanceRaw();
EvaluationContext ec = asw.getEvaluationContext(m.getId());
return XPathFuncExpr.toBoolean(relevance.eval(ec));
}
return true;
}
private void addRelevantCommandEntries(Menu m, Vector<MenuDisplayable> items,
Hashtable<String, Entry> map)
throws XPathSyntaxException {
EvaluationContext ec = asw.getEvaluationContext();
for (String command : m.getCommandIds()) {
errorXpathException = "";
XPathExpression mRelevantCondition = m.getCommandRelevance(m.indexOfCommand(command));
if (mRelevantCondition != null) {
errorXpathException = m.getCommandRelevanceRaw(m.indexOfCommand(command));
Object ret = mRelevantCondition.eval(ec);
try {
if (!XPathFuncExpr.toBoolean(ret)) {
continue;
}
} catch (XPathTypeMismatchException e) {
final String msg = "relevancy condition for menu item returned non-boolean value : " + ret;
XPathErrorLogger.INSTANCE.logErrorToCurrentApp(e.getSource(), msg);
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, msg);
throw new RuntimeException(msg);
}
}
Entry e = map.get(command);
if (e.isView()) {
//If this is a "view", not an "entry"
//we only want to display it if all of its
//datums are not already present
if (asw.getSession().getNeededDatum(e) == null) {
continue;
}
}
items.add(e);
}
}
private static void addUnaddedMenu(String menuID, Menu m, Vector<MenuDisplayable> items) {
if (menuID.equals(m.getRoot())) {
//make sure we didn't already add this ID
boolean idExists = false;
for (Object o : items) {
if (o instanceof Menu) {
if (((Menu)o).getId().equals(m.getId())) {
idExists = true;
break;
}
}
}
if (!idExists) {
items.add(m);
}
}
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int arg0) {
return true;
}
@Override
public int getCount() {
return displayableData.length;
}
@Override
public Object getItem(int i) {
return displayableData[i];
}
@Override
public long getItemId(int i) {
Object tempItem = displayableData[i];
if (tempItem instanceof Menu) {
return ((Menu)tempItem).getId().hashCode();
} else {
return ((Entry)tempItem).getCommandId().hashCode();
}
}
@Override
public int getItemViewType(int i) {
return 0;
}
enum NavIconState {
NONE, NEXT, JUMP
}
@Override
public View getView(int i, View menuListItem, ViewGroup vg) {
MenuDisplayable menuDisplayable = displayableData[i];
if (menuListItem == null) {
// inflate it and do not attach to parent, or we will get the 'addView not supported' exception
menuListItem = LayoutInflater.from(context).inflate(R.layout.menu_list_item_modern, vg, false);
}
TextView rowText = (TextView)menuListItem.findViewById(R.id.row_txt);
setupTextView(rowText, menuDisplayable);
AudioButton mAudioButton = (AudioButton)menuListItem.findViewById(R.id.row_soundicon);
setupAudioButton(mAudioButton, menuDisplayable);
// set up the image, if available
ImageView mIconView = (ImageView)menuListItem.findViewById(R.id.row_img);
setupImageView(mIconView, menuDisplayable);
return menuListItem;
}
private void setupAudioButton(AudioButton mAudioButton, MenuDisplayable menuDisplayable) {
final String audioURI = menuDisplayable.getAudioURI();
String audioFilename = "";
if (audioURI != null && !audioURI.equals("")) {
try {
audioFilename = ReferenceManager._().DeriveReference(audioURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e("AVTLayout", "Invalid reference exception");
e.printStackTrace();
}
}
File audioFile = new File(audioFilename);
// First set up the audio button
if (!"".equals(audioFilename) && audioFile.exists()) {
// Set not focusable so that list onclick will work
mAudioButton.setFocusable(false);
mAudioButton.setFocusableInTouchMode(false);
mAudioButton.resetButton(audioURI, true);
} else {
if (mAudioButton != null) {
mAudioButton.resetButton(audioURI, false);
((LinearLayout)mAudioButton.getParent()).removeView(mAudioButton);
}
}
}
public void setupTextView(TextView textView, MenuDisplayable menuDisplayable) {
String mQuestionText = textViewHelper(menuDisplayable);
//Final change, remove any numeric context requests. J2ME uses these to
//help with numeric navigation.
if (mQuestionText != null) {
mQuestionText = Localizer.processArguments(mQuestionText, new String[]{""}).trim();
}
textView.setText(mQuestionText);
}
public void setupImageView(ImageView mIconView, MenuDisplayable menuDisplayable) {
String imageURI = menuDisplayable.getImageURI();
Bitmap image = MediaUtil.inflateDisplayImage(context, imageURI);
if (mIconView != null) {
if (image != null) {
mIconView.setImageBitmap(image);
mIconView.setAdjustViewBounds(true);
} else {
setupDefaultIcon(mIconView, getIconState(menuDisplayable));
}
}
}
private NavIconState getIconState(MenuDisplayable menuDisplayable) {
NavIconState iconChoice = NavIconState.NEXT;
//figure out some icons
if (menuDisplayable instanceof Entry) {
SessionDatum datum = asw.getSession().getNeededDatum((Entry)menuDisplayable);
if (datum == null || !(datum instanceof EntityDatum)) {
iconChoice = NavIconState.JUMP;
}
}
if (!DeveloperPreferences.isNewNavEnabled()) {
iconChoice = NavIconState.NONE;
}
return iconChoice;
}
protected void setupDefaultIcon(ImageView mIconView, NavIconState iconChoice) {
if (mIconView != null) {
switch (iconChoice) {
case NEXT:
mIconView.setImageResource(R.drawable.avatar_module);
break;
case JUMP:
mIconView.setImageResource(R.drawable.avatar_form);
break;
case NONE:
mIconView.setVisibility(View.GONE);
break;
}
}
}
private static String textViewHelper(MenuDisplayable e) {
return e.getDisplayText();
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void registerDataSetObserver(DataSetObserver arg0) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver arg0) {
}
}
|
package org.metawatch.manager.widgets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;
import org.metawatch.manager.FontCache;
import org.metawatch.manager.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
public class CalendarWidget implements InternalWidget {
public final static String id_0 = "Calendar_24_32";
final static String desc_0 = "Next Calendar Appointment (24x32)";
public final static String id_1 = "Calendar_96_32";
final static String desc_1 = "Next Calendar Appointment (96x32)";
private Context context;
private TextPaint paintSmall;
private TextPaint paintNumerals;
private String meetingTime = "None";
public void init(Context context, ArrayList<CharSequence> widgetIds) {
this.context = context;
paintSmall = new TextPaint();
paintSmall.setColor(Color.BLACK);
paintSmall.setTextSize(FontCache.instance(context).Small.size);
paintSmall.setTypeface(FontCache.instance(context).Small.face);
paintSmall.setTextAlign(Align.CENTER);
paintNumerals = new TextPaint();
paintNumerals.setColor(Color.BLACK);
paintNumerals.setTextSize(FontCache.instance(context).Numerals.size);
paintNumerals.setTypeface(FontCache.instance(context).Numerals.face);
paintNumerals.setTextAlign(Align.CENTER);
}
public void shutdown() {
paintSmall = null;
}
public void refresh(ArrayList<CharSequence> widgetIds) {
meetingTime = Utils.readCalendar(context, 0);
}
public void get(ArrayList<CharSequence> widgetIds, Map<String,WidgetData> result) {
if(widgetIds == null || widgetIds.contains(id_0)) {
result.put(id_0, GenWidget(id_0));
}
if(widgetIds == null || widgetIds.contains(id_1)) {
result.put(id_1, GenWidget(id_1));
}
}
private InternalWidget.WidgetData GenWidget(String widget_id) {
InternalWidget.WidgetData widget = new InternalWidget.WidgetData();
widget.priority = meetingTime.equals("None") ? 0 : 1;
if (widget_id.equals(id_0)) {
widget.id = id_0;
widget.description = desc_0;
widget.width = 24;
widget.height = 32;
}
else if (widget_id.equals(id_1)) {
widget.id = id_1;
widget.description = desc_1;
widget.width = 96;
widget.height = 32;
}
Bitmap icon = Utils.loadBitmapFromAssets(context, "idle_calendar.bmp");
widget.bitmap = Bitmap.createBitmap(widget.width, widget.height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(widget.bitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(icon, 0, 3, null);
Calendar c = Calendar.getInstance();
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
if(dayOfMonth<10) {
canvas.drawText(""+dayOfMonth, 12, 16, paintNumerals);
}
else
{
canvas.drawText(""+dayOfMonth/10, 9, 16, paintNumerals);
canvas.drawText(""+dayOfMonth%10, 15, 16, paintNumerals);
}
canvas.drawText(meetingTime, 12, 29, paintSmall);
if (widget_id.equals(id_1)) {
paintSmall.setTextAlign(Align.LEFT);
String text = Utils.Meeting_Title;
if ((Utils.Meeting_Location !=null) && (Utils.Meeting_Location.length()>0))
text += " - " + Utils.Meeting_Location;
canvas.save();
StaticLayout layout = new StaticLayout(text, paintSmall, 70, Layout.Alignment.ALIGN_CENTER, 1.2f, 0, false);
int height = layout.getHeight();
int textY = 16 - (height/2);
if(textY<0) {
textY=0;
}
canvas.translate(25, textY); //position the text
layout.draw(canvas);
canvas.restore();
paintSmall.setTextAlign(Align.CENTER);
}
return widget;
}
}
|
package org.nutz.mvc.adaptor.injector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nutz.lang.Parsing;
/**
* .<br/>
* URL, {@link Parsing}<br/>
* URL:
* <ul>
* <li>"."
* <li>,Collection, "[]"":". <b style='color:red'>, </b>
* <li>Map"()""."key
* </ul>
* :<br>
* <code>
* Object: node.str = str<br>
* list: node.list[1].str = abc;<br>
* node.list:2.str = 2<br>
* set: node.set[2].str = bbb<br>
* node.set:jk.str = jk<br>
* Map: node.map(key).str = bb;<br>
* node.map.key.name = map<br>
*
* </code>
* @author juqkai(juqkai@gmail.com)
*
*/
public class ObjectNaviNode {
private static final char separator = '.';
private static final char LIST_SEPARATOR = ':';
private static final int TYPE_NONE = 0;
private static final int TYPE_LIST = 1;
private String name;
private String[] value;
private boolean leaf = true;
private Map<String, ObjectNaviNode> child = new HashMap<String, ObjectNaviNode>();
private int type = TYPE_NONE;
public void put(String path, String[] value) {
path = path.replace("[", ":");
path = path.replace("]", "");
path = path.replace("(", ".");
path = path.replace(")", "");
putPath(path, value);
}
private void putPath(String path, String[] value){
init(path);
String subPath = fetchSubPath(path);
if ("".equals(subPath) || path.equals(subPath)) {
this.value = value;
return;
}
leaf = false;
addChild(subPath, value);
}
private void addChild(String path, String[] value) {
String subname = fetchName(path);
ObjectNaviNode onn = child.get(subname);
if (onn == null) {
onn = new ObjectNaviNode();
}
onn.putPath(path, value);
child.put(subname, onn);
}
/**
* name, type
* @param path
*/
private void init(String path){
String key = fetchNode(path);
if(isList(key)){
type = TYPE_LIST;
name = key.substring(0, key.indexOf(LIST_SEPARATOR));
return;
}
name = key;
}
/**
*
* @param path
* @return
*/
private String fetchSubPath(String path){
if(isList(fetchNode(path))){
return path.substring(path.indexOf(LIST_SEPARATOR) + 1);
}
return path.substring(path.indexOf(separator) + 1);
}
private String fetchNode(String path) {
if (path.indexOf(separator) <= 0) {
return path;
}
return path.substring(0, path.indexOf(separator));
}
/**
* name
* @param key
* @return
*/
private String fetchName(String path){
String key = fetchNode(path);
if(isList(key)){
return key.substring(0, key.indexOf(LIST_SEPARATOR));
}
return key;
}
/**
* list,map
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object get(){
if(isLeaf()){
return value.length == 1 ? value[0] : value;
}
if(type == TYPE_LIST){
List list = new ArrayList();
for(String o : child.keySet()){
list.add(child.get(o).get());
}
return list;
}
Map map = new HashMap();
for(String o : child.keySet()){
map.put(o, child.get(o).get());
}
return map;
}
/**
* list
* @param key
* @return
*/
private boolean isList(String key){
return key.indexOf(LIST_SEPARATOR) > 0;
}
public String getName() {
return name;
}
public String[] getValue() {
return value;
}
public boolean isLeaf() {
return leaf;
}
}
|
package org.eclipse.hawkbit.rest.documentation;
/**
* Constants for API documentation.
*/
public final class ApiModelPropertiesGeneric {
public static final String ENDING = " of the entity";
// generic
public static final String TENANT = "The tenant";
public static final String ITEM_ID = "The technical identifier " + ENDING;
public static final String NAME = "The name" + ENDING;
public static final String DESCRPTION = "The description" + ENDING;
public static final String COLOUR = "The colour" + ENDING;
public static final String DELETED = "Deleted flag, used for soft deleted entities";
public static final String CREATED_BY = "Entity was originally created by User, AMQP-Controller, anonymous etc.)";
public static final String CREATED_AT = "Entity was originally created at (timestamp UTC in milliseconds)";
public static final String LAST_MODIFIED_BY = "Entity was last modified by User, AMQP-Controller, anonymous etc.)";
public static final String LAST_MODIFIED_AT = "Entity was last modified at (timestamp UTC in milliseconds)";
// Paging elements
public static final String SIZE = "Current page size";
public static final String TOTAL_ELEMENTS = "Total number of elements";
public static final String SELF_LINKS_TO_RESOURCE = "Links to the given resource itself";
private ApiModelPropertiesGeneric() {
// utility class
}
// parameters
public static final String OFFSET = "The paging offset (default is 0).";
public static final String LIMIT = "The maximum number of entries in a page (default is 50).";
public static final String SORT = "The query parameter sort allows to define the sort order for the result of a query. "
+ "A sort criteria consists of the name of a field and the sort direction (ASC for ascending and DESC descending). "
+ "The sequence of the sort criteria (multiple can be used) defines the sort order of the entities in the result.";
public static final String FIQL = "Query fields based on the Feed Item Query Language (FIQL). See Entity Definitions for available fields.";
// Error/exception handling
public static final String EXCEPTION_CLASS = "The exception class name.";
public static final String ERROR_CODE = "The exception error code.";
public static final String ERROR_MESSAGE = "The exception human readable message.";
public static final String ERROR_PARAMETERS = "The exception message parameters.";
}
|
package hu.bme.mit.inf.telecare.simplified.generator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.incquery.runtime.api.IPatternMatch;
import org.eclipse.incquery.runtime.api.IQuerySpecification;
import org.eclipse.incquery.runtime.exception.IncQueryException;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import dataflow.DataflowFactory;
import dataflow.DataflowPackage;
import dataflow.InformationType;
import events.AbstractActivity;
import events.Activity;
import events.EventsFactory;
import events.EventsPackage;
import events.Finish;
import events.Init;
import hu.bme.mit.inf.dslreasoner.visualisation.emf2yed.Model2Yed;
import hu.bme.mit.inf.telecare.simplified.generator.query.ActionMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.AfterExtendedAMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.AfterExtendedBMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.AfterMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.DataflowExtendedMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.DataflowMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.FinishMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.InitMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.SrcMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.TrgMatch;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.ActionQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.AfterExtendedAQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.AfterExtendedBQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.AfterQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.DataflowExtendedQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.DataflowQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.FinishQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.InitQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.SrcQuerySpecification;
import hu.bme.mit.inf.telecare.simplified.generator.query.util.TrgQuerySpecification;
import telecare.Host;
import telecare.Measure;
import telecare.MeasurementType;
import telecare.NamedElement;
import telecare.PeriodicTrigger;
import telecare.Report;
import telecare.TelecareFactory;
import telecare.TelecarePackage;
import telecare.TelecareSystem;
public class ChangeGenerator {
// private static final Random RANDOM = new Random();
private Set<IQuerySpecification<?>> objRules;
private Set<IQuerySpecification<?>> refRules;
private Set<IQuerySpecification<?>> extendedRules;
private Multimap<Object, IPatternMatch> traceO;
private Multimap<Object, IPatternMatch> traceF;
private Multimap<Object, IPatternMatch> traceE;
private CategorizedModel model;
@SuppressWarnings("unused")
private TelecarePackage eTelecarePackage;
private TelecareFactory eTelecareFactory;
private DataflowPackage eDataflowPackage;
private DataflowFactory eDataflowFactory;
private EventsPackage eEventsPackage;
private EventsFactory eEventsFactory;
public ChangeGenerator(int changeSize, TelecareSystem system, Collection<ChangeTypes> changeTypes) throws Exception {
eTelecarePackage = TelecarePackage.eINSTANCE;
eTelecareFactory = TelecareFactory.eINSTANCE;
eDataflowPackage = DataflowPackage.eINSTANCE;
eDataflowFactory = DataflowFactory.eINSTANCE;
eEventsPackage = EventsPackage.eINSTANCE;
eEventsFactory = EventsFactory.eINSTANCE;
model = new CategorizedModel(system);
initialize();
buildTraceability();
buildViewModelObjects();
buildViewModelReferences();
if(changeTypes.contains(ChangeTypes.AddNewActivationWithNewEdgeToReportAndPeriodicTrigger))
introduceChanges(changeSize, ChangeTypes.AddNewActivationWithNewEdgeToReportAndPeriodicTrigger);
if(changeTypes.contains(ChangeTypes.RemoveHostWithEdgesAddNewEdgesToOtherHost))
introduceChanges(changeSize, ChangeTypes.RemoveHostWithEdgesAddNewEdgesToOtherHost);
if(changeTypes.contains(ChangeTypes.RemoveInformationTypeWithEdges))
introduceChanges(changeSize, ChangeTypes.RemoveInformationTypeWithEdges);
model.refRemoval.addAll(model.dontCareRemoval);
buildModifiedViewModels();
model.yedOriginal = calculateYed();
model.yedEventsOriginal = calculateEventsYed();
model.yedDataflowOriginal = calculateDataflowYed();
model.yedEventsModified = calculateEventYedColored();
model.yedDataflowModified = calculateDataflowYedColored();
model.yedModified = calculateYedColored();
}
private void buildModifiedViewModels() {
for(IPatternMatch match : model.objAddition) {
if(match instanceof ActionMatch) {
Activity activity = eEventsFactory.createActivity();
long i = model.viewNewObjectsEvents.stream().filter(x -> x instanceof Activity).count()+1;
activity.setName("new_activity_"+i);
model.viewNewObjectsEvents.add(activity);
model.mapEvents.put(((ActionMatch) match).getT(), activity);
}
}
for(IPatternMatch match : model.objRemoval) {
if(match instanceof TrgMatch) {
dataflow.Host host = (dataflow.Host) model.mapDataflow.get(((TrgMatch) match).getHost());
model.viewDelObjectsDataflow.add(host);
}
if(match instanceof SrcMatch) {
InformationType type = (InformationType) model.mapDataflow.get(((SrcMatch) match).getType());
model.viewDelObjectsDataflow.add(type);
}
}
for(IPatternMatch match : model.refAddition) {
if(match instanceof AfterMatch) {
AfterMatch afterMatch = (AfterMatch) match;
AbstractActivity source = model.mapEvents.get(afterMatch.getA()).stream().filter(x -> x instanceof Init || x instanceof Activity).findFirst().get();
AbstractActivity target = model.mapEvents.get(afterMatch.getB()).stream().filter(x -> x instanceof Finish || x instanceof Activity).findFirst().get();
model.addEdgesEvents.put(source, target, eEventsPackage.getAbstractActivity_After());
}
}
for(IPatternMatch match : model.refRemoval) {
if(match instanceof DataflowMatch) {
DataflowMatch dataflowMatch = (DataflowMatch) match;
InformationType type = (InformationType) model.mapDataflow.get(dataflowMatch.getType());
dataflow.Host host = (dataflow.Host) model.mapDataflow.get(dataflowMatch.getHost());
model.delEdgesDataflow.put(type, host, eDataflowPackage.getInformationType_Dataflow());
}
}
}
private void buildViewModelReferences() {
Collection<IPatternMatch> referenceMatches = traceF.values();
for (IPatternMatch match : referenceMatches) {
if(match instanceof AfterMatch) {
AfterMatch afterMatch = (AfterMatch) match;
AbstractActivity source = model.mapEvents.get(afterMatch.getA()).stream().filter(x -> x instanceof Init || x instanceof Activity).findFirst().get();
AbstractActivity target = model.mapEvents.get(afterMatch.getB()).stream().filter(x -> x instanceof Finish || x instanceof Activity).findFirst().get();
source.getAfter().add(target);
}
if(match instanceof DataflowMatch) {
DataflowMatch dataflowMatch = (DataflowMatch) match;
InformationType type = (InformationType) model.mapDataflow.get(dataflowMatch.getType());
dataflow.Host host = (dataflow.Host) model.mapDataflow.get(dataflowMatch.getHost());
type.getDataflow().add(host);
}
}
}
private void buildViewModelObjects() {
Collection<IPatternMatch> objectMatches = traceO.values();
for (IPatternMatch match : objectMatches) {
if(match instanceof ActionMatch) {
Activity activity = eEventsFactory.createActivity();
long i = model.viewObjectsEvents.stream().filter(x -> x instanceof Activity).count()+1;
activity.setName("activity_"+i);
model.viewObjectsEvents.add(activity);
model.mapEvents.put(((ActionMatch) match).getT(), activity);
}
if(match instanceof InitMatch) {
Init init = eEventsFactory.createInit();
model.viewObjectsEvents.add(init);
model.mapEvents.put(((InitMatch) match).getT(), init);
}
if(match instanceof FinishMatch) {
Finish finish = eEventsFactory.createFinish();
model.viewObjectsEvents.add(finish);
model.mapEvents.put(((FinishMatch) match).getT(), finish);
}
if(match instanceof TrgMatch) {
dataflow.Host host = eDataflowFactory.createHost();
long i = model.viewObjectsDataflow.stream().filter(x -> x instanceof dataflow.Host).count()+1;
host.setName("host_"+i);
model.viewObjectsDataflow.add(host);
model.mapDataflow.put(((TrgMatch) match).getHost(), host);
}
if(match instanceof SrcMatch) {
InformationType type = eDataflowFactory.createInformationType();
long i = model.viewObjectsDataflow.stream().filter(x -> x instanceof InformationType).count()+1;
type.setName("type_"+i);
model.viewObjectsDataflow.add(type);
model.mapDataflow.put(((SrcMatch) match).getType(), type);
}
}
}
public CategorizedModel getModel() {
return model;
}
private CharSequence calculateDataflowYed() {
Model2Yed yed = new Model2Yed();
CharSequence sequence = yed.transform(model.viewObjectsDataflow);
return sequence;
}
private CharSequence calculateDataflowYedColored() {
Model2Yed yed = new Model2Yed();
ArrayList<EObject> objects = Lists.newArrayList(model.viewObjectsDataflow);
objects.addAll(model.viewNewObjectsDataflow);
CharSequence sequence = yed.transform(objects, Collections.emptySet(), model.viewDelObjectsDataflow, model.viewNewObjectsDataflow, model.addEdgesDataflow, model.delEdgesDataflow);
return sequence;
}
private CharSequence calculateEventsYed() {
Model2Yed yed = new Model2Yed();
CharSequence sequence = yed.transform(model.viewObjectsEvents);
return sequence;
}
private CharSequence calculateEventYedColored() {
Model2Yed yed = new Model2Yed();
ArrayList<EObject> objects = Lists.newArrayList(model.viewObjectsEvents);
objects.addAll(model.viewNewObjectsEvents);
CharSequence sequence = yed.transform(objects, Collections.emptySet(), model.viewDelObjectsEvents, model.viewNewObjectsEvents, model.addEdgesEvents, model.delEdgesEvents);
return sequence;
}
private CharSequence calculateYed() {
Model2Yed yed = new Model2Yed();
ArrayList<EObject> objects = Lists.newArrayList(model.system.eAllContents());
objects.add(model.system);
CharSequence sequence = yed.transform(objects);
return sequence;
}
private CharSequence calculateYedColored() {
Model2Yed yed = new Model2Yed();
List<EObject> objects = Lists.newArrayList(model.system.eAllContents());
objects.add(model.system);
objects.addAll(model.newObjects);
CharSequence sequence = yed.transform(objects, model.changeblePart, model.removablePart, model.newObjects, null, null);
return sequence;
}
private void initialize() throws IncQueryException {
objRules = ImmutableSet.<IQuerySpecification<?>>of(
ActionQuerySpecification.instance(),
FinishQuerySpecification.instance(),
InitQuerySpecification.instance(),
SrcQuerySpecification.instance(),
TrgQuerySpecification.instance());
refRules = ImmutableSet.<IQuerySpecification<?>>of(
AfterQuerySpecification.instance(),
DataflowQuerySpecification.instance());
extendedRules = ImmutableSet.<IQuerySpecification<?>>of(
AfterExtendedAQuerySpecification.instance(),
AfterExtendedBQuerySpecification.instance(),
DataflowExtendedQuerySpecification.instance());
}
private void buildTraceability() throws IncQueryException {
traceO = TraceabilityModel.calculateTraceList(model.system, objRules);
traceF = TraceabilityModel.calculateTraceList(model.system, refRules);
traceE = TraceabilityModel.calculateTraceList(model.system, extendedRules);
}
private void introduceChanges(int numberOfChanges, ChangeTypes type) throws Exception {
for(int i = 0; i < numberOfChanges; i++) {
switch (type) {
case AddNewActivationWithNewEdgeToReportAndPeriodicTrigger:
introduceAddNewActivationWithNewEdgeToReportAndPeriodicTrigger(i);
break;
case RemoveHostWithEdgesAddNewEdgesToOtherHost:
introduceRemoveHostWithEdgesAddNewEdgesToOtherHost(i);
break;
case RemoveInformationTypeWithEdges:
introduceRemoveInformationTypeWithEdges(i);
break;
default:
break;
}
}
}
private void introduceRemoveInformationTypeWithEdges(int i) {
IPatternMatch objRemoval = traceO.values().stream().filter(x -> x instanceof SrcMatch).findFirst().get();
model.objRemoval.add(objRemoval);
removeObjectMatch(model, objRemoval);
}
private void introduceRemoveHostWithEdgesAddNewEdgesToOtherHost(int i) throws Exception {
IPatternMatch hostMatch = traceO.values().stream().filter(x -> x instanceof TrgMatch).findFirst().get();
Collection<IPatternMatch> dataflows = traceF.values().stream().filter(x -> x instanceof DataflowMatch && x.get(1) == hostMatch.get(0)).collect(Collectors.toList());
for (IPatternMatch removal : dataflows) {
if(model.refAddition.contains(removal)) {
model.refAddition.remove(removal);
} else {
model.refRemoval.add(removal);
removeReferenceMatch(model, removal);
}
}
Collection<MeasurementType> measurementTypes = dataflows.stream().map(y -> (MeasurementType)y.get(0)).collect(Collectors.toList());
for (MeasurementType measurementType : measurementTypes) {
Host host = (Host)traceO.keySet().stream().filter(x -> x instanceof Host).findFirst().get();
DataflowMatch newReferenceMatchFromMeasurementToHost = DataflowQuerySpecification.instance().newEmptyMatch();
newReferenceMatchFromMeasurementToHost.setHost(host);
newReferenceMatchFromMeasurementToHost.setType(measurementType);
if(!traceF.values().stream().filter(x -> x instanceof DataflowMatch).map(y -> (DataflowMatch)y).anyMatch(z -> z.getHost() == host && z.getType() == measurementType)) {
if(!model.refRemoval.contains(newReferenceMatchFromMeasurementToHost)) {
model.refAddition.add(newReferenceMatchFromMeasurementToHost);
}
}
}
model.objRemoval.add(hostMatch);
removeObjectMatch(model, hostMatch);
}
private void introduceAddNewActivationWithNewEdgeToReportAndPeriodicTrigger(int i) throws Exception {
Measure measure = eTelecareFactory.createMeasure();
measure.setName("newAction_"+i);
model.newObjects.add(measure);
ActionMatch newObjectMatch = ActionQuerySpecification.instance().newEmptyMatch();
newObjectMatch.setT(measure);
AfterMatch newReferenceMatchToPeriodicTrigger = AfterQuerySpecification.instance().newEmptyMatch();
newReferenceMatchToPeriodicTrigger.setA((NamedElement)traceO.keySet().stream().filter(x -> x instanceof PeriodicTrigger).findFirst().get());
newReferenceMatchToPeriodicTrigger.setB(measure);
AfterMatch newReferenceMatchToReport = AfterQuerySpecification.instance().newEmptyMatch();
newReferenceMatchToReport.setA(measure);
newReferenceMatchToReport.setB((NamedElement)traceO.keySet().stream().filter(x -> x instanceof Report).findFirst().get());
model.objAddition.add(newObjectMatch);
model.refAddition.add(newReferenceMatchToPeriodicTrigger);
model.refAddition.add(newReferenceMatchToReport);
}
private void removeObjectMatch(CategorizedModel model, IPatternMatch removal) {
traceO.values().remove(removal);
removeDontCareMatches(model, removal);
for (String param : removal.parameterNames()) {
Object object = removal.get(param);
if(traceO.containsKey(object) || traceF.containsKey(object)) {
if(!model.removablePart.contains(object))
model.changeblePart.add(object);
} else {
model.changeblePart.remove(object);
model.removablePart.add(object);
}
}
}
private void removeReferenceMatch(CategorizedModel model, IPatternMatch removal) {
traceF.values().remove(removal);
Object first = removal.get(0);
Object second = removal.get(1);
List<IPatternMatch> extendedRemovals = traceE.values().stream().filter(x -> x.get(0) == first && x.get(1) == second).collect(Collectors.toList());
traceE.values().removeAll(extendedRemovals);
for (IPatternMatch match : extendedRemovals) {
for (String param : match.parameterNames()) {
Object object = match.get(param);
if(traceO.containsKey(object) || traceF.containsKey(object)) {
if(!model.removablePart.contains(object))
model.changeblePart.add(object);
} else {
model.changeblePart.remove(object);
model.removablePart.add(object);
}
}
}
}
private void removeDontCareMatches(CategorizedModel model, IPatternMatch match) {
if(match instanceof InitMatch || match instanceof FinishMatch || match instanceof ActionMatch) {
Object object = match.get(0);
List<IPatternMatch> dontCare = traceF.get(object).stream().filter(x -> x instanceof AfterMatch)
.filter(y -> y.get(0) == object || y.get(1) == object).collect(Collectors.toList());
//traceF.values().removeAll(dontCare);
for (IPatternMatch removal : dontCare) {
removeReferenceMatch(model, removal);
}
model.dontCareRemoval.addAll(dontCare);
List<IPatternMatch> dontCareExtended = traceE.get(object).stream().filter(x ->
x instanceof AfterExtendedAMatch ||
x instanceof AfterExtendedBMatch)
.filter(y -> y.get(0) == object || y.get(1) == object).collect(Collectors.toList());
traceE.values().removeAll(dontCareExtended);
model.dontCareRemoval.addAll(dontCareExtended);
}
if(match instanceof TrgMatch) {
Object object = match.get(0);
List<IPatternMatch> dontCare = traceF.get(object).stream().filter(x -> x instanceof DataflowMatch)
.filter(y -> y.get(1) == object).collect(Collectors.toList());
//traceF.values().removeAll(dontCare);
for (IPatternMatch removal : dontCare) {
removeReferenceMatch(model, removal);
}
model.dontCareRemoval.addAll(dontCare);
List<IPatternMatch> dontCareExtended = traceE.get(object).stream().filter(x -> x instanceof DataflowExtendedMatch)
.filter(y -> y.get(1) == object).collect(Collectors.toList());
traceE.values().removeAll(dontCareExtended);
model.dontCareRemoval.addAll(dontCareExtended);
}
if(match instanceof SrcMatch) {
Object object = match.get(0);
List<IPatternMatch> dontCare = traceF.get(object).stream().filter(x -> x instanceof DataflowMatch)
.filter(y -> y.get(0) == object).collect(Collectors.toList());
//traceF.values().removeAll(dontCare);
for (IPatternMatch removal : dontCare) {
removeReferenceMatch(model, removal);
}
model.dontCareRemoval.addAll(dontCare);
List<IPatternMatch> dontCareExtended = traceE.get(object).stream().filter(x -> x instanceof DataflowExtendedMatch)
.filter(y -> y.get(0) == object).collect(Collectors.toList());
traceE.values().removeAll(dontCareExtended);
model.dontCareRemoval.addAll(dontCareExtended);
}
}
// private void loadResource(String path) {
// ResourceSet rSet = new ResourceSetImpl();
// resource = rSet.getResource(URI.createFileURI(path), true);
public Multimap<Object, IPatternMatch> getTraceO() {
return traceO;
}
public Multimap<Object, IPatternMatch> getTraceF() {
return traceF;
}
enum ChangeTypes {
RemoveInformationTypeWithEdges,
RemoveHostWithEdgesAddNewEdgesToOtherHost,
AddNewActivationWithNewEdgeToReportAndPeriodicTrigger
}
}
|
package org.opencms.ade.sitemap;
import org.opencms.ade.configuration.CmsADEConfigData;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.configuration.CmsFunctionReference;
import org.opencms.ade.configuration.CmsModelPageConfig;
import org.opencms.ade.configuration.CmsResourceTypeConfig;
import org.opencms.ade.detailpage.CmsDetailPageConfigurationWriter;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry.EntryType;
import org.opencms.ade.sitemap.shared.CmsDetailPageTable;
import org.opencms.ade.sitemap.shared.CmsNewResourceInfo;
import org.opencms.ade.sitemap.shared.CmsSitemapChange;
import org.opencms.ade.sitemap.shared.CmsSitemapChange.ChangeType;
import org.opencms.ade.sitemap.shared.CmsSitemapClipboardData;
import org.opencms.ade.sitemap.shared.CmsSitemapData;
import org.opencms.ade.sitemap.shared.CmsSitemapInfo;
import org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService;
import org.opencms.configuration.CmsDefaultUserSettings;
import org.opencms.db.CmsAlias;
import org.opencms.db.CmsAliasManager;
import org.opencms.db.CmsRewriteAlias;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeFolderSubSitemap;
import org.opencms.file.types.CmsResourceTypeUnknownFolder;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsCoreService;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.gwt.CmsTemplateFinder;
import org.opencms.gwt.shared.CmsBrokenLinkBean;
import org.opencms.gwt.shared.CmsClientLock;
import org.opencms.gwt.shared.CmsCoreData;
import org.opencms.gwt.shared.CmsCoreData.AdeContext;
import org.opencms.gwt.shared.CmsListInfoBean;
import org.opencms.gwt.shared.alias.CmsAliasEditValidationReply;
import org.opencms.gwt.shared.alias.CmsAliasEditValidationRequest;
import org.opencms.gwt.shared.alias.CmsAliasImportResult;
import org.opencms.gwt.shared.alias.CmsAliasInitialFetchResult;
import org.opencms.gwt.shared.alias.CmsAliasSaveValidationRequest;
import org.opencms.gwt.shared.alias.CmsAliasTableRow;
import org.opencms.gwt.shared.alias.CmsRewriteAliasTableRow;
import org.opencms.gwt.shared.alias.CmsRewriteAliasValidationReply;
import org.opencms.gwt.shared.alias.CmsRewriteAliasValidationRequest;
import org.opencms.gwt.shared.property.CmsClientProperty;
import org.opencms.gwt.shared.property.CmsPropertyModification;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.json.JSONArray;
import org.opencms.jsp.CmsJspNavBuilder;
import org.opencms.jsp.CmsJspNavBuilder.Visibility;
import org.opencms.jsp.CmsJspNavElement;
import org.opencms.loader.CmsLoaderException;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsSecurityException;
import org.opencms.site.CmsSite;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplaceManager;
import org.opencms.workplace.CmsWorkplaceMessages;
import org.opencms.workplace.explorer.CmsExplorerTypeAccess;
import org.opencms.workplace.explorer.CmsExplorerTypeSettings;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.CmsXmlDynamicFunctionHandler;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentProperty;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
/**
* Handles all RPC services related to the vfs sitemap.<p>
*
* @since 8.0.0
*
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapServiceAsync
*/
public class CmsVfsSitemapService extends CmsGwtService implements I_CmsSitemapService {
/** Helper class for representing information about a lock. */
protected class LockInfo {
/** The lock state. */
private CmsLock m_lock;
/** True if the lock was just locked. */
private boolean m_wasJustLocked;
/**
* Creates a new LockInfo object.<p>
*
* @param lock the lock state
* @param wasJustLocked true if the lock was just locked
*/
public LockInfo(CmsLock lock, boolean wasJustLocked) {
m_lock = lock;
m_wasJustLocked = wasJustLocked;
}
/**
* Returns the lock state.<p>
*
* @return the lock state
*/
public CmsLock getLock() {
return m_lock;
}
/**
* Returns true if the lock was just locked.<p>
*
* @return true if the lock was just locked
*/
public boolean wasJustLocked() {
return m_wasJustLocked;
}
}
/** The path of the JSP used to download aliases. */
public static final String ALIAS_DOWNLOAD_PATH = "/system/modules/org.opencms.ade.sitemap/pages/download-aliases.jsp";
/** The path to the JSP used to upload aliases. */
public static final String ALIAS_IMPORT_PATH = "/system/modules/org.opencms.ade.sitemap/pages/import-aliases.jsp";
/** The configuration key for the functionDetail attribute in the container.info property. */
public static final String KEY_FUNCTION_DETAIL = "functionDetail";
/** The additional user info key for deleted list. */
private static final String ADDINFO_ADE_DELETED_LIST = "ADE_DELETED_LIST";
/** The additional user info key for modified list. */
private static final String ADDINFO_ADE_MODIFIED_LIST = "ADE_MODIFIED_LIST";
/** The lock table to prevent multiple users from editing the alias table concurrently. */
private static CmsAliasEditorLockTable aliasEditorLockTable = new CmsAliasEditorLockTable();
/** The table containing the alias import results. */
private static CmsAliasImportResponseTable aliasImportResponseTable = new CmsAliasImportResponseTable();
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsVfsSitemapService.class);
/** The redirect recource type name. */
private static final String RECOURCE_TYPE_NAME_REDIRECT = "htmlredirect";
/** The redirect target XPath. */
private static final String REDIRECT_LINK_TARGET_XPATH = "Link";
/** Serialization uid. */
private static final long serialVersionUID = -7236544324371767330L;
/** The VFS path of the redirect copy page for navigation level entries. */
private static final String SUB_LEVEL_REDIRECT_COPY_PAGE = "/system/modules/org.opencms.ade.sitemap/pages/sub-level-redirect.html";
/** The navigation builder. */
private CmsJspNavBuilder m_navBuilder;
/**
* Adds an alias import result.<p>
*
* @param results the list of alias import results to add
*
* @return the key to retrieve the alias import results
*/
public static String addAliasImportResult(List<CmsAliasImportResult> results) {
return aliasImportResponseTable.addImportResult(results);
}
/**
* Returns a new configured service instance.<p>
*
* @param request the current request
*
* @return a new service instance
*/
public static CmsVfsSitemapService newInstance(HttpServletRequest request) {
CmsVfsSitemapService service = new CmsVfsSitemapService();
service.setCms(CmsFlexController.getCmsObject(request));
service.setRequest(request);
return service;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createSubSitemap(org.opencms.util.CmsUUID)
*/
public CmsSitemapChange createSubSitemap(CmsUUID entryId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(entryId);
ensureLock(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
createSitemapContentFolder(cms, subSitemapFolder);
subSitemapFolder.setType(getSubsitemapType());
cms.writeResource(subSitemapFolder);
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getAliasImportResult(java.lang.String)
*/
public List<CmsAliasImportResult> getAliasImportResult(String resultKey) {
return aliasImportResponseTable.getAndRemove(resultKey);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getAliasTable()
*/
public CmsAliasInitialFetchResult getAliasTable() throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsAliasManager aliasManager = OpenCms.getAliasManager();
List<CmsAlias> aliases = aliasManager.getAliasesForSite(cms, cms.getRequestContext().getSiteRoot());
List<CmsAliasTableRow> rows = new ArrayList<CmsAliasTableRow>();
CmsAliasInitialFetchResult result = new CmsAliasInitialFetchResult();
for (CmsAlias alias : aliases) {
CmsAliasTableRow row = createAliasTableEntry(cms, alias);
rows.add(row);
}
result.setRows(rows);
List<CmsRewriteAlias> rewriteAliases = aliasManager.getRewriteAliases(
cms,
cms.getRequestContext().getSiteRoot());
List<CmsRewriteAliasTableRow> rewriteRows = new ArrayList<CmsRewriteAliasTableRow>();
for (CmsRewriteAlias rewriteAlias : rewriteAliases) {
CmsRewriteAliasTableRow rewriteRow = new CmsRewriteAliasTableRow(
rewriteAlias.getId(),
rewriteAlias.getPatternString(),
rewriteAlias.getReplacementString(),
rewriteAlias.getMode());
rewriteRows.add(rewriteRow);
}
result.setRewriteRows(rewriteRows);
CmsUser otherLockOwner = aliasEditorLockTable.update(cms, cms.getRequestContext().getSiteRoot());
if (otherLockOwner != null) {
result.setAliasLockOwner(otherLockOwner.getName());
}
result.setDownloadUrl(OpenCms.getLinkManager().substituteLinkForRootPath(cms, ALIAS_DOWNLOAD_PATH));
return result;
} catch (Throwable e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getChildren(java.lang.String, org.opencms.util.CmsUUID, int)
*/
public CmsClientSitemapEntry getChildren(String entryPointUri, CmsUUID entryId, int levels) throws CmsRpcException {
CmsClientSitemapEntry entry = null;
try {
CmsObject cms = getCmsObject();
//ensure that root ends with a '/' if it's a folder
CmsResource rootRes = cms.readResource(entryId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String root = cms.getSitePath(rootRes);
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
root,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
boolean isRoot = root.equals(entryPointUri);
entry = toClientEntry(navElement, isRoot);
if ((levels > 0) && (isRoot || (rootRes.isFolder() && (!isSubSitemap(navElement))))) {
entry.setSubEntries(getChildren(root, levels, null), null);
}
} catch (Throwable e) {
error(e);
}
return entry;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#mergeSubSitemap(java.lang.String, org.opencms.util.CmsUUID)
*/
public CmsSitemapChange mergeSubSitemap(String entryPoint, CmsUUID subSitemapId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(subSitemapId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(subSitemapFolder);
subSitemapFolder.setType(OpenCms.getResourceManager().getResourceType(
CmsResourceTypeFolder.RESOURCE_TYPE_NAME).getTypeId());
cms.writeResource(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
String sitemapConfigName = CmsStringUtil.joinPaths(
sitePath,
CmsADEManager.CONTENT_FOLDER_NAME,
CmsADEManager.CONFIG_FILE_NAME);
if (cms.existsResource(sitemapConfigName)) {
cms.deleteResource(sitemapConfigName, CmsResource.DELETE_PRESERVE_SIBLINGS);
}
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(
cms.getSitePath(subSitemapFolder),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
entry = getChildren(entryPoint, subSitemapId, 1);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#prefetch(java.lang.String)
*/
public CmsSitemapData prefetch(String sitemapUri) throws CmsRpcException {
CmsSitemapData result = null;
CmsObject cms = getCmsObject();
try {
String openPath = getRequest().getParameter(CmsCoreData.PARAM_PATH);
if (!isValidOpenPath(cms, openPath)) {
// if no path is supplied, start from root
openPath = "/";
}
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(openPath));
Map<String, CmsXmlContentProperty> propertyConfig = new LinkedHashMap<String, CmsXmlContentProperty>(
configData.getPropertyConfigurationAsMap());
Map<String, CmsClientProperty> parentProperties = generateParentProperties(configData.getBasePath());
String siteRoot = cms.getRequestContext().getSiteRoot();
String exportRfsPrefix = OpenCms.getStaticExportManager().getDefaultRfsPrefix();
CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
boolean isSecure = site.hasSecureServer();
String parentSitemap = null;
if (configData.getBasePath() != null) {
CmsADEConfigData parentConfigData = OpenCms.getADEManager().lookupConfiguration(
cms,
CmsResource.getParentFolder(configData.getBasePath()));
parentSitemap = parentConfigData.getBasePath();
if (parentSitemap != null) {
parentSitemap = cms.getRequestContext().removeSiteRoot(parentSitemap);
}
}
String noEdit = "";
CmsNewResourceInfo defaultNewInfo = null;
List<CmsNewResourceInfo> newResourceInfos = null;
CmsDetailPageTable detailPages = null;
List<CmsNewResourceInfo> resourceTypeInfos = null;
boolean canEditDetailPages = false;
boolean isOnlineProject = CmsProject.isOnlineProject(cms.getRequestContext().getCurrentProject().getUuid());
Locale locale = CmsLocaleManager.getDefaultLocale();
try {
String basePath = configData.getBasePath();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsResource baseDir = rootCms.readResource(basePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
locale = CmsLocaleManager.getMainLocale(cms, baseDir);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
detailPages = new CmsDetailPageTable(configData.getAllDetailPages());
if (!isOnlineProject) {
newResourceInfos = getNewResourceInfos(cms, configData, locale);
CmsResource modelResource = null;
if (configData.getDefaultModelPage() != null) {
if (cms.existsResource(configData.getDefaultModelPage().getResource().getStructureId())) {
modelResource = configData.getDefaultModelPage().getResource();
} else {
try {
modelResource = cms.readResource(
cms.getSitePath(configData.getDefaultModelPage().getResource()),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
if ((modelResource == null) && !newResourceInfos.isEmpty()) {
try {
modelResource = cms.readResource(newResourceInfos.get(0).getCopyResourceId());
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
if (modelResource != null) {
resourceTypeInfos = getResourceTypeInfos(
getCmsObject(),
configData.getResourceTypes(),
configData.getFunctionReferences(),
modelResource,
locale);
try {
defaultNewInfo = createNewResourceInfo(cms, modelResource, locale);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
canEditDetailPages = !(configData.isModuleConfiguration());
}
if (isOnlineProject) {
noEdit = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_SITEMAP_NO_EDIT_ONLINE_0);
}
List<String> allPropNames = getPropertyNames(cms);
String returnCode = getRequest().getParameter(CmsCoreData.PARAM_RETURNCODE);
if (!isValidReturnCode(returnCode)) {
returnCode = null;
}
cms.getRequestContext().getSiteRoot();
String aliasImportUrl = OpenCms.getLinkManager().substituteLinkForRootPath(cms, ALIAS_IMPORT_PATH);
boolean canEditAliases = OpenCms.getAliasManager().hasPermissionsForMassEdit(cms, siteRoot);
List<CmsListInfoBean> subsitemapFolderTypeInfos = collectSitemapTypeInfos(cms, configData);
result = new CmsSitemapData(
(new CmsTemplateFinder(cms)).getTemplates(),
propertyConfig,
getClipboardData(),
CmsCoreService.newInstance(getRequest()).getContextMenuEntries(
configData.getResource().getStructureId(),
AdeContext.sitemap),
parentProperties,
allPropNames,
exportRfsPrefix,
isSecure,
noEdit,
isDisplayToolbar(getRequest()),
defaultNewInfo,
newResourceInfos,
createResourceTypeInfo(OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT), null),
createNavigationLevelTypeInfo(),
getSitemapInfo(configData.getBasePath()),
parentSitemap,
getRootEntry(configData.getBasePath(), openPath),
openPath,
30,
detailPages,
resourceTypeInfos,
returnCode,
canEditDetailPages,
aliasImportUrl,
canEditAliases,
OpenCms.getWorkplaceManager().getDefaultUserSettings().getSubsitemapCreationMode() == CmsDefaultUserSettings.SubsitemapCreationMode.createfolder,
subsitemapFolderTypeInfos);
} catch (Throwable e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#save(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange save(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
CmsSitemapChange result = null;
try {
result = saveInternal(entryPoint, change);
} catch (Exception e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#saveAliases(org.opencms.gwt.shared.alias.CmsAliasSaveValidationRequest)
*/
public CmsAliasEditValidationReply saveAliases(CmsAliasSaveValidationRequest saveRequest) throws CmsRpcException {
CmsObject cms = getCmsObject();
CmsAliasBulkEditHelper helper = new CmsAliasBulkEditHelper(cms);
try {
return helper.saveAliases(saveRequest);
} catch (Exception e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#saveSync(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange saveSync(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
return save(entryPoint, change);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#updateAliasEditorStatus(boolean)
*/
public void updateAliasEditorStatus(boolean editing) {
CmsObject cms = getCmsObject();
if (editing) {
aliasEditorLockTable.update(cms, cms.getRequestContext().getSiteRoot());
} else {
aliasEditorLockTable.clear(cms, cms.getRequestContext().getSiteRoot());
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#validateAliases(org.opencms.gwt.shared.alias.CmsAliasEditValidationRequest)
*/
public CmsAliasEditValidationReply validateAliases(CmsAliasEditValidationRequest validationRequest) {
CmsObject cms = getCmsObject();
CmsAliasBulkEditHelper helper = new CmsAliasBulkEditHelper(cms);
return helper.validateAliases(validationRequest);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#validateRewriteAliases(org.opencms.gwt.shared.alias.CmsRewriteAliasValidationRequest)
*/
public CmsRewriteAliasValidationReply validateRewriteAliases(CmsRewriteAliasValidationRequest validationRequest) {
CmsRewriteAliasValidationReply result = new CmsRewriteAliasValidationReply();
for (CmsRewriteAliasTableRow editedRow : validationRequest.getEditedRewriteAliases()) {
try {
String patternString = editedRow.getPatternString();
Pattern.compile(patternString);
} catch (PatternSyntaxException e) {
result.addError(editedRow.getId(), "Syntax error in regular expression: " + e.getMessage());
}
}
return result;
}
/**
* Creates a "broken link" bean based on a resource.<p>
*
* @param resource the resource
*
* @return the "broken link" bean with the data from the resource
*
* @throws CmsException if something goes wrong
*/
protected CmsBrokenLinkBean createSitemapBrokenLinkBean(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsProperty titleProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, true);
String defaultTitle = "";
String title = titleProp.getValue(defaultTitle);
String path = cms.getSitePath(resource);
String subtitle = path;
return new CmsBrokenLinkBean(title, subtitle);
}
/**
* Locks the given resource with a temporary, if not already locked by the current user.
* Will throw an exception if the resource could not be locked for the current user.<p>
*
* @param resource the resource to lock
*
* @return the assigned lock
*
* @throws CmsException if the resource could not be locked
*/
protected LockInfo ensureLockAndGetInfo(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
boolean justLocked = false;
List<CmsResource> blockingResources = cms.getBlockingLockedResources(resource);
if ((blockingResources != null) && !blockingResources.isEmpty()) {
throw new CmsException(org.opencms.gwt.Messages.get().container(
org.opencms.gwt.Messages.ERR_RESOURCE_HAS_BLOCKING_LOCKED_CHILDREN_1,
cms.getSitePath(resource)));
}
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsLock lock = cms.getLock(resource);
if (!lock.isOwnedBy(user)) {
cms.lockResourceTemporary(resource);
lock = cms.getLock(resource);
justLocked = true;
} else if (!lock.isOwnedInProjectBy(user, cms.getRequestContext().getCurrentProject())) {
cms.changeLock(resource);
lock = cms.getLock(resource);
justLocked = true;
}
return new LockInfo(lock, justLocked);
}
/**
* Internal method for saving a sitemap.<p>
*
* @param entryPoint the URI of the sitemap to save
* @param change the change to save
*
* @return list of changed sitemap entries
*
* @throws CmsException
*/
protected CmsSitemapChange saveInternal(String entryPoint, CmsSitemapChange change) throws CmsException {
ensureSession();
switch (change.getChangeType()) {
case clipboardOnly:
// do nothing
break;
case remove:
change = removeEntryFromNavigation(change);
break;
case undelete:
change = undelete(change);
break;
default:
change = applyChange(entryPoint, change);
}
setClipboardData(change.getClipBoardData());
return change;
}
/**
* Converts a sequence of properties to a map of client-side property beans.<p>
*
* @param props the sequence of properties
* @param preserveOrigin if true, the origin of the properties should be copied to the client properties
*
* @return the map of client properties
*
*/
Map<String, CmsClientProperty> createClientProperties(Iterable<CmsProperty> props, boolean preserveOrigin) {
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, preserveOrigin);
result.put(prop.getName(), clientProp);
}
return result;
}
/**
* Removes unnecessary locales from a container page.<p>
*
* @param containerPage the container page which should be changed
* @param localeRes the resource used to determine the locale
*
* @throws CmsException if something goes wrong
*/
void ensureSingleLocale(CmsXmlContainerPage containerPage, CmsResource localeRes) throws CmsException {
CmsObject cms = getCmsObject();
Locale mainLocale = CmsLocaleManager.getMainLocale(cms, localeRes);
OpenCms.getLocaleManager();
Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
if (containerPage.hasLocale(mainLocale)) {
removeAllLocalesExcept(containerPage, mainLocale);
// remove other locales
} else if (containerPage.hasLocale(defaultLocale)) {
containerPage.copyLocale(defaultLocale, mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else if (containerPage.getLocales().size() > 0) {
containerPage.copyLocale(containerPage.getLocales().get(0), mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else {
containerPage.addLocale(cms, mainLocale);
}
}
/**
* Gets the properties of a resource as a map of client properties.<p>
*
* @param cms the CMS context to use
* @param res the resource whose properties to read
* @param search true if the inherited properties should be read
*
* @return the client properties as a map
*
* @throws CmsException if something goes wrong
*/
Map<String, CmsClientProperty> getClientProperties(CmsObject cms, CmsResource res, boolean search)
throws CmsException {
List<CmsProperty> props = cms.readPropertyObjects(res, search);
Map<String, CmsClientProperty> result = createClientProperties(props, false);
return result;
}
/**
* Adds a function detail element to a container page.<p>
*
* @param cms the current CMS context
* @param page the container page which should be changed
* @param containerName the name of the container which should be used for function detail elements
* @param elementId the structure id of the element to add
* @param formatterId the structure id of the formatter for the element
*
* @throws CmsException if something goes wrong
*/
private void addFunctionDetailElement(
CmsObject cms,
CmsXmlContainerPage page,
String containerName,
CmsUUID elementId,
CmsUUID formatterId) throws CmsException {
List<Locale> pageLocales = page.getLocales();
for (Locale locale : pageLocales) {
CmsContainerPageBean bean = page.getContainerPage(cms, locale);
List<CmsContainerBean> containerBeans = new ArrayList<CmsContainerBean>();
Collection<CmsContainerBean> originalContainers = bean.getContainers().values();
if ((containerName == null) && !originalContainers.isEmpty()) {
CmsContainerBean firstContainer = originalContainers.iterator().next();
containerName = firstContainer.getName();
}
boolean foundContainer = false;
for (CmsContainerBean cntBean : originalContainers) {
boolean isDetailTarget = cntBean.getName().equals(containerName);
if (isDetailTarget && !foundContainer) {
foundContainer = true;
List<CmsContainerElementBean> newElems = new ArrayList<CmsContainerElementBean>();
newElems.addAll(cntBean.getElements());
CmsContainerElementBean newElement = new CmsContainerElementBean(
elementId,
formatterId,
new HashMap<String, String>(),
false);
newElems.add(0, newElement);
CmsContainerBean newCntBean = new CmsContainerBean(cntBean.getName(), cntBean.getType(), newElems);
containerBeans.add(newCntBean);
} else {
containerBeans.add(cntBean);
}
}
if (!foundContainer) {
throw new CmsException(Messages.get().container(
Messages.ERR_NO_FUNCTION_DETAIL_CONTAINER_1,
page.getFile().getRootPath()));
}
CmsContainerPageBean bean2 = new CmsContainerPageBean(locale, new ArrayList<CmsContainerBean>(
containerBeans));
page.writeContainerPage(cms, locale, bean2);
}
}
/**
* Applys the given change to the VFS.<p>
*
* @param entryPoint the sitemap entry-point
* @param change the change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange applyChange(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource configFile = null;
// lock the config file first, to avoid half done changes
if (change.hasDetailPageInfos()) {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(entryPoint));
if (!configData.isModuleConfiguration() && (configData.getResource() != null)) {
configFile = configData.getResource();
}
if (configFile != null) {
ensureLock(configFile);
}
}
if (change.isNew()) {
CmsClientSitemapEntry newEntry = createNewEntry(entryPoint, change);
change.setUpdatedEntry(newEntry);
change.setEntryId(newEntry.getId());
} else if (change.getChangeType() == ChangeType.delete) {
delete(change);
} else if (change.getEntryId() != null) {
modifyEntry(change);
}
if (change.hasDetailPageInfos() && (configFile != null)) {
saveDetailPages(change.getDetailPageInfos(), configFile, change.getEntryId(), change.getUpdatedEntry());
tryUnlock(configFile);
}
return change;
}
/**
* Changes the navigation for a moved entry and its neighbors.<p>
*
* @param change the sitemap change
* @param entryFolder the moved entry
*
* @throws CmsException if something goes wrong
*/
private void applyNavigationChanges(CmsSitemapChange change, CmsResource entryFolder) throws CmsException {
CmsObject cms = getCmsObject();
String parentPath = null;
if (change.hasNewParent()) {
CmsResource parent = cms.readResource(change.getParentId());
parentPath = cms.getSitePath(parent);
} else {
parentPath = CmsResource.getParentFolder(cms.getSitePath(entryFolder));
}
List<CmsJspNavElement> navElements = getNavBuilder().getNavigationForFolder(
parentPath,
Visibility.all,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsSitemapNavPosCalculator npc = new CmsSitemapNavPosCalculator(navElements, entryFolder, change.getPosition());
List<CmsJspNavElement> navs = npc.getNavigationChanges();
List<CmsResource> needToUnlock = new ArrayList<CmsResource>();
try {
for (CmsJspNavElement nav : navs) {
LockInfo lockInfo = ensureLockAndGetInfo(nav.getResource());
if (!nav.getResource().equals(entryFolder) && lockInfo.wasJustLocked()) {
needToUnlock.add(nav.getResource());
}
}
for (CmsJspNavElement nav : navs) {
CmsProperty property = new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
"" + nav.getNavPosition(),
null);
cms.writePropertyObject(cms.getSitePath(nav.getResource()), property);
}
} finally {
for (CmsResource lockedRes : needToUnlock) {
try {
cms.unlockResource(lockedRes);
} catch (CmsException e) {
// we catch this because we still want to unlock the other resources
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
/**
* Builds the list info bean for a resource type which can be used as a sub-sitemap folder.<p>
*
* @param sitemapType the sitemap folder type
*
* @return the list info bean for the given type
*/
private CmsListInfoBean buildSitemapTypeInfo(I_CmsResourceType sitemapType) {
CmsListInfoBean result = new CmsListInfoBean();
CmsWorkplaceManager wm = OpenCms.getWorkplaceManager();
String typeName = sitemapType.getTypeName();
Locale wpLocale = wm.getWorkplaceLocale(getCmsObject());
String title = typeName;
String description = "";
try {
title = CmsWorkplaceMessages.getResourceTypeName(wpLocale, typeName);
} catch (Throwable e) {
LOG.warn(e.getLocalizedMessage(), e);
}
try {
description = CmsWorkplaceMessages.getResourceTypeDescription(wpLocale, typeName);
} catch (Throwable e) {
LOG.warn(e.getLocalizedMessage(), e);
}
result.setResourceType(typeName);
result.setTitle(title);
result.setSubTitle(description);
return result;
}
/**
* Gets the information for the available sitemap folder types.<p>
*
* @param cms the current CMS context
* @param configData the configuration data for the current subsitemap
* @return the list info beans corresponding to available sitemap folder types
*/
private List<CmsListInfoBean> collectSitemapTypeInfos(CmsObject cms, CmsADEConfigData configData) {
List<CmsListInfoBean> subsitemapFolderTypeInfos = new ArrayList<CmsListInfoBean>();
List<Integer> sitemapTypeIds = CmsResourceTypeFolderSubSitemap.getSubSitemapResourceTypeIds();
String checkPath = configData.getBasePath();
if (checkPath != null) {
checkPath = cms.getRequestContext().removeSiteRoot(checkPath);
} else {
checkPath = "/";
}
CmsResource checkResource = null;
try {
checkResource = cms.readResource(checkPath);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
for (Integer typeId : sitemapTypeIds) {
try {
I_CmsResourceType sitemapType = OpenCms.getResourceManager().getResourceType(typeId.intValue());
String typeName = sitemapType.getTypeName();
CmsExplorerTypeSettings explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(typeName);
if ((explorerType != null) && (checkResource != null)) {
try {
CmsExplorerTypeAccess access = explorerType.getAccess();
if (!access.getPermissions(cms, checkResource).requiresControlPermission()) {
continue;
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
CmsListInfoBean infoBean = buildSitemapTypeInfo(sitemapType);
subsitemapFolderTypeInfos.add(infoBean);
} catch (CmsLoaderException e) {
LOG.warn("Could not read sitemap folder type " + typeId + ": " + e.getLocalizedMessage(), e);
}
}
return subsitemapFolderTypeInfos;
}
/**
* Creates a client alias bean from a server-side alias.<p>
*
* @param cms the current CMS context
* @param alias the alias to convert
*
* @return the alias table row
*
* @throws CmsException if something goes wrong
*/
private CmsAliasTableRow createAliasTableEntry(CmsObject cms, CmsAlias alias) throws CmsException {
CmsResource resource = cms.readResource(alias.getStructureId(), CmsResourceFilter.ALL);
CmsAliasTableRow result = new CmsAliasTableRow();
result.setStructureId(alias.getStructureId());
result.setOriginalStructureId(alias.getStructureId());
result.setAliasPath(alias.getAliasPath());
result.setResourcePath(cms.getSitePath(resource));
result.setKey((new CmsUUID()).toString());
result.setMode(alias.getMode());
result.setChanged(false);
return result;
}
/**
* Creates a client property bean from a server-side property.<p>
*
* @param prop the property from which to create the client property
* @param preserveOrigin if true, the origin will be copied into the new object
*
* @return the new client property
*/
private CmsClientProperty createClientProperty(CmsProperty prop, boolean preserveOrigin) {
CmsClientProperty result = new CmsClientProperty(
prop.getName(),
prop.getStructureValue(),
prop.getResourceValue());
if (preserveOrigin) {
result.setOrigin(prop.getOrigin());
}
return result;
}
/**
* Creates a navigation level type info.<p>
*
* @return the navigation level type info bean
*
* @throws CmsException if reading the sub level redirect copy page fails
*/
private CmsNewResourceInfo createNavigationLevelTypeInfo() throws CmsException {
String name = CmsResourceTypeFolder.getStaticTypeName();
Locale locale = getWorkplaceLocale();
String subtitle = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_NAVIGATION_LEVEL_SUBTITLE_0);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subtitle)) {
subtitle = CmsWorkplaceMessages.getResourceTypeName(locale, name);
}
CmsNewResourceInfo result = new CmsNewResourceInfo(
CmsResourceTypeFolder.getStaticTypeId(),
name,
Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_NAVIGATION_LEVEL_TITLE_0),
subtitle,
getCmsObject().readResource(SUB_LEVEL_REDIRECT_COPY_PAGE).getStructureId(),
false,
subtitle);
result.setCreateParameter(CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER);
return result;
}
/**
* Creates a new page in navigation.<p>
*
* @param entryPoint the site-map entry-point
* @param change the new change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry createNewEntry(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsClientSitemapEntry newEntry = null;
if (change.getParentId() != null) {
CmsResource parentFolder = cms.readResource(change.getParentId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String entryPath = "";
CmsResource entryFolder = null;
CmsResource newRes = null;
byte[] content = null;
List<CmsProperty> properties = Collections.emptyList();
CmsResource copyPage = null;
if (change.getNewCopyResourceId() != null) {
copyPage = cms.readResource(change.getNewCopyResourceId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
content = cms.readFile(copyPage).getContents();
properties = cms.readPropertyObjects(copyPage, false);
}
if (isRedirectType(change.getNewResourceTypeId())) {
entryPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName());
newRes = cms.createResource(
entryPath,
change.getNewResourceTypeId(),
null,
Collections.singletonList(new CmsProperty(
CmsPropertyDefinition.PROPERTY_TITLE,
change.getName(),
null)));
cms.writePropertyObjects(newRes, generateInheritProperties(change, newRes));
applyNavigationChanges(change, newRes);
} else {
String entryFolderPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName() + "/");
boolean idWasNull = change.getEntryId() == null;
// we don't really need to create a folder object here anymore.
if (idWasNull) {
// need this for calculateNavPosition, even though the id will get overwritten
change.setEntryId(new CmsUUID());
}
boolean isFunctionDetail = false;
boolean isNavigationLevel = false;
if (change.getCreateParameter() != null) {
if (CmsUUID.isValidUUID(change.getCreateParameter())) {
isFunctionDetail = true;
} else if (CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER.equals(change.getCreateParameter())) {
isNavigationLevel = true;
}
}
String folderType = CmsResourceTypeFolder.getStaticTypeName();
String createSitemapFolderType = change.getCreateSitemapFolderType();
if (createSitemapFolderType != null) {
folderType = createSitemapFolderType;
}
int folderTypeId = OpenCms.getResourceManager().getResourceType(folderType).getTypeId();
entryFolder = new CmsResource(
change.getEntryId(),
new CmsUUID(),
entryFolderPath,
folderTypeId,
true,
0,
cms.getRequestContext().getCurrentProject().getUuid(),
CmsResource.STATE_NEW,
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
1,
0,
System.currentTimeMillis(),
0);
List<CmsProperty> folderProperties = generateInheritProperties(change, entryFolder);
if (isNavigationLevel) {
folderProperties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_DEFAULT_FILE,
CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER,
null));
}
entryFolder = cms.createResource(entryFolderPath, folderTypeId, null, folderProperties);
if (createSitemapFolderType != null) {
createSitemapContentFolder(cms, entryFolder);
}
if (idWasNull) {
change.setEntryId(entryFolder.getStructureId());
}
applyNavigationChanges(change, entryFolder);
entryPath = CmsStringUtil.joinPaths(entryFolderPath, "index.html");
boolean isContainerPage = change.getNewResourceTypeId() == CmsResourceTypeXmlContainerPage.getContainerPageTypeIdSafely();
if (isContainerPage && (copyPage != null)) {
// do *NOT* get this from the cache, because we perform some destructive operation on the XML content
CmsXmlContainerPage page = CmsXmlContainerPageFactory.unmarshal(
cms,
cms.readFile(copyPage),
true,
true);
ensureSingleLocale(page, entryFolder);
if (isFunctionDetail) {
String functionDetailContainer = getFunctionDetailContainerName(parentFolder);
CmsUUID functionStructureId = new CmsUUID(change.getCreateParameter());
CmsResource functionFormatter = cms.readResource(
CmsXmlDynamicFunctionHandler.FORMATTER_PATH,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
addFunctionDetailElement(
cms,
page,
functionDetailContainer,
functionStructureId,
functionFormatter.getStructureId());
}
content = page.marshal();
}
newRes = cms.createResource(
entryPath,
copyPage != null ? copyPage.getTypeId() : change.getNewResourceTypeId(),
content,
properties);
cms.writePropertyObjects(newRes, generateOwnProperties(change));
}
if (entryFolder != null) {
tryUnlock(entryFolder);
String sitePath = cms.getSitePath(entryFolder);
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
newEntry.setSubEntries(getChildren(sitePath, 1, null), null);
newEntry.setChildrenLoadedInitially(true);
}
if (newRes != null) {
tryUnlock(newRes);
}
if (newEntry == null) {
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(
cms.getSitePath(newRes),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
}
// mark position as not set
newEntry.setPosition(-1);
newEntry.setNew(true);
change.getClipBoardData().getModifications().remove(null);
change.getClipBoardData().getModifications().put(newEntry.getId(), newEntry);
}
return newEntry;
}
/**
* Creates a new resource info to a given model page resource.<p>
*
* @param cms the current CMS context
* @param modelResource the model page resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the new resource info
*
* @throws CmsException if something goes wrong
*/
private CmsNewResourceInfo createNewResourceInfo(CmsObject cms, CmsResource modelResource, Locale locale)
throws CmsException {
// if model page got overwritten by another resource, reread from site path
if (!cms.existsResource(modelResource.getStructureId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
modelResource = cms.readResource(cms.getSitePath(modelResource), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
int typeId = modelResource.getTypeId();
String name = OpenCms.getResourceManager().getResourceType(typeId).getTypeName();
String title = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
String description = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
try {
CmsGallerySearchResult result = CmsGallerySearch.searchById(cms, modelResource.getStructureId(), locale);
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getTitle())) {
title = result.getTitle();
}
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getDescription())) {
description = result.getDescription();
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
boolean editable = false;
try {
CmsResource freshModelResource = cms.readResource(
modelResource.getStructureId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
editable = cms.hasPermissions(
freshModelResource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.DEFAULT);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
typeId,
name,
title,
description,
modelResource.getStructureId(),
editable,
description);
Float navpos = null;
try {
CmsProperty navposProp = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_NAVPOS, true);
String navposStr = navposProp.getValue();
if (navposStr != null) {
try {
navpos = Float.valueOf(navposStr);
} catch (NumberFormatException e) {
// noop
}
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
info.setNavPos(navpos);
info.setDate(CmsDateUtil.getDate(
new Date(modelResource.getDateLastModified()),
DateFormat.LONG,
getWorkplaceLocale()));
info.setVfsPath(modelResource.getRootPath());
return info;
}
/**
* Creates a resource type info bean for a given resource type.<p>
*
* @param resType the resource type
* @param copyResource the structure id of the copy resource
*
* @return the resource type info bean
*/
private CmsNewResourceInfo createResourceTypeInfo(I_CmsResourceType resType, CmsResource copyResource) {
String name = resType.getTypeName();
Locale locale = getWorkplaceLocale();
String subtitle = CmsWorkplaceMessages.getResourceTypeDescription(locale, name);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subtitle)) {
subtitle = CmsWorkplaceMessages.getResourceTypeName(locale, name);
}
if (copyResource != null) {
return new CmsNewResourceInfo(
copyResource.getTypeId(),
name,
CmsWorkplaceMessages.getResourceTypeName(locale, name),
CmsWorkplaceMessages.getResourceTypeDescription(locale, name),
copyResource.getStructureId(),
false,
subtitle);
} else {
return new CmsNewResourceInfo(resType.getTypeId(), name, CmsWorkplaceMessages.getResourceTypeName(
locale,
name), CmsWorkplaceMessages.getResourceTypeDescription(locale, name), null, false, subtitle);
}
}
/**
* Helper method for creating the .content folder of a sub-sitemap.<p>
*
* @param cms the current CMS context
* @param subSitemapFolder the sub-sitemap folder in which the .content folder should be created
*
* @throws CmsException if something goes wrong
* @throws CmsLoaderException
*/
private void createSitemapContentFolder(CmsObject cms, CmsResource subSitemapFolder)
throws CmsException, CmsLoaderException {
String sitePath = cms.getSitePath(subSitemapFolder);
String folderName = CmsStringUtil.joinPaths(sitePath, CmsADEManager.CONTENT_FOLDER_NAME + "/");
String sitemapConfigName = CmsStringUtil.joinPaths(folderName, CmsADEManager.CONFIG_FILE_NAME);
if (!cms.existsResource(folderName)) {
cms.createResource(
folderName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_FOLDER_TYPE).getTypeId());
}
I_CmsResourceType configType = OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE);
if (cms.existsResource(sitemapConfigName)) {
CmsResource configFile = cms.readResource(sitemapConfigName);
if (configFile.getTypeId() != configType.getTypeId()) {
throw new CmsException(Messages.get().container(
Messages.ERR_CREATING_SUB_SITEMAP_WRONG_CONFIG_FILE_TYPE_2,
sitemapConfigName,
CmsADEManager.CONFIG_TYPE));
}
} else {
cms.createResource(
sitemapConfigName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE).getTypeId());
}
}
/**
* Deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return CmsClientSitemapEntry always null
*
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry delete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource resource = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(resource);
cms.deleteResource(cms.getSitePath(resource), CmsResource.DELETE_PRESERVE_SIBLINGS);
tryUnlock(resource);
return null;
}
/**
* Generates a client side lock info object representing the current lock state of the given resource.<p>
*
* @param resource the resource
*
* @return the client lock
*
* @throws CmsException if something goes wrong
*/
private CmsClientLock generateClientLock(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsLock lock = cms.getLock(resource);
CmsClientLock clientLock = new CmsClientLock();
clientLock.setLockType(CmsClientLock.LockType.valueOf(lock.getType().getMode()));
CmsUUID ownerId = lock.getUserId();
if (!lock.isUnlocked() && (ownerId != null)) {
clientLock.setLockOwner(cms.readUser(ownerId).getDisplayName(cms, cms.getRequestContext().getLocale()));
clientLock.setOwnedByUser(cms.getRequestContext().getCurrentUser().getId().equals(ownerId));
}
return clientLock;
}
/**
* Generates a list of property object to save to the sitemap entry folder to apply the given change.<p>
*
* @param change the change
* @param entryFolder the entry folder
*
* @return the property objects
*/
private List<CmsProperty> generateInheritProperties(CmsSitemapChange change, CmsResource entryFolder) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getOwnInternalProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property object to save to the sitemap entry resource to apply the given change.<p>
*
* @param change the change
*
* @return the property objects
*/
private List<CmsProperty> generateOwnProperties(CmsSitemapChange change) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getDefaultFileProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property values inherited to the site-map root entry.<p>
*
* @param rootPath the root entry name
*
* @return the list of property values inherited to the site-map root entry
*
* @throws CmsException if something goes wrong reading the properties
*/
private Map<String, CmsClientProperty> generateParentProperties(String rootPath) throws CmsException {
CmsObject cms = getCmsObject();
if (rootPath == null) {
rootPath = cms.getRequestContext().addSiteRoot("/");
}
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
String parentRootPath = CmsResource.getParentFolder(rootPath);
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
if (parentRootPath != null) {
List<CmsProperty> props = rootCms.readPropertyObjects(parentRootPath, true);
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, true);
result.put(clientProp.getName(), clientProp);
}
}
return result;
}
/**
* Returns the sitemap children for the given path with all descendants up to the given level or to the given target path, ie.
* <dl><dt>levels=1 <dd>only children<dt>levels=2<dd>children and great children</dl>
* and so on.<p>
*
* @param root the site relative root
* @param levels the levels to recurse
* @param targetPath the target path
*
* @return the sitemap children
*
* @throws CmsException if something goes wrong
*/
private List<CmsClientSitemapEntry> getChildren(String root, int levels, String targetPath) throws CmsException {
List<CmsClientSitemapEntry> children = new ArrayList<CmsClientSitemapEntry>();
int i = 0;
for (CmsJspNavElement navElement : getNavBuilder().getNavigationForFolder(
root,
Visibility.all,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
CmsClientSitemapEntry child = toClientEntry(navElement, false);
if (child != null) {
child.setPosition(i);
children.add(child);
int nextLevels = levels;
if ((nextLevels == 1) && (targetPath != null) && targetPath.startsWith(child.getSitePath())) {
nextLevels = 2;
}
if (child.isFolderType() && ((nextLevels > 1) || (nextLevels == -1)) && !isSubSitemap(navElement)) {
child.setSubEntries(getChildren(child.getSitePath(), nextLevels - 1, targetPath), null);
child.setChildrenLoadedInitially(true);
}
i++;
}
}
return children;
}
/**
* Returns the clipboard data from the current user.<p>
*
* @return the clipboard data
*/
private CmsSitemapClipboardData getClipboardData() {
CmsSitemapClipboardData result = new CmsSitemapClipboardData();
result.setModifications(getModifiedList());
result.setDeletions(getDeletedList());
return result;
}
/**
* Returns the deleted list from the current user.<p>
*
* @return the deleted list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getDeletedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_DELETED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID delId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(delId, CmsResourceFilter.ALL);
if (res.getState().isDeleted()) {
// make sure resource is still deleted
CmsClientSitemapEntry delEntry = new CmsClientSitemapEntry();
delEntry.setSitePath(cms.getSitePath(res));
delEntry.setOwnProperties(getClientProperties(cms, res, false));
delEntry.setName(res.getName());
delEntry.setVfsPath(cms.getSitePath(res));
delEntry.setResourceTypeName(OpenCms.getResourceManager().getResourceType(res).getTypeName());
delEntry.setEntryType(res.isFolder() ? EntryType.folder : isRedirectType(res.getTypeId())
? EntryType.redirect
: EntryType.leaf);
delEntry.setId(delId);
result.put(delId, delEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Gets the container name for function detail elements depending on the parent folder.<p>
*
* @param parent the parent folder
* @return the name of the function detail container
*/
private String getFunctionDetailContainerName(CmsResource parent) {
try {
CmsObject cms = getCmsObject();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsProperty templateProp = cms.readPropertyObject(parent, CmsPropertyDefinition.PROPERTY_TEMPLATE, true);
String templateVal = templateProp.getValue();
if (templateVal == null) {
return null;
}
CmsResource templateRes;
try {
templateRes = cms.readResource(templateVal, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
} catch (CmsVfsResourceNotFoundException e) {
templateRes = rootCms.readResource(templateVal, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
CmsProperty containerInfoProp = cms.readPropertyObject(
templateRes,
CmsPropertyDefinition.PROPERTY_CONTAINER_INFO,
true);
String containerInfo = containerInfoProp.getValue() == null ? "" : containerInfoProp.getValue();
Map<String, String> attrs = CmsStringUtil.splitAsMap(containerInfo, "|", "="); //$NON-NLS-2$
String functionDetailContainerName = attrs.get(KEY_FUNCTION_DETAIL);
return functionDetailContainerName;
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return null;
}
}
/**
* Returns the modified list from the current user.<p>
*
* @return the modified list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getModifiedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID modId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(modId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String sitePath = cms.getSitePath(res);
CmsJspNavElement navEntry = getNavBuilder().getNavigationForResource(
sitePath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
if (navEntry.isInNavigation()) {
CmsClientSitemapEntry modEntry = toClientEntry(navEntry, false);
result.put(modId, modEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Returns a navigation builder reference.<p>
*
* @return the navigation builder
*/
private CmsJspNavBuilder getNavBuilder() {
if (m_navBuilder == null) {
m_navBuilder = new CmsJspNavBuilder(getCmsObject());
}
return m_navBuilder;
}
/**
* Returns the new resource infos.<p>
*
* @param cms the current CMS context
* @param configData the configuration data from which the new resource infos should be read
* @param locale locale used for retrieving descriptions/titles
*
* @return the new resource infos
*/
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsModelPageConfig modelConfig : configData.getModelPages()) {
try {
result.add(createNewResourceInfo(cms, modelConfig.getResource(), locale));
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
}
Collections.sort(result, new Comparator<CmsNewResourceInfo>() {
public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) {
return ComparisonChain.start().compare(a.getNavPos(), b.getNavPos(), Ordering.natural().nullsLast()).result();
}
});
return result;
}
/**
* Gets the names of all available properties.<p>
*
* @param cms the CMS context
*
* @return the list of all property names
*
* @throws CmsException
*/
private List<String> getPropertyNames(CmsObject cms) throws CmsException {
List<CmsPropertyDefinition> propDefs = cms.readAllPropertyDefinitions();
List<String> result = new ArrayList<String>();
for (CmsPropertyDefinition propDef : propDefs) {
result.add(propDef.getName());
}
return result;
}
/**
* Gets the resource type info beans for types for which new detail pages can be created.<p>
*
* @param cms the current CMS context
* @param resourceTypeConfigs the resource type configurations
* @param functionReferences the function references
* @param modelResource the model resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the resource type info beans for types for which new detail pages can be created
*/
private List<CmsNewResourceInfo> getResourceTypeInfos(
CmsObject cms,
List<CmsResourceTypeConfig> resourceTypeConfigs,
List<CmsFunctionReference> functionReferences,
CmsResource modelResource,
Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsResourceTypeConfig typeConfig : resourceTypeConfigs) {
if (typeConfig.isDetailPagesDisabled()) {
continue;
}
String typeName = typeConfig.getTypeName();
try {
I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(typeName);
result.add(createResourceTypeInfo(resourceType, modelResource));
} catch (CmsLoaderException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
for (CmsFunctionReference functionRef : functionReferences) {
try {
CmsResource functionRes = cms.readResource(functionRef.getStructureId());
String description = cms.readPropertyObject(
functionRes,
CmsPropertyDefinition.PROPERTY_DESCRIPTION,
false).getValue();
String subtitle = description;
try {
CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(
cms,
functionRef.getStructureId(),
getWorkplaceLocale());
subtitle = searchResult.getDescription();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
modelResource.getTypeId(),
CmsDetailPageInfo.FUNCTION_PREFIX + functionRef.getName(),
functionRef.getName(),
description,
modelResource.getStructureId(),
false,
subtitle);
info.setCreateParameter(functionRef.getStructureId().toString());
info.setIsFunction(true);
result.add(info);
} catch (CmsVfsResourceNotFoundException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return result;
}
private CmsClientSitemapEntry getRootEntry(String rootPath, String targetPath)
throws CmsSecurityException, CmsException {
String sitePath = "/";
if (rootPath != null) {
sitePath = getCmsObject().getRequestContext().removeSiteRoot(rootPath);
}
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
sitePath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsClientSitemapEntry result = toClientEntry(navElement, true);
if (result != null) {
result.setPosition(0);
result.setChildrenLoadedInitially(true);
result.setSubEntries(getChildren(sitePath, 2, targetPath), null);
}
return result;
}
/**
* Returns the sitemap info for the given base path.<p>
*
* @param basePath the base path
*
* @return the sitemap info
*
* @throws CmsException if something goes wrong reading the resources
*/
private CmsSitemapInfo getSitemapInfo(String basePath) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource baseFolder = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(basePath)) {
baseFolder = cms.readResource(
cms.getRequestContext().removeSiteRoot(basePath),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
} else {
// in case of an empty base path, use base folder of the current site
basePath = "/";
baseFolder = cms.readResource("/");
}
CmsResource defaultFile = cms.readDefaultFile(baseFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String title = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(title) && (defaultFile != null)) {
title = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
}
String description = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(description) && (defaultFile != null)) {
description = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
}
return new CmsSitemapInfo(
cms.getRequestContext().getCurrentProject().getName(),
description,
OpenCms.getLocaleManager().getDefaultLocale(cms, baseFolder).toString(),
OpenCms.getSiteManager().getCurrentSite(cms).getUrl()
+ OpenCms.getLinkManager().substituteLinkForUnknownTarget(cms, basePath),
title);
}
/**
* Gets the default type id for subsitemap folders.<p>
*
* @return the default type id for subsitemap folders
*
* @throws CmsRpcException in case of an error
*/
private int getSubsitemapType() throws CmsRpcException {
try {
return OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolderSubSitemap.TYPE_SUBSITEMAP).getTypeId();
} catch (CmsLoaderException e) {
error(e);
}
return CmsResourceTypeUnknownFolder.getStaticTypeId();
}
/**
* Returns the workplace locale for the current user.<p>
*
* @return the workplace locale
*/
private Locale getWorkplaceLocale() {
Locale result = OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject());
if (result == null) {
result = CmsLocaleManager.getDefaultLocale();
}
if (result == null) {
result = Locale.getDefault();
}
return result;
}
/**
* Checks whether the sitemap change has default file changes.<p>
*
* @param change a sitemap change
* @return true if the change would change the default file
*/
private boolean hasDefaultFileChanges(CmsSitemapChange change) {
return (change.getDefaultFileId() != null) && !change.isNew();
//TODO: optimize this!
}
/**
* Checks whether the sitemap change has changes for the sitemap entry resource.<p>
*
* @param change the sitemap change
* @return true if the change would change the original sitemap entry resource
*/
private boolean hasOwnChanges(CmsSitemapChange change) {
return !change.isNew();
}
/**
* Checks whether a resource is a default file of a folder.<p>
*
* @param resource the resource to check
*
* @return true if the resource is the default file of a folder
*
* @throws CmsException if something goes wrong
*/
private boolean isDefaultFile(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
if (resource.isFolder()) {
return false;
}
CmsResource parent = cms.readResource(
CmsResource.getParentFolder(cms.getSitePath(resource)),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsResource defaultFile = cms.readDefaultFile(parent, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
return resource.equals(defaultFile);
}
/**
* Checks if the toolbar should be displayed.<p>
*
* @param request the current request to get the default locale from
*
* @return <code>true</code> if the toolbar should be displayed
*/
private boolean isDisplayToolbar(HttpServletRequest request) {
// display the toolbar by default
boolean displayToolbar = true;
if (CmsHistoryResourceHandler.isHistoryRequest(request)) {
// we do not want to display the toolbar in case of an historical request
displayToolbar = false;
}
return displayToolbar;
}
/**
* Returns if the given type id matches the xml-redirect resource type.<p>
*
* @param typeId the resource type id
*
* @return <code>true</code> if the given type id matches the xml-redirect resource type
*/
private boolean isRedirectType(int typeId) {
try {
return typeId == OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT).getTypeId();
} catch (Exception e) {
return false;
}
}
/**
* Returns if the given nav-element resembles a sub-sitemap entry-point.<p>
*
* @param navElement the nav-element
*
* @return <code>true</code> if the given nav-element resembles a sub-sitemap entry-point.<p>
*/
private boolean isSubSitemap(CmsJspNavElement navElement) {
return CmsResourceTypeFolderSubSitemap.isSubSitemap(navElement.getResource());
}
/**
* Checks if the given open path is valid.<p>
*
* @param cms the cms context
* @param openPath the open path
*
* @return <code>true</code> if the given open path is valid
*/
private boolean isValidOpenPath(CmsObject cms, String openPath) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(openPath)) {
return false;
}
if (!cms.existsResource(openPath)) {
// in case of a detail-page check the parent folder
String parent = CmsResource.getParentFolder(openPath);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(parent) || !cms.existsResource(parent)) {
return false;
}
}
return true;
}
/**
* Returns if the given return code is valid.<p>
*
* @param returnCode the return code to check
*
* @return <code>true</code> if the return code is valid
*/
private boolean isValidReturnCode(String returnCode) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(returnCode)) {
return false;
}
int pos = returnCode.indexOf(":");
if (pos > 0) {
return CmsUUID.isValidUUID(returnCode.substring(0, pos))
&& CmsUUID.isValidUUID(returnCode.substring(pos + 1));
} else {
return CmsUUID.isValidUUID(returnCode);
}
}
/**
* Applys the given changes to the entry.<p>
*
* @param change the change to apply
*
* @throws CmsException if something goes wrong
*/
private void modifyEntry(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryPage = null;
CmsResource entryFolder = null;
CmsResource ownRes = null;
CmsResource defaultFileRes = null;
try {
// lock all resources necessary first to avoid doing changes only half way through
if (hasOwnChanges(change)) {
ownRes = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(ownRes);
}
if (hasDefaultFileChanges(change)) {
defaultFileRes = cms.readResource(change.getDefaultFileId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(defaultFileRes);
}
if ((ownRes != null) && ownRes.isFolder()) {
entryFolder = ownRes;
}
if ((ownRes != null) && ownRes.isFile()) {
entryPage = ownRes;
}
if (defaultFileRes != null) {
entryPage = defaultFileRes;
}
if (change.isLeafType()) {
entryFolder = entryPage;
}
updateProperties(cms, ownRes, defaultFileRes, change.getPropertyChanges());
if (change.hasChangedPosition()) {
updateNavPos(ownRes, change);
}
if (entryFolder != null) {
if (change.hasNewParent() || change.hasChangedName()) {
String destinationPath;
if (change.hasNewParent()) {
CmsResource futureParent = cms.readResource(
change.getParentId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
destinationPath = CmsStringUtil.joinPaths(cms.getSitePath(futureParent), change.getName());
} else {
destinationPath = CmsStringUtil.joinPaths(
CmsResource.getParentFolder(cms.getSitePath(entryFolder)),
change.getName());
}
if (change.isLeafType() && destinationPath.endsWith("/")) {
destinationPath = destinationPath.substring(0, destinationPath.length() - 1);
}
// only if the site-path has really changed
if (!cms.getSitePath(entryFolder).equals(destinationPath)) {
cms.moveResource(cms.getSitePath(entryFolder), destinationPath);
}
entryFolder = cms.readResource(
entryFolder.getStructureId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
}
} finally {
if (entryPage != null) {
tryUnlock(entryPage);
}
if (entryFolder != null) {
tryUnlock(entryFolder);
}
}
}
/**
* Helper method for removing all locales except one from a container page.<p>
*
* @param page the container page to proces
* @param localeToKeep the locale which should be kept
*
* @throws CmsXmlException if something goes wrong
*/
private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException {
List<Locale> locales = page.getLocales();
for (Locale locale : locales) {
if (!locale.equals(localeToKeep)) {
page.removeLocale(locale);
}
}
}
/**
* Applys the given remove change.<p>
*
* @param change the change to apply
*
* @return the changed client sitemap entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange removeEntryFromNavigation(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryFolder = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(entryFolder);
List<CmsProperty> properties = new ArrayList<CmsProperty>();
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVTEXT,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
cms.writePropertyObjects(cms.getSitePath(entryFolder), properties);
tryUnlock(entryFolder);
return change;
}
/**
* Saves the detail page information of a sitemap to the sitemap's configuration file.<p>
*
* @param detailPages saves the detailpage configuration
* @param resource the configuration file resource
* @param newId the structure id to use for new detail page entries
* @param updateEntry the new detail page entry
*
* @throws CmsException if something goes wrong
*/
private void saveDetailPages(
List<CmsDetailPageInfo> detailPages,
CmsResource resource,
CmsUUID newId,
CmsClientSitemapEntry updateEntry) throws CmsException {
CmsObject cms = getCmsObject();
if (updateEntry != null) {
for (CmsDetailPageInfo info : detailPages) {
if (info.getId() == null) {
updateEntry.setDetailpageTypeName(info.getType());
break;
}
}
}
CmsDetailPageConfigurationWriter writer = new CmsDetailPageConfigurationWriter(cms, resource);
writer.updateAndSave(detailPages, newId);
}
/**
* Saves the given clipboard data to the session.<p>
*
* @param clipboardData the clipboard data to save
*
* @throws CmsException if something goes wrong writing the user
*/
private void setClipboardData(CmsSitemapClipboardData clipboardData) throws CmsException {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
if (clipboardData != null) {
JSONArray modified = new JSONArray();
if (clipboardData.getModifications() != null) {
for (CmsUUID id : clipboardData.getModifications().keySet()) {
if (id != null) {
modified.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST, modified.toString());
JSONArray deleted = new JSONArray();
if (clipboardData.getDeletions() != null) {
for (CmsUUID id : clipboardData.getDeletions().keySet()) {
if (id != null) {
deleted.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_DELETED_LIST, deleted.toString());
cms.writeUser(user);
}
}
/**
* Determines if the title property of the default file should be changed.<p>
*
* @param properties the current default file properties
* @param folderNavtext the 'NavText' property of the folder
*
* @return <code>true</code> if the title property should be changed
*/
private boolean shouldChangeDefaultFileTitle(Map<String, CmsProperty> properties, CmsProperty folderNavtext) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((folderNavtext != null) && properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
folderNavtext.getValue()));
}
/**
* Determines if the title property should be changed in case of a 'NavText' change.<p>
*
* @param properties the current resource properties
*
* @return <code>true</code> if the title property should be changed in case of a 'NavText' change
*/
private boolean shouldChangeTitle(Map<String, CmsProperty> properties) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT) != null) && properties.get(
CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT).getValue()));
}
/**
* Converts a jsp navigation element into a client sitemap entry.<p>
*
* @param navElement the jsp navigation element
* @param isRoot true if the entry is a root entry
*
* @return the client sitemap entry
* @throws CmsException
*/
private CmsClientSitemapEntry toClientEntry(CmsJspNavElement navElement, boolean isRoot) throws CmsException {
CmsResource entryPage = null;
CmsObject cms = getCmsObject();
CmsClientSitemapEntry clientEntry = new CmsClientSitemapEntry();
CmsResource entryFolder = null;
CmsResource ownResource = navElement.getResource();
clientEntry.setResourceState(ownResource.getState());
CmsResource defaultFileResource = null;
if (ownResource.isFolder() && !navElement.isNavigationLevel()) {
defaultFileResource = cms.readDefaultFile(ownResource, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
Map<String, CmsClientProperty> ownProps = getClientProperties(cms, ownResource, false);
Map<String, CmsClientProperty> defaultFileProps = null;
if (defaultFileResource != null) {
defaultFileProps = getClientProperties(cms, defaultFileResource, false);
clientEntry.setDefaultFileId(defaultFileResource.getStructureId());
clientEntry.setDefaultFileType(OpenCms.getResourceManager().getResourceType(defaultFileResource.getTypeId()).getTypeName());
} else {
defaultFileProps = new HashMap<String, CmsClientProperty>();
}
boolean isDefault = isDefaultFile(ownResource);
clientEntry.setId(ownResource.getStructureId());
clientEntry.setFolderDefaultPage(isDefault);
if (navElement.getResource().isFolder()) {
entryFolder = navElement.getResource();
entryPage = defaultFileResource;
clientEntry.setName(entryFolder.getName());
if (entryPage == null) {
entryPage = entryFolder;
}
if (!isRoot && isSubSitemap(navElement)) {
clientEntry.setEntryType(EntryType.subSitemap);
clientEntry.setDefaultFileType(null);
} else if (navElement.isNavigationLevel()) {
clientEntry.setEntryType(EntryType.navigationLevel);
}
CmsLock folderLock = cms.getLock(entryFolder);
clientEntry.setHasForeignFolderLock(!folderLock.isUnlocked()
&& !folderLock.isOwnedBy(cms.getRequestContext().getCurrentUser()));
if (!cms.getRequestContext().getCurrentProject().isOnlineProject()) {
List<CmsResource> blockingChildren = cms.getBlockingLockedResources(entryFolder);
clientEntry.setBlockingLockedChildren((blockingChildren != null) && !blockingChildren.isEmpty());
}
} else {
entryPage = navElement.getResource();
clientEntry.setName(entryPage.getName());
if (isRedirectType(entryPage.getTypeId())) {
clientEntry.setEntryType(EntryType.redirect);
CmsFile file = getCmsObject().readFile(entryPage);
I_CmsXmlDocument content = CmsXmlContentFactory.unmarshal(getCmsObject(), file);
I_CmsXmlContentValue linkValue = content.getValue(
REDIRECT_LINK_TARGET_XPATH,
getCmsObject().getRequestContext().getLocale());
String link = linkValue != null ? linkValue.getStringValue(getCmsObject()) : Messages.get().getBundle(
getWorkplaceLocale()).key(Messages.GUI_REDIRECT_SUB_LEVEL_0);
clientEntry.setRedirectTarget(link);
} else {
clientEntry.setEntryType(EntryType.leaf);
}
}
if (entryPage.isFile()) {
List<CmsAlias> aliases = OpenCms.getAliasManager().getAliasesForStructureId(
getCmsObject(),
entryPage.getStructureId());
if (!aliases.isEmpty()) {
List<String> aliasList = new ArrayList<String>();
for (CmsAlias alias : aliases) {
String aliasPath = alias.getAliasPath();
aliasList.add(aliasPath);
}
clientEntry.setAliases(aliasList);
}
}
long dateExpired = navElement.getResource().getDateExpired();
if (dateExpired != CmsResource.DATE_EXPIRED_DEFAULT) {
clientEntry.setDateExpired(CmsDateUtil.getDate(
new Date(dateExpired),
DateFormat.SHORT,
getWorkplaceLocale()));
}
long dateReleased = navElement.getResource().getDateReleased();
if (dateReleased != CmsResource.DATE_RELEASED_DEFAULT) {
clientEntry.setDateReleased(CmsDateUtil.getDate(
new Date(dateReleased),
DateFormat.SHORT,
getWorkplaceLocale()));
}
clientEntry.setResleasedAndNotExpired(navElement.getResource().isReleasedAndNotExpired(
System.currentTimeMillis()));
String path = cms.getSitePath(entryPage);
clientEntry.setVfsPath(path);
clientEntry.setOwnProperties(ownProps);
clientEntry.setDefaultFileProperties(defaultFileProps);
clientEntry.setSitePath(entryFolder != null ? cms.getSitePath(entryFolder) : path);
//CHECK: assuming that, if entryPage refers to the default file, the lock state of the folder
clientEntry.setLock(generateClientLock(entryPage));
clientEntry.setInNavigation(isRoot || navElement.isInNavigation());
String type = OpenCms.getResourceManager().getResourceType(ownResource).getTypeName();
clientEntry.setResourceTypeName(type);
return clientEntry;
}
/**
* Un-deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return the changed entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange undelete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource deleted = cms.readResource(change.getEntryId(), CmsResourceFilter.ALL);
if (deleted.getState().isDeleted()) {
ensureLock(deleted);
cms.undeleteResource(getCmsObject().getSitePath(deleted), true);
tryUnlock(deleted);
}
String parentPath = CmsResource.getParentFolder(cms.getSitePath(deleted));
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
parentPath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsClientSitemapEntry entry = toClientEntry(navElement, navElement.isInNavigation());
entry.setSubEntries(getChildren(parentPath, 2, null), null);
change.setUpdatedEntry(entry);
return change;
}
/**
* Updates the navigation position for a resource.<p>
*
* @param res the resource for which to update the navigation position
* @param change the sitemap change
*
* @throws CmsException if something goes wrong
*/
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException {
if (change.hasChangedPosition()) {
applyNavigationChanges(change, res);
}
}
/**
* Updates properties for a resource and possibly its detail page.<p>
*
* @param cms the CMS context
* @param ownRes the resource
* @param defaultFileRes the default file resource (possibly null)
* @param propertyModifications the property modifications
*
* @throws CmsException if something goes wrong
*/
private void updateProperties(
CmsObject cms,
CmsResource ownRes,
CmsResource defaultFileRes,
List<CmsPropertyModification> propertyModifications) throws CmsException {
Map<String, CmsProperty> ownProps = getPropertiesByName(cms.readPropertyObjects(ownRes, false));
// determine if the title property should be changed in case of a 'NavText' change
boolean changeOwnTitle = shouldChangeTitle(ownProps);
boolean changeDefaultFileTitle = false;
Map<String, CmsProperty> defaultFileProps = Collections.emptyMap();
if (defaultFileRes != null) {
defaultFileProps = getPropertiesByName(cms.readPropertyObjects(defaultFileRes, false));
// determine if the title property of the default file should be changed
changeDefaultFileTitle = shouldChangeDefaultFileTitle(
defaultFileProps,
ownProps.get(CmsPropertyDefinition.PROPERTY_NAVTEXT));
}
String hasNavTextChange = null;
List<CmsProperty> ownPropertyChanges = new ArrayList<CmsProperty>();
List<CmsProperty> defaultFilePropertyChanges = new ArrayList<CmsProperty>();
for (CmsPropertyModification propMod : propertyModifications) {
CmsProperty propToModify = null;
if (ownRes.getStructureId().equals(propMod.getId())) {
if (CmsPropertyDefinition.PROPERTY_NAVTEXT.equals(propMod.getName())) {
hasNavTextChange = propMod.getValue();
} else if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeOwnTitle = false;
}
propToModify = ownProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
ownPropertyChanges.add(propToModify);
} else {
if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeDefaultFileTitle = false;
}
propToModify = defaultFileProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
defaultFilePropertyChanges.add(propToModify);
}
String newValue = propMod.getValue();
if (newValue == null) {
newValue = "";
}
if (propMod.isStructureValue()) {
propToModify.setStructureValue(newValue);
} else {
propToModify.setResourceValue(newValue);
}
}
if (hasNavTextChange != null) {
if (changeOwnTitle) {
CmsProperty titleProp = ownProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
ownPropertyChanges.add(titleProp);
}
if (changeDefaultFileTitle) {
CmsProperty titleProp = defaultFileProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
defaultFilePropertyChanges.add(titleProp);
}
}
if (!ownPropertyChanges.isEmpty()) {
cms.writePropertyObjects(ownRes, ownPropertyChanges);
}
if (!defaultFilePropertyChanges.isEmpty() && (defaultFileRes != null)) {
cms.writePropertyObjects(defaultFileRes, defaultFilePropertyChanges);
}
}
}
|
package com.worth.ifs.application;
import com.worth.ifs.application.resource.ApplicationResource;
import com.worth.ifs.registration.AcceptInviteController;
import com.worth.ifs.registration.OrganisationCreationController;
import com.worth.ifs.registration.RegistrationController;
import com.worth.ifs.util.CookieUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This controller will handle all requests that are related to the create of a application.
* This is used when the users want create a new application and that also includes the creation of the organisation.
* These URLs are publicly available, since there user might not have a account yet.
* <p>
* The user input is stored in cookies, so we can use the data after a page refresh / redirect.
* For user-account creation, have a look at {@link RegistrationController}
*/
@Controller
@RequestMapping("/application/create")
public class ApplicationCreationController extends AbstractApplicationController {
public static final String COMPETITION_ID = "competitionId";
public static final String USER_ID = "userId";
private static final String APPLICATION_ID = "applicationId";
private static final Log log = LogFactory.getLog(ApplicationCreationController.class);
Validator validator;
@Autowired
public void setValidator(Validator validator) {
this.validator = validator;
}
@RequestMapping("/check-eligibility/{competitionId}")
public String checkEligibility(Model model,
@PathVariable(COMPETITION_ID) Long competitionId,
HttpServletResponse response) {
model.addAttribute(COMPETITION_ID, competitionId);
CookieUtil.saveToCookie(response, COMPETITION_ID, String.valueOf(competitionId));
CookieUtil.removeCookie(response, AcceptInviteController.INVITE_HASH);
CookieUtil.removeCookie(response, OrganisationCreationController.ORGANISATION_ID);
return "create-application/check-eligibility";
}
@RequestMapping("/your-details")
public String checkEligibility() {
return "create-application/your-details";
}
@RequestMapping("/initialize-application")
public String initializeApplication(HttpServletRequest request,
HttpServletResponse response) {
log.info("get competition id");
Long competitionId = Long.valueOf(CookieUtil.getCookieValue(request, COMPETITION_ID));
log.info("get user id");
Long userId = Long.valueOf(CookieUtil.getCookieValue(request, USER_ID));
ApplicationResource application = applicationService.createApplication(competitionId, userId, "");
if (application == null || application.getId() == null) {
log.error("Application not created with competitionID: " + competitionId);
log.error("Application not created with userId: " + userId);
} else {
CookieUtil.saveToCookie(response, APPLICATION_ID, String.valueOf(application.getId()));
// TODO INFUND-936 temporary measure to redirect to login screen until email verification is in place below
if (userAuthenticationService.getAuthentication(request) == null) {
return "redirect:/";
}
// TODO INFUND-936 temporary measure to redirect to login screen until email verification is in place above
return String.format("redirect:/application/%s/contributors/invite?newApplication", String.valueOf(application.getId()));
}
return null;
}
}
|
package org.opencms.ade.sitemap;
import org.opencms.ade.configuration.CmsADEConfigData;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.configuration.CmsFunctionReference;
import org.opencms.ade.configuration.CmsModelPageConfig;
import org.opencms.ade.configuration.CmsResourceTypeConfig;
import org.opencms.ade.detailpage.CmsDetailPageConfigurationWriter;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry.EntryType;
import org.opencms.ade.sitemap.shared.CmsDetailPageTable;
import org.opencms.ade.sitemap.shared.CmsNewResourceInfo;
import org.opencms.ade.sitemap.shared.CmsSitemapChange;
import org.opencms.ade.sitemap.shared.CmsSitemapChange.ChangeType;
import org.opencms.ade.sitemap.shared.CmsSitemapClipboardData;
import org.opencms.ade.sitemap.shared.CmsSitemapData;
import org.opencms.ade.sitemap.shared.CmsSitemapInfo;
import org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeFolderExtended;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.gwt.CmsTemplateFinder;
import org.opencms.gwt.shared.CmsBrokenLinkBean;
import org.opencms.gwt.shared.CmsClientLock;
import org.opencms.gwt.shared.CmsCoreData;
import org.opencms.gwt.shared.property.CmsClientProperty;
import org.opencms.gwt.shared.property.CmsPropertyModification;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.json.JSONArray;
import org.opencms.jsp.CmsJspNavBuilder;
import org.opencms.jsp.CmsJspNavElement;
import org.opencms.loader.CmsLoaderException;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsSecurityException;
import org.opencms.site.CmsSite;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplaceMessages;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.CmsXmlDynamicFunctionHandler;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentProperty;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
/**
* Handles all RPC services related to the vfs sitemap.<p>
*
* @since 8.0.0
*
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapServiceAsync
*/
public class CmsVfsSitemapService extends CmsGwtService implements I_CmsSitemapService {
/** Helper class for representing information about a lock. */
protected class LockInfo {
/** The lock state. */
private CmsLock m_lock;
/** True if the lock was just locked. */
private boolean m_wasJustLocked;
/**
* Creates a new LockInfo object.<p>
*
* @param lock the lock state
* @param wasJustLocked true if the lock was just locked
*/
public LockInfo(CmsLock lock, boolean wasJustLocked) {
m_lock = lock;
m_wasJustLocked = wasJustLocked;
}
/**
* Returns the lock state.<p>
*
* @return the lock state
*/
public CmsLock getLock() {
return m_lock;
}
/**
* Returns true if the lock was just locked.<p>
*
* @return true if the lock was just locked
*/
public boolean wasJustLocked() {
return m_wasJustLocked;
}
}
/** The configuration key for the functionDetail attribute in the container.info property. */
public static final String KEY_FUNCTION_DETAIL = "functionDetail";
/** The additional user info key for deleted list. */
private static final String ADDINFO_ADE_DELETED_LIST = "ADE_DELETED_LIST";
/** The additional user info key for modified list. */
private static final String ADDINFO_ADE_MODIFIED_LIST = "ADE_MODIFIED_LIST";
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsVfsSitemapService.class);
/** The redirect recource type name. */
private static final String RECOURCE_TYPE_NAME_REDIRECT = "htmlredirect";
/** The redirect target XPath. */
private static final String REDIRECT_LINK_TARGET_XPATH = "Link";
/** Serialization uid. */
private static final long serialVersionUID = -7236544324371767330L;
/** The navigation builder. */
private CmsJspNavBuilder m_navBuilder;
/**
* Returns a new configured service instance.<p>
*
* @param request the current request
*
* @return a new service instance
*/
public static CmsVfsSitemapService newInstance(HttpServletRequest request) {
CmsVfsSitemapService service = new CmsVfsSitemapService();
service.setCms(CmsFlexController.getCmsObject(request));
service.setRequest(request);
return service;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createSubSitemap(org.opencms.util.CmsUUID)
*/
public CmsSitemapChange createSubSitemap(CmsUUID entryId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(entryId);
ensureLock(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
String folderName = CmsStringUtil.joinPaths(sitePath, CmsADEManager.CONFIG_FOLDER_NAME + "/");
String sitemapConfigName = CmsStringUtil.joinPaths(folderName, CmsADEManager.CONFIG_FILE_NAME);
if (!cms.existsResource(folderName)) {
cms.createResource(
folderName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_FOLDER_TYPE).getTypeId());
}
I_CmsResourceType configType = OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE);
if (cms.existsResource(sitemapConfigName)) {
CmsResource configFile = cms.readResource(sitemapConfigName);
if (configFile.getTypeId() != configType.getTypeId()) {
throw new CmsException(Messages.get().container(
Messages.ERR_CREATING_SUB_SITEMAP_WRONG_CONFIG_FILE_TYPE_2,
sitemapConfigName,
CmsADEManager.CONFIG_TYPE));
}
} else {
cms.createResource(
sitemapConfigName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE).getTypeId());
}
subSitemapFolder.setType(getEntryPointType());
cms.writeResource(subSitemapFolder);
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getChildren(java.lang.String, org.opencms.util.CmsUUID, int)
*/
public CmsClientSitemapEntry getChildren(String entryPointUri, CmsUUID entryId, int levels) throws CmsRpcException {
CmsClientSitemapEntry entry = null;
try {
CmsObject cms = getCmsObject();
//ensure that root ends with a '/' if it's a folder
CmsResource rootRes = cms.readResource(entryId, CmsResourceFilter.ONLY_VISIBLE);
String root = cms.getSitePath(rootRes);
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(root, CmsResourceFilter.ONLY_VISIBLE);
boolean isRoot = root.equals(entryPointUri);
entry = toClientEntry(navElement, isRoot);
if ((levels > 0) && (isRoot || (rootRes.isFolder() && (!isSubSitemap(navElement))))) {
entry.setSubEntries(getChildren(root, levels, null), null);
}
} catch (Throwable e) {
error(e);
}
return entry;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#mergeSubSitemap(java.lang.String, org.opencms.util.CmsUUID)
*/
public CmsSitemapChange mergeSubSitemap(String entryPoint, CmsUUID subSitemapId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(subSitemapId, CmsResourceFilter.ONLY_VISIBLE);
ensureLock(subSitemapFolder);
subSitemapFolder.setType(OpenCms.getResourceManager().getResourceType(
CmsResourceTypeFolder.RESOURCE_TYPE_NAME).getTypeId());
cms.writeResource(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
String sitemapConfigName = CmsStringUtil.joinPaths(
sitePath,
CmsADEManager.CONFIG_FOLDER_NAME,
CmsADEManager.CONFIG_FILE_NAME);
if (cms.existsResource(sitemapConfigName)) {
cms.deleteResource(sitemapConfigName, CmsResource.DELETE_PRESERVE_SIBLINGS);
}
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(
cms.getSitePath(subSitemapFolder),
CmsResourceFilter.ONLY_VISIBLE),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
entry = getChildren(entryPoint, subSitemapId, 1);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#prefetch(java.lang.String)
*/
public CmsSitemapData prefetch(String sitemapUri) throws CmsRpcException {
CmsSitemapData result = null;
CmsObject cms = getCmsObject();
try {
String openPath = getRequest().getParameter(CmsCoreData.PARAM_PATH);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(openPath)) {
// if no path is supplied, start from root
openPath = "/";
}
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(openPath));
Map<String, CmsXmlContentProperty> propertyConfig = new LinkedHashMap<String, CmsXmlContentProperty>(
configData.getPropertyConfigurationAsMap());
Map<String, CmsClientProperty> parentProperties = generateParentProperties(configData.getBasePath());
String siteRoot = cms.getRequestContext().getSiteRoot();
String exportRfsPrefix = OpenCms.getStaticExportManager().getDefaultRfsPrefix();
CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
boolean isSecure = site.hasSecureServer();
String parentSitemap = null;
if (configData.getBasePath() != null) {
CmsADEConfigData parentConfigData = OpenCms.getADEManager().lookupConfiguration(
cms,
CmsResource.getParentFolder(configData.getBasePath()));
parentSitemap = parentConfigData.getBasePath();
if (parentSitemap != null) {
parentSitemap = cms.getRequestContext().removeSiteRoot(parentSitemap);
}
}
String noEdit = "";
CmsNewResourceInfo defaultNewInfo = null;
List<CmsNewResourceInfo> newResourceInfos = null;
CmsDetailPageTable detailPages = null;
List<CmsNewResourceInfo> resourceTypeInfos = null;
boolean canEditDetailPages = false;
boolean isOnlineProject = CmsProject.isOnlineProject(cms.getRequestContext().getCurrentProject().getUuid());
Locale locale = CmsLocaleManager.getDefaultLocale();
try {
String basePath = configData.getBasePath();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsResource baseDir = rootCms.readResource(basePath, CmsResourceFilter.ONLY_VISIBLE);
OpenCms.getLocaleManager();
locale = CmsLocaleManager.getMainLocale(cms, baseDir);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
detailPages = new CmsDetailPageTable(configData.getAllDetailPages());
if (!isOnlineProject) {
newResourceInfos = getNewResourceInfos(cms, configData, locale);
CmsResource modelResource = null;
if (configData.getDefaultModelPage() != null) {
if (cms.existsResource(configData.getDefaultModelPage().getResource().getStructureId())) {
modelResource = configData.getDefaultModelPage().getResource();
} else {
try {
modelResource = cms.readResource(
cms.getSitePath(configData.getDefaultModelPage().getResource()),
CmsResourceFilter.ONLY_VISIBLE);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
if ((modelResource == null) && !newResourceInfos.isEmpty()) {
try {
modelResource = cms.readResource(newResourceInfos.get(0).getCopyResourceId());
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
if (modelResource != null) {
resourceTypeInfos = getResourceTypeInfos(
getCmsObject(),
configData.getResourceTypes(),
configData.getFunctionReferences(),
modelResource,
locale);
try {
defaultNewInfo = createNewResourceInfo(cms, modelResource, locale);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
canEditDetailPages = !(configData.isModuleConfiguration());
}
if (isOnlineProject) {
noEdit = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_SITEMAP_NO_EDIT_ONLINE_0);
}
List<String> allPropNames = getPropertyNames(cms);
String returnCode = getRequest().getParameter(CmsCoreData.PARAM_RETURNCODE);
cms.getRequestContext().getSiteRoot();
result = new CmsSitemapData(
(new CmsTemplateFinder(cms)).getTemplates(),
propertyConfig,
getClipboardData(),
parentProperties,
allPropNames,
exportRfsPrefix,
isSecure,
noEdit,
isDisplayToolbar(getRequest()),
defaultNewInfo,
newResourceInfos,
createResourceTypeInfo(OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT), null),
getSitemapInfo(configData.getBasePath()),
parentSitemap,
getRootEntry(configData.getBasePath(), openPath),
openPath,
30,
detailPages,
resourceTypeInfos,
returnCode,
canEditDetailPages);
} catch (Throwable e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#save(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange save(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
CmsSitemapChange result = null;
try {
result = saveInternal(entryPoint, change);
} catch (Exception e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#saveSync(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange saveSync(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
return save(entryPoint, change);
}
/**
* Creates a "broken link" bean based on a resource.<p>
*
* @param resource the resource
*
* @return the "broken link" bean with the data from the resource
*
* @throws CmsException if something goes wrong
*/
protected CmsBrokenLinkBean createSitemapBrokenLinkBean(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsProperty titleProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, true);
String defaultTitle = "";
String title = titleProp.getValue(defaultTitle);
String path = cms.getSitePath(resource);
String subtitle = path;
return new CmsBrokenLinkBean(title, subtitle);
}
/**
* Locks the given resource with a temporary, if not already locked by the current user.
* Will throw an exception if the resource could not be locked for the current user.<p>
*
* @param resource the resource to lock
*
* @return the assigned lock
*
* @throws CmsException if the resource could not be locked
*/
protected LockInfo ensureLockAndGetInfo(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
boolean justLocked = false;
List<CmsResource> blockingResources = cms.getBlockingLockedResources(resource);
if ((blockingResources != null) && !blockingResources.isEmpty()) {
throw new CmsException(org.opencms.gwt.Messages.get().container(
org.opencms.gwt.Messages.ERR_RESOURCE_HAS_BLOCKING_LOCKED_CHILDREN_1,
cms.getSitePath(resource)));
}
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsLock lock = cms.getLock(resource);
if (!lock.isOwnedBy(user)) {
cms.lockResourceTemporary(resource);
lock = cms.getLock(resource);
justLocked = true;
} else if (!lock.isOwnedInProjectBy(user, cms.getRequestContext().getCurrentProject())) {
cms.changeLock(resource);
lock = cms.getLock(resource);
justLocked = true;
}
return new LockInfo(lock, justLocked);
}
/**
* Internal method for saving a sitemap.<p>
*
* @param entryPoint the URI of the sitemap to save
* @param change the change to save
*
* @return list of changed sitemap entries
*
* @throws CmsException
*/
protected CmsSitemapChange saveInternal(String entryPoint, CmsSitemapChange change) throws CmsException {
ensureSession();
switch (change.getChangeType()) {
case clipboardOnly:
// do nothing
break;
case remove:
change = removeEntryFromNavigation(change);
break;
case undelete:
change = undelete(change);
break;
default:
change = applyChange(entryPoint, change);
}
setClipboardData(change.getClipBoardData());
return change;
}
/**
* Converts a sequence of properties to a map of client-side property beans.<p>
*
* @param props the sequence of properties
* @param preserveOrigin if true, the origin of the properties should be copied to the client properties
*
* @return the map of client properties
*
*/
Map<String, CmsClientProperty> createClientProperties(Iterable<CmsProperty> props, boolean preserveOrigin) {
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, preserveOrigin);
result.put(prop.getName(), clientProp);
}
return result;
}
/**
* Removes unnecessary locales from a container page.<p>
*
* @param containerPage the container page which should be changed
* @param localeRes the resource used to determine the locale
*
* @throws CmsException if something goes wrong
*/
void ensureSingleLocale(CmsXmlContainerPage containerPage, CmsResource localeRes) throws CmsException {
CmsObject cms = getCmsObject();
Locale mainLocale = CmsLocaleManager.getMainLocale(cms, localeRes);
OpenCms.getLocaleManager();
Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
if (containerPage.hasLocale(mainLocale)) {
removeAllLocalesExcept(containerPage, mainLocale);
// remove other locales
} else if (containerPage.hasLocale(defaultLocale)) {
containerPage.copyLocale(defaultLocale, mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else if (containerPage.getLocales().size() > 0) {
containerPage.copyLocale(containerPage.getLocales().get(0), mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else {
containerPage.addLocale(cms, mainLocale);
}
}
/**
* Gets the properties of a resource as a map of client properties.<p>
*
* @param cms the CMS context to use
* @param res the resource whose properties to read
* @param search true if the inherited properties should be read
*
* @return the client properties as a map
*
* @throws CmsException if something goes wrong
*/
Map<String, CmsClientProperty> getClientProperties(CmsObject cms, CmsResource res, boolean search)
throws CmsException {
List<CmsProperty> props = cms.readPropertyObjects(res, search);
Map<String, CmsClientProperty> result = createClientProperties(props, false);
return result;
}
/**
* Adds a function detail element to a container page.<p>
*
* @param cms the current CMS context
* @param page the container page which should be changed
* @param containerName the name of the container which should be used for function detail elements
* @param elementId the structure id of the element to add
* @param formatterId the structure id of the formatter for the element
*
* @throws CmsException if something goes wrong
*/
private void addFunctionDetailElement(
CmsObject cms,
CmsXmlContainerPage page,
String containerName,
CmsUUID elementId,
CmsUUID formatterId) throws CmsException {
List<Locale> pageLocales = page.getLocales();
for (Locale locale : pageLocales) {
CmsContainerPageBean bean = page.getContainerPage(cms, locale);
List<CmsContainerBean> containerBeans = new ArrayList<CmsContainerBean>();
Collection<CmsContainerBean> originalContainers = bean.getContainers().values();
if ((containerName == null) && !originalContainers.isEmpty()) {
CmsContainerBean firstContainer = originalContainers.iterator().next();
containerName = firstContainer.getName();
}
boolean foundContainer = false;
for (CmsContainerBean cntBean : originalContainers) {
boolean isDetailTarget = cntBean.getName().equals(containerName);
if (isDetailTarget && !foundContainer) {
foundContainer = true;
List<CmsContainerElementBean> newElems = new ArrayList<CmsContainerElementBean>();
newElems.addAll(cntBean.getElements());
CmsContainerElementBean newElement = new CmsContainerElementBean(
elementId,
formatterId,
new HashMap<String, String>(),
false);
newElems.add(0, newElement);
CmsContainerBean newCntBean = new CmsContainerBean(cntBean.getName(), cntBean.getType(), newElems);
containerBeans.add(newCntBean);
} else {
containerBeans.add(cntBean);
}
}
if (!foundContainer) {
throw new CmsException(Messages.get().container(
Messages.ERR_NO_FUNCTION_DETAIL_CONTAINER_1,
page.getFile().getRootPath()));
}
CmsContainerPageBean bean2 = new CmsContainerPageBean(locale, new ArrayList<CmsContainerBean>(
containerBeans));
page.writeContainerPage(cms, locale, bean2);
}
}
/**
* Applys the given change to the VFS.<p>
*
* @param entryPoint the sitemap entry-point
* @param change the change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange applyChange(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource configFile = null;
// lock the config file first, to avoid half done changes
if (change.hasDetailPageInfos()) {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(entryPoint));
if (!configData.isModuleConfiguration() && (configData.getResource() != null)) {
configFile = configData.getResource();
}
if (configFile != null) {
ensureLock(configFile);
}
}
if (change.isNew()) {
CmsClientSitemapEntry newEntry = createNewEntry(entryPoint, change);
change.setUpdatedEntry(newEntry);
change.setEntryId(newEntry.getId());
} else if (change.getChangeType() == ChangeType.delete) {
delete(change);
} else if (change.getEntryId() != null) {
modifyEntry(change);
}
if (change.hasDetailPageInfos() && (configFile != null)) {
saveDetailPages(change.getDetailPageInfos(), configFile, change.getEntryId());
tryUnlock(configFile);
}
return change;
}
/**
* Changes the navigation for a moved entry and its neighbors.<p>
*
* @param change the sitemap change
* @param entryFolder the moved entry
*
* @throws CmsException if something goes wrong
*/
private void applyNavigationChanges(CmsSitemapChange change, CmsResource entryFolder) throws CmsException {
CmsObject cms = getCmsObject();
String parentPath = null;
if (change.hasNewParent()) {
CmsResource parent = cms.readResource(change.getParentId());
parentPath = cms.getSitePath(parent);
} else {
parentPath = CmsResource.getParentFolder(cms.getSitePath(entryFolder));
}
List<CmsJspNavElement> navElements = getNavBuilder().getNavigationForFolder(
parentPath,
true,
CmsResourceFilter.ONLY_VISIBLE);
CmsSitemapNavPosCalculator npc = new CmsSitemapNavPosCalculator(navElements, entryFolder, change.getPosition());
List<CmsJspNavElement> navs = npc.getNavigationChanges();
List<CmsResource> needToUnlock = new ArrayList<CmsResource>();
try {
for (CmsJspNavElement nav : navs) {
LockInfo lockInfo = ensureLockAndGetInfo(nav.getResource());
if (!nav.getResource().equals(entryFolder) && lockInfo.wasJustLocked()) {
needToUnlock.add(nav.getResource());
}
}
for (CmsJspNavElement nav : navs) {
CmsProperty property = new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
"" + nav.getNavPosition(),
null);
cms.writePropertyObject(cms.getSitePath(nav.getResource()), property);
}
} finally {
for (CmsResource lockedRes : needToUnlock) {
try {
cms.unlockResource(lockedRes);
} catch (CmsException e) {
// we catch this because we still want to unlock the other resources
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
/**
* Creates a client property bean from a server-side property.<p>
*
* @param prop the property from which to create the client property
* @param preserveOrigin if true, the origin will be copied into the new object
*
* @return the new client property
*/
private CmsClientProperty createClientProperty(CmsProperty prop, boolean preserveOrigin) {
CmsClientProperty result = new CmsClientProperty(
prop.getName(),
prop.getStructureValue(),
prop.getResourceValue());
if (preserveOrigin) {
result.setOrigin(prop.getOrigin());
}
return result;
}
/**
* Creates a new page in navigation.<p>
*
* @param entryPoint the site-map entry-point
* @param change the new change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry createNewEntry(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsClientSitemapEntry newEntry = null;
if (change.getParentId() != null) {
CmsResource parentFolder = cms.readResource(change.getParentId(), CmsResourceFilter.ONLY_VISIBLE);
String entryPath = "";
CmsResource entryFolder = null;
CmsResource newRes = null;
byte[] content = null;
List<CmsProperty> properties = Collections.emptyList();
CmsResource copyPage = null;
if (change.getNewCopyResourceId() != null) {
copyPage = cms.readResource(change.getNewCopyResourceId(), CmsResourceFilter.ONLY_VISIBLE);
content = cms.readFile(copyPage).getContents();
properties = cms.readPropertyObjects(copyPage, false);
}
if (isRedirectType(change.getNewResourceTypeId())) {
entryPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName());
newRes = cms.createResource(
entryPath,
change.getNewResourceTypeId(),
null,
Collections.singletonList(new CmsProperty(
CmsPropertyDefinition.PROPERTY_TITLE,
change.getName(),
null)));
cms.writePropertyObjects(newRes, generateInheritProperties(change, newRes));
applyNavigationChanges(change, newRes);
} else {
String entryFolderPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName() + "/");
boolean idWasNull = change.getEntryId() == null;
// we don'T really need to create a folder object here anymore.
if (idWasNull) {
// need this for calculateNavPosition, even though the id will get overwritten
change.setEntryId(new CmsUUID());
}
boolean isFunctionDetail = false;
if (change.getCreateParameter() != null) {
if (CmsUUID.isValidUUID(change.getCreateParameter())) {
isFunctionDetail = true;
}
}
entryFolder = new CmsResource(
change.getEntryId(),
new CmsUUID(),
entryFolderPath,
CmsResourceTypeFolder.getStaticTypeId(),
true,
0,
cms.getRequestContext().getCurrentProject().getUuid(),
CmsResource.STATE_NEW,
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
1,
0,
System.currentTimeMillis(),
0);
List<CmsProperty> folderProperties = generateInheritProperties(change, entryFolder);
entryFolder = cms.createResource(
entryFolderPath,
OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.getStaticTypeName()).getTypeId(),
null,
folderProperties);
if (idWasNull) {
change.setEntryId(entryFolder.getStructureId());
}
applyNavigationChanges(change, entryFolder);
entryPath = CmsStringUtil.joinPaths(entryFolderPath, "index.html");
boolean isContainerPage = change.getNewResourceTypeId() == CmsResourceTypeXmlContainerPage.getContainerPageTypeIdSafely();
if (isContainerPage && (copyPage != null)) {
// do *NOT* get this from the cache, because we perform some destructive operation on the XML content
CmsXmlContainerPage page = CmsXmlContainerPageFactory.unmarshal(
cms,
cms.readFile(copyPage),
true,
true);
ensureSingleLocale(page, entryFolder);
if (isFunctionDetail) {
String functionDetailContainer = getFunctionDetailContainerName(parentFolder);
CmsUUID functionStructureId = new CmsUUID(change.getCreateParameter());
CmsResource functionFormatter = cms.readResource(
CmsXmlDynamicFunctionHandler.FORMATTER_PATH,
CmsResourceFilter.ONLY_VISIBLE);
addFunctionDetailElement(
cms,
page,
functionDetailContainer,
functionStructureId,
functionFormatter.getStructureId());
}
content = page.marshal();
}
newRes = cms.createResource(entryPath, change.getNewResourceTypeId(), content, properties);
cms.writePropertyObjects(newRes, generateOwnProperties(change));
}
if (entryFolder != null) {
tryUnlock(entryFolder);
String sitePath = cms.getSitePath(entryFolder);
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE),
false);
newEntry.setSubEntries(getChildren(sitePath, 1, null), null);
newEntry.setChildrenLoadedInitially(true);
}
if (newRes != null) {
tryUnlock(newRes);
}
if (newEntry == null) {
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(cms.getSitePath(newRes), CmsResourceFilter.ONLY_VISIBLE),
false);
}
// mark position as not set
newEntry.setPosition(-1);
newEntry.setNew(true);
change.getClipBoardData().getModifications().remove(null);
change.getClipBoardData().getModifications().put(newEntry.getId(), newEntry);
}
return newEntry;
}
/**
* Creates a new resource info to a given model page resource.<p>
*
* @param cms the current CMS context
* @param modelResource the model page resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the new resource info
*
* @throws CmsException if something goes wrong
*/
private CmsNewResourceInfo createNewResourceInfo(CmsObject cms, CmsResource modelResource, Locale locale)
throws CmsException {
// if model page got overwritten by another resource, reread from site path
if (!cms.existsResource(modelResource.getStructureId(), CmsResourceFilter.ONLY_VISIBLE)) {
modelResource = cms.readResource(cms.getSitePath(modelResource), CmsResourceFilter.ONLY_VISIBLE);
}
int typeId = modelResource.getTypeId();
String name = OpenCms.getResourceManager().getResourceType(typeId).getTypeName();
String title = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
String description = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
try {
CmsGallerySearchResult result = CmsGallerySearch.searchById(cms, modelResource.getStructureId(), locale);
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getTitle())) {
title = result.getTitle();
}
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getDescription())) {
description = result.getDescription();
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
boolean editable = false;
try {
CmsResource freshModelResource = cms.readResource(
modelResource.getStructureId(),
CmsResourceFilter.ONLY_VISIBLE);
editable = cms.hasPermissions(
freshModelResource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.DEFAULT);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
typeId,
name,
title,
description,
modelResource.getStructureId(),
editable,
description);
Float navpos = null;
try {
CmsProperty navposProp = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_NAVPOS, true);
String navposStr = navposProp.getValue();
if (navposStr != null) {
try {
navpos = Float.valueOf(navposStr);
} catch (NumberFormatException e) {
// noop
}
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
info.setNavPos(navpos);
info.setDate(CmsDateUtil.getDate(
new Date(modelResource.getDateLastModified()),
DateFormat.LONG,
getWorkplaceLocale()));
info.setVfsPath(modelResource.getRootPath());
return info;
}
/**
* Creates a resource type info bean for a given resource type.<p>
*
* @param resType the resource type
* @param copyResource the structure id of the copy resource
*
* @return the resource type info bean
*/
private CmsNewResourceInfo createResourceTypeInfo(I_CmsResourceType resType, CmsResource copyResource) {
String name = resType.getTypeName();
Locale locale = getWorkplaceLocale();
String subtitle = CmsWorkplaceMessages.getResourceTypeDescription(locale, name);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subtitle)) {
subtitle = CmsWorkplaceMessages.getResourceTypeName(locale, name);
}
if (copyResource != null) {
return new CmsNewResourceInfo(
copyResource.getTypeId(),
name,
CmsWorkplaceMessages.getResourceTypeName(locale, name),
CmsWorkplaceMessages.getResourceTypeDescription(locale, name),
copyResource.getStructureId(),
false,
subtitle);
} else {
return new CmsNewResourceInfo(resType.getTypeId(), name, CmsWorkplaceMessages.getResourceTypeName(
locale,
name), CmsWorkplaceMessages.getResourceTypeDescription(locale, name), null, false, subtitle);
}
}
/**
* Deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return CmsClientSitemapEntry always null
*
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry delete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource resource = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE);
ensureLock(resource);
cms.deleteResource(cms.getSitePath(resource), CmsResource.DELETE_PRESERVE_SIBLINGS);
tryUnlock(resource);
return null;
}
/**
* Generates a client side lock info object representing the current lock state of the given resource.<p>
*
* @param resource the resource
*
* @return the client lock
*
* @throws CmsException if something goes wrong
*/
private CmsClientLock generateClientLock(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsLock lock = cms.getLock(resource);
CmsClientLock clientLock = new CmsClientLock();
clientLock.setLockType(CmsClientLock.LockType.valueOf(lock.getType().getMode()));
CmsUUID ownerId = lock.getUserId();
if (!lock.isUnlocked() && (ownerId != null)) {
clientLock.setLockOwner(cms.readUser(ownerId).getDisplayName(cms, cms.getRequestContext().getLocale()));
clientLock.setOwnedByUser(cms.getRequestContext().getCurrentUser().getId().equals(ownerId));
}
return clientLock;
}
/**
* Generates a list of property object to save to the sitemap entry folder to apply the given change.<p>
*
* @param change the change
* @param entryFolder the entry folder
*
* @return the property objects
*/
private List<CmsProperty> generateInheritProperties(CmsSitemapChange change, CmsResource entryFolder) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getOwnInternalProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property object to save to the sitemap entry resource to apply the given change.<p>
*
* @param change the change
*
* @return the property objects
*/
private List<CmsProperty> generateOwnProperties(CmsSitemapChange change) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getDefaultFileProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property values inherited to the site-map root entry.<p>
*
* @param rootPath the root entry name
*
* @return the list of property values inherited to the site-map root entry
*
* @throws CmsException if something goes wrong reading the properties
*/
private Map<String, CmsClientProperty> generateParentProperties(String rootPath) throws CmsException {
CmsObject cms = getCmsObject();
if (rootPath == null) {
rootPath = cms.getRequestContext().addSiteRoot("/");
}
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
String parentRootPath = CmsResource.getParentFolder(rootPath);
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
if (parentRootPath != null) {
List<CmsProperty> props = rootCms.readPropertyObjects(parentRootPath, true);
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, true);
result.put(clientProp.getName(), clientProp);
}
}
return result;
}
/**
* Returns the sitemap children for the given path with all descendants up to the given level or to the given target path, ie.
* <dl><dt>levels=1 </dt><dd>only children</dd><dt>levels=2</dt><dd>children and great children</dd></dl>
* and so on.<p>
*
* @param root the site relative root
* @param levels the levels to recurse
* @param targetPath the target path
*
* @return the sitemap children
*
* @throws CmsException if something goes wrong
*/
private List<CmsClientSitemapEntry> getChildren(String root, int levels, String targetPath) throws CmsException {
List<CmsClientSitemapEntry> children = new ArrayList<CmsClientSitemapEntry>();
int i = 0;
for (CmsJspNavElement navElement : getNavBuilder().getNavigationForFolder(
root,
true,
CmsResourceFilter.ONLY_VISIBLE)) {
CmsClientSitemapEntry child = toClientEntry(navElement, false);
if (child != null) {
child.setPosition(i);
children.add(child);
int nextLevels = levels;
if ((nextLevels == 1) && (targetPath != null) && targetPath.startsWith(child.getSitePath())) {
nextLevels = 2;
}
if (child.isFolderType() && ((nextLevels > 1) || (nextLevels == -1)) && !isSubSitemap(navElement)) {
child.setSubEntries(getChildren(child.getSitePath(), nextLevels - 1, targetPath), null);
child.setChildrenLoadedInitially(true);
}
i++;
}
}
return children;
}
/**
* Returns the clipboard data from the current user.<p>
*
* @return the clipboard data
*/
private CmsSitemapClipboardData getClipboardData() {
CmsSitemapClipboardData result = new CmsSitemapClipboardData();
result.setModifications(getModifiedList());
result.setDeletions(getDeletedList());
return result;
}
/**
* Returns the deleted list from the current user.<p>
*
* @return the deleted list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getDeletedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_DELETED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID delId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(delId, CmsResourceFilter.ALL);
if (res.getState().isDeleted()) {
// make sure resource is still deleted
CmsClientSitemapEntry delEntry = new CmsClientSitemapEntry();
delEntry.setSitePath(cms.getSitePath(res));
delEntry.setOwnProperties(getClientProperties(cms, res, false));
delEntry.setName(res.getName());
delEntry.setVfsPath(cms.getSitePath(res));
delEntry.setEntryType(res.isFolder() ? EntryType.folder : isRedirectType(res.getTypeId())
? EntryType.redirect
: EntryType.leaf);
delEntry.setId(delId);
result.put(delId, delEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Gets the type id for entry point folders.<p>
*
* @return the type id for entry point folders
*
* @throws CmsException if something goes wrong
*/
private int getEntryPointType() throws CmsException {
return OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolderExtended.TYPE_ENTRY_POINT).getTypeId();
}
/**
* Gets the container name for function detail elements depending on the parent folder.<p>
*
* @param parent the parent folder
* @return the name of the function detail container
*/
private String getFunctionDetailContainerName(CmsResource parent) {
try {
CmsObject cms = getCmsObject();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsProperty templateProp = cms.readPropertyObject(parent, CmsPropertyDefinition.PROPERTY_TEMPLATE, true);
String templateVal = templateProp.getValue();
if (templateVal == null) {
return null;
}
CmsResource templateRes;
try {
templateRes = cms.readResource(templateVal, CmsResourceFilter.ONLY_VISIBLE);
} catch (CmsVfsResourceNotFoundException e) {
templateRes = rootCms.readResource(templateVal, CmsResourceFilter.ONLY_VISIBLE);
}
CmsProperty containerInfoProp = cms.readPropertyObject(
templateRes,
CmsPropertyDefinition.PROPERTY_CONTAINER_INFO,
true);
String containerInfo = containerInfoProp.getValue() == null ? "" : containerInfoProp.getValue();
Map<String, String> attrs = CmsStringUtil.splitAsMap(containerInfo, "|", "=");
String functionDetailContainerName = attrs.get(KEY_FUNCTION_DETAIL);
return functionDetailContainerName;
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return null;
}
}
/**
* Returns the modified list from the current user.<p>
*
* @return the modified list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getModifiedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID modId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(modId, CmsResourceFilter.ONLY_VISIBLE);
String sitePath = cms.getSitePath(res);
CmsJspNavElement navEntry = getNavBuilder().getNavigationForResource(
sitePath,
CmsResourceFilter.ONLY_VISIBLE);
if (navEntry.isInNavigation()) {
CmsClientSitemapEntry modEntry = toClientEntry(navEntry, false);
result.put(modId, modEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Returns a navigation builder reference.<p>
*
* @return the navigation builder
*/
private CmsJspNavBuilder getNavBuilder() {
if (m_navBuilder == null) {
m_navBuilder = new CmsJspNavBuilder(getCmsObject());
}
return m_navBuilder;
}
/**
* Returns the new resource infos.<p>
*
* @param cms the current CMS context
* @param configData the configuration data from which the new resource infos should be read
* @param locale locale used for retrieving descriptions/titles
*
* @return the new resource infos
*/
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsModelPageConfig modelConfig : configData.getModelPages()) {
try {
result.add(createNewResourceInfo(cms, modelConfig.getResource(), locale));
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
}
Collections.sort(result, new Comparator<CmsNewResourceInfo>() {
public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) {
return ComparisonChain.start().compare(a.getNavPos(), b.getNavPos(), Ordering.natural().nullsLast()).result();
}
});
return result;
}
/**
* Gets the names of all available properties.<p>
*
* @param cms the CMS context
*
* @return the list of all property names
*
* @throws CmsException
*/
private List<String> getPropertyNames(CmsObject cms) throws CmsException {
List<CmsPropertyDefinition> propDefs = cms.readAllPropertyDefinitions();
List<String> result = new ArrayList<String>();
for (CmsPropertyDefinition propDef : propDefs) {
result.add(propDef.getName());
}
return result;
}
/**
* Gets the resource type info beans for types for which new detail pages can be created.<p>
*
* @param cms the current CMS context
* @param resourceTypeConfigs the resource type configurations
* @param functionReferences the function references
* @param modelResource the model resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the resource type info beans for types for which new detail pages can be created
*/
private List<CmsNewResourceInfo> getResourceTypeInfos(
CmsObject cms,
List<CmsResourceTypeConfig> resourceTypeConfigs,
List<CmsFunctionReference> functionReferences,
CmsResource modelResource,
Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsResourceTypeConfig typeConfig : resourceTypeConfigs) {
if (typeConfig.isDetailPagesDisabled()) {
continue;
}
String typeName = typeConfig.getTypeName();
try {
I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(typeName);
result.add(createResourceTypeInfo(resourceType, modelResource));
} catch (CmsLoaderException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
for (CmsFunctionReference functionRef : functionReferences) {
try {
CmsResource functionRes = cms.readResource(functionRef.getStructureId());
String description = cms.readPropertyObject(
functionRes,
CmsPropertyDefinition.PROPERTY_DESCRIPTION,
false).getValue();
String subtitle = description;
try {
CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(
cms,
functionRef.getStructureId(),
getWorkplaceLocale());
subtitle = searchResult.getDescription();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
modelResource.getTypeId(),
CmsDetailPageInfo.FUNCTION_PREFIX + functionRef.getName(),
functionRef.getName(),
description,
modelResource.getStructureId(),
false,
subtitle);
info.setCreateParameter(functionRef.getStructureId().toString());
info.setIsFunction(true);
result.add(info);
} catch (CmsVfsResourceNotFoundException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return result;
}
private CmsClientSitemapEntry getRootEntry(String rootPath, String targetPath)
throws CmsSecurityException, CmsException {
String sitePath = "/";
if (rootPath != null) {
sitePath = getCmsObject().getRequestContext().removeSiteRoot(rootPath);
}
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE);
CmsClientSitemapEntry result = toClientEntry(navElement, true);
if (result != null) {
result.setPosition(0);
result.setChildrenLoadedInitially(true);
result.setSubEntries(getChildren(sitePath, 2, targetPath), null);
}
return result;
}
/**
* Returns the sitemap info for the given base path.<p>
*
* @param basePath the base path
*
* @return the sitemap info
*
* @throws CmsException if something goes wrong reading the resources
*/
private CmsSitemapInfo getSitemapInfo(String basePath) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource baseFolder = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(basePath)) {
baseFolder = cms.readResource(
cms.getRequestContext().removeSiteRoot(basePath),
CmsResourceFilter.ONLY_VISIBLE);
} else {
// in case of an empty base path, use base folder of the current site
basePath = "/";
baseFolder = cms.readResource("/");
}
CmsResource defaultFile = cms.readDefaultFile(baseFolder, CmsResourceFilter.ONLY_VISIBLE);
String title = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(title) && (defaultFile != null)) {
title = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
}
String description = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(description) && (defaultFile != null)) {
description = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
}
return new CmsSitemapInfo(
cms.getRequestContext().getCurrentProject().getName(),
description,
OpenCms.getLocaleManager().getDefaultLocale(cms, baseFolder).toString(),
OpenCms.getSiteManager().getCurrentSite(cms).getUrl()
+ OpenCms.getLinkManager().substituteLinkForUnknownTarget(cms, basePath),
title);
}
/**
* Returns the workplace locale for the current user.<p>
*
* @return the workplace locale
*/
private Locale getWorkplaceLocale() {
Locale result = OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject());
if (result == null) {
result = CmsLocaleManager.getDefaultLocale();
}
if (result == null) {
result = Locale.getDefault();
}
return result;
}
/**
* Checks whether the sitemap change has default file changes.<p>
*
* @param change a sitemap change
* @return true if the change would change the default file
*/
private boolean hasDefaultFileChanges(CmsSitemapChange change) {
return (change.getDefaultFileId() != null) && !change.isNew();
//TODO: optimize this!
}
/**
* Checks whether the sitemap change has changes for the sitemap entry resource.<p>
*
* @param change the sitemap change
* @return true if the change would change the original sitemap entry resource
*/
private boolean hasOwnChanges(CmsSitemapChange change) {
return !change.isNew();
//TODO: optimize this!
}
/**
* Checks whether a resource is a default file of a folder.<p>
*
* @param resource the resource to check
*
* @return true if the resource is the default file of a folder
*
* @throws CmsException if something goes wrong
*/
private boolean isDefaultFile(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
if (resource.isFolder()) {
return false;
}
CmsResource parent = cms.readResource(
CmsResource.getParentFolder(cms.getSitePath(resource)),
CmsResourceFilter.ONLY_VISIBLE);
CmsResource defaultFile = cms.readDefaultFile(parent, CmsResourceFilter.ONLY_VISIBLE);
return resource.equals(defaultFile);
}
/**
* Checks if the toolbar should be displayed.<p>
*
* @param request the current request to get the default locale from
*
* @return <code>true</code> if the toolbar should be displayed
*/
private boolean isDisplayToolbar(HttpServletRequest request) {
// display the toolbar by default
boolean displayToolbar = true;
if (CmsHistoryResourceHandler.isHistoryRequest(request)) {
// we do not want to display the toolbar in case of an historical request
displayToolbar = false;
}
return displayToolbar;
}
/**
* Returns if the given type id matches the xml-redirect resource type.<p>
*
* @param typeId the resource type id
*
* @return <code>true</code> if the given type id matches the xml-redirect resource type
*/
private boolean isRedirectType(int typeId) {
try {
return typeId == OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT).getTypeId();
} catch (Exception e) {
return false;
}
}
/**
* Returns if the given nav-element resembles a sub-sitemap entry-point.<p>
*
* @param navElement the nav-element
*
* @return <code>true</code> if the given nav-element resembles a sub-sitemap entry-point.<p>
* @throws CmsException if something goes wrong
*/
private boolean isSubSitemap(CmsJspNavElement navElement) throws CmsException {
return navElement.getResource().getTypeId() == getEntryPointType();
}
/**
* Applys the given changes to the entry.<p>
*
* @param change the change to apply
*
* @throws CmsException if something goes wrong
*/
private void modifyEntry(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryPage = null;
CmsResource entryFolder = null;
CmsResource ownRes = null;
CmsResource defaultFileRes = null;
try {
// lock all resources necessary first to avoid doing changes only half way through
if (hasOwnChanges(change)) {
ownRes = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE);
ensureLock(ownRes);
}
if (hasDefaultFileChanges(change)) {
defaultFileRes = cms.readResource(change.getDefaultFileId(), CmsResourceFilter.ONLY_VISIBLE);
ensureLock(defaultFileRes);
}
if ((ownRes != null) && ownRes.isFolder()) {
entryFolder = ownRes;
}
if ((ownRes != null) && ownRes.isFile()) {
entryPage = ownRes;
}
if (defaultFileRes != null) {
entryPage = defaultFileRes;
}
if (change.isLeafType()) {
entryFolder = entryPage;
}
updateProperties(cms, ownRes, defaultFileRes, change.getPropertyChanges());
if (change.hasChangedPosition()) {
updateNavPos(ownRes, change);
}
if (entryFolder != null) {
if (change.hasNewParent() || change.hasChangedName()) {
String destinationPath;
if (change.hasNewParent()) {
CmsResource futureParent = cms.readResource(
change.getParentId(),
CmsResourceFilter.ONLY_VISIBLE);
destinationPath = CmsStringUtil.joinPaths(cms.getSitePath(futureParent), change.getName());
} else {
destinationPath = CmsStringUtil.joinPaths(
CmsResource.getParentFolder(cms.getSitePath(entryFolder)),
change.getName());
}
if (change.isLeafType() && destinationPath.endsWith("/")) {
destinationPath = destinationPath.substring(0, destinationPath.length() - 1);
}
// only if the site-path has really changed
if (!cms.getSitePath(entryFolder).equals(destinationPath)) {
cms.moveResource(cms.getSitePath(entryFolder), destinationPath);
}
entryFolder = cms.readResource(entryFolder.getStructureId(), CmsResourceFilter.ONLY_VISIBLE);
}
}
} finally {
if (entryPage != null) {
tryUnlock(entryPage);
}
if (entryFolder != null) {
tryUnlock(entryFolder);
}
}
}
/**
* Helper method for removing all locales except one from a container page.<p>
*
* @param page the container page to proces
* @param localeToKeep the locale which should be kept
*
* @throws CmsXmlException if something goes wrong
*/
private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException {
List<Locale> locales = page.getLocales();
for (Locale locale : locales) {
if (!locale.equals(localeToKeep)) {
page.removeLocale(locale);
}
}
}
/**
* Applys the given remove change.<p>
*
* @param change the change to apply
*
* @return the changed client sitemap entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange removeEntryFromNavigation(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryFolder = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE);
ensureLock(entryFolder);
List<CmsProperty> properties = new ArrayList<CmsProperty>();
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVTEXT,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
cms.writePropertyObjects(cms.getSitePath(entryFolder), properties);
tryUnlock(entryFolder);
return change;
}
/**
* Saves the detail page information of a sitemap to the sitemap's configuration file.<p>
*
* @param detailPages saves the detailpage configuration
* @param resource the configuration file resource
* @param newId the structure id to use for new detail page entries
*
* @throws CmsException
*/
private void saveDetailPages(List<CmsDetailPageInfo> detailPages, CmsResource resource, CmsUUID newId)
throws CmsException {
CmsObject cms = getCmsObject();
CmsDetailPageConfigurationWriter writer = new CmsDetailPageConfigurationWriter(cms, resource);
writer.updateAndSave(detailPages, newId);
}
/**
* Saves the given clipboard data to the session.<p>
*
* @param clipboardData the clipboard data to save
*
* @throws CmsException if something goes wrong writing the user
*/
private void setClipboardData(CmsSitemapClipboardData clipboardData) throws CmsException {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
if (clipboardData != null) {
JSONArray modified = new JSONArray();
if (clipboardData.getModifications() != null) {
for (CmsUUID id : clipboardData.getModifications().keySet()) {
if (id != null) {
modified.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST, modified.toString());
JSONArray deleted = new JSONArray();
if (clipboardData.getDeletions() != null) {
for (CmsUUID id : clipboardData.getDeletions().keySet()) {
if (id != null) {
deleted.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_DELETED_LIST, deleted.toString());
cms.writeUser(user);
}
}
/**
* Determines if the title property of the default file should be changed.<p>
*
* @param properties the current default file properties
* @param folderNavtext the 'NavText' property of the folder
*
* @return <code>true</code> if the title property should be changed
*/
private boolean shouldChangeDefaultFileTitle(Map<String, CmsProperty> properties, CmsProperty folderNavtext) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((folderNavtext != null) && properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
folderNavtext.getValue()));
}
/**
* Determines if the title property should be changed in case of a 'NavText' change.<p>
*
* @param properties the current resource properties
*
* @return <code>true</code> if the title property should be changed in case of a 'NavText' change
*/
private boolean shouldChangeTitle(Map<String, CmsProperty> properties) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT) != null) && properties.get(
CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT).getValue()));
}
/**
* Converts a jsp navigation element into a client sitemap entry.<p>
*
* @param navElement the jsp navigation element
* @param isRoot true if the entry is a root entry
*
* @return the client sitemap entry
* @throws CmsException
*/
private CmsClientSitemapEntry toClientEntry(CmsJspNavElement navElement, boolean isRoot) throws CmsException {
CmsResource entryPage = null;
CmsObject cms = getCmsObject();
CmsClientSitemapEntry clientEntry = new CmsClientSitemapEntry();
CmsResource entryFolder = null;
CmsResource ownResource = navElement.getResource();
clientEntry.setResourceState(ownResource.getState());
CmsResource defaultFileResource = null;
if (ownResource.isFolder()) {
defaultFileResource = cms.readDefaultFile(ownResource, CmsResourceFilter.ONLY_VISIBLE);
}
Map<String, CmsClientProperty> ownProps = getClientProperties(cms, ownResource, false);
Map<String, CmsClientProperty> defaultFileProps = null;
if (defaultFileResource != null) {
defaultFileProps = getClientProperties(cms, defaultFileResource, false);
clientEntry.setDefaultFileId(defaultFileResource.getStructureId());
clientEntry.setDefaultFileType(OpenCms.getResourceManager().getResourceType(defaultFileResource.getTypeId()).getTypeName());
} else {
defaultFileProps = new HashMap<String, CmsClientProperty>();
}
boolean isDefault = isDefaultFile(ownResource);
clientEntry.setId(ownResource.getStructureId());
clientEntry.setFolderDefaultPage(isDefault);
if (navElement.getResource().isFolder()) {
entryFolder = navElement.getResource();
entryPage = defaultFileResource;
clientEntry.setName(entryFolder.getName());
if (entryPage == null) {
entryPage = entryFolder;
}
if (!isRoot && isSubSitemap(navElement)) {
clientEntry.setEntryType(EntryType.subSitemap);
clientEntry.setDefaultFileType(null);
}
CmsLock folderLock = cms.getLock(entryFolder);
clientEntry.setHasForeignFolderLock(!folderLock.isUnlocked()
&& !folderLock.isOwnedBy(cms.getRequestContext().getCurrentUser()));
if (!cms.getRequestContext().getCurrentProject().isOnlineProject()) {
List<CmsResource> blockingChildren = cms.getBlockingLockedResources(entryFolder);
clientEntry.setBlockingLockedChildren((blockingChildren != null) && !blockingChildren.isEmpty());
}
} else {
entryPage = navElement.getResource();
clientEntry.setName(entryPage.getName());
if (isRedirectType(entryPage.getTypeId())) {
clientEntry.setEntryType(EntryType.redirect);
CmsFile file = cms.readFile(entryPage);
I_CmsXmlDocument content = CmsXmlContentFactory.unmarshal(cms, file);
Locale contentLocale = OpenCms.getLocaleManager().getDefaultLocale(cms, entryPage);
// ensure the content contains the default locale
contentLocale = content.getBestMatchingLocale(contentLocale);
if (contentLocale == null) {
// no best matching locale, use the first available
List<Locale> locales = content.getLocales();
if (!locales.isEmpty()) {
contentLocale = locales.get(0);
}
}
String link = "";
if (contentLocale != null) {
link = content.getValue(REDIRECT_LINK_TARGET_XPATH, getCmsObject().getRequestContext().getLocale()).getStringValue(
getCmsObject());
}
clientEntry.setRedirectTarget(link);
} else {
clientEntry.setEntryType(EntryType.leaf);
}
}
long dateExpired = navElement.getResource().getDateExpired();
if (dateExpired != CmsResource.DATE_EXPIRED_DEFAULT) {
clientEntry.setDateExpired(CmsDateUtil.getDate(
new Date(dateExpired),
DateFormat.SHORT,
getWorkplaceLocale()));
}
long dateReleased = navElement.getResource().getDateReleased();
if (dateReleased != CmsResource.DATE_RELEASED_DEFAULT) {
clientEntry.setDateReleased(CmsDateUtil.getDate(
new Date(dateReleased),
DateFormat.SHORT,
getWorkplaceLocale()));
}
clientEntry.setResleasedAndNotExpired(navElement.getResource().isReleasedAndNotExpired(
System.currentTimeMillis()));
String path = cms.getSitePath(entryPage);
clientEntry.setVfsPath(path);
clientEntry.setOwnProperties(ownProps);
clientEntry.setDefaultFileProperties(defaultFileProps);
clientEntry.setSitePath(entryFolder != null ? cms.getSitePath(entryFolder) : path);
//CHECK: assuming that, if entryPage refers to the default file, the lock state of the folder
clientEntry.setLock(generateClientLock(entryPage));
clientEntry.setInNavigation(isRoot || navElement.isInNavigation());
String type = OpenCms.getResourceManager().getResourceType(ownResource).getTypeName();
clientEntry.setResourceTypeName(type);
return clientEntry;
}
/**
* Un-deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return the changed entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange undelete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource deleted = cms.readResource(change.getEntryId(), CmsResourceFilter.ALL);
if (deleted.getState().isDeleted()) {
ensureLock(deleted);
cms.undeleteResource(getCmsObject().getSitePath(deleted), true);
tryUnlock(deleted);
}
String parentPath = CmsResource.getParentFolder(cms.getSitePath(deleted));
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
parentPath,
CmsResourceFilter.ONLY_VISIBLE);
CmsClientSitemapEntry entry = toClientEntry(navElement, navElement.isInNavigation());
entry.setSubEntries(getChildren(parentPath, 2, null), null);
change.setUpdatedEntry(entry);
return change;
}
/**
* Updates the navigation position for a resource.<p>
*
* @param res the resource for which to update the navigation position
* @param change the sitemap change
*
* @throws CmsException if something goes wrong
*/
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException {
if (change.hasChangedPosition()) {
applyNavigationChanges(change, res);
}
}
/**
* Updates properties for a resource and possibly its detail page.<p>
*
* @param cms the CMS context
* @param ownRes the resource
* @param defaultFileRes the default file resource (possibly null)
* @param propertyModifications the property modifications
*
* @throws CmsException if something goes wrong
*/
private void updateProperties(
CmsObject cms,
CmsResource ownRes,
CmsResource defaultFileRes,
List<CmsPropertyModification> propertyModifications) throws CmsException {
Map<String, CmsProperty> ownProps = getPropertiesByName(cms.readPropertyObjects(ownRes, false));
// determine if the title property should be changed in case of a 'NavText' change
boolean changeOwnTitle = shouldChangeTitle(ownProps);
boolean changeDefaultFileTitle = false;
Map<String, CmsProperty> defaultFileProps = Collections.emptyMap();
if (defaultFileRes != null) {
defaultFileProps = getPropertiesByName(cms.readPropertyObjects(defaultFileRes, false));
// determine if the title property of the default file should be changed
changeDefaultFileTitle = shouldChangeDefaultFileTitle(
defaultFileProps,
ownProps.get(CmsPropertyDefinition.PROPERTY_NAVTEXT));
}
String hasNavTextChange = null;
List<CmsProperty> ownPropertyChanges = new ArrayList<CmsProperty>();
List<CmsProperty> defaultFilePropertyChanges = new ArrayList<CmsProperty>();
for (CmsPropertyModification propMod : propertyModifications) {
CmsProperty propToModify = null;
if (ownRes.getStructureId().equals(propMod.getId())) {
if (CmsPropertyDefinition.PROPERTY_NAVTEXT.equals(propMod.getName())) {
hasNavTextChange = propMod.getValue();
} else if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeOwnTitle = false;
}
propToModify = ownProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
ownPropertyChanges.add(propToModify);
} else {
if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeDefaultFileTitle = false;
}
propToModify = defaultFileProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
defaultFilePropertyChanges.add(propToModify);
}
String newValue = propMod.getValue();
if (newValue == null) {
newValue = "";
}
if (propMod.isStructureValue()) {
propToModify.setStructureValue(newValue);
} else {
propToModify.setResourceValue(newValue);
}
}
if (hasNavTextChange != null) {
if (changeOwnTitle) {
CmsProperty titleProp = ownProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
ownPropertyChanges.add(titleProp);
}
if (changeDefaultFileTitle) {
CmsProperty titleProp = defaultFileProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
defaultFilePropertyChanges.add(titleProp);
}
}
if (!ownPropertyChanges.isEmpty()) {
cms.writePropertyObjects(ownRes, ownPropertyChanges);
}
if (!defaultFilePropertyChanges.isEmpty() && (defaultFileRes != null)) {
cms.writePropertyObjects(defaultFileRes, defaultFilePropertyChanges);
}
}
}
|
package org.javarosa.formmanager.view.chatterbox.widget;
import org.javarosa.core.model.QuestionDef;
import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.ChoiceItem;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.MoreUIAccess;
import de.enough.polish.ui.Style;
/**
* The base widget for multi and single choice selections.
*
* NOTE: This class has a number of Hacks that I've made after rooting through
* the j2me polish source. If polish is behaving unpredictably, it is possibly because
* of conflicting changes in new Polish versions with this code. I have outlined
* the latest versions of polish in which the changes appear to work.
*
* Questions should be directed to csims@dimagi.com
*
* @author Clayton Sims
* @date Feb 16, 2009
*
*/
public abstract class SelectEntryWidget extends ExpandedWidget {
private int style;
protected QuestionDef question;
private ChoiceGroup choicegroup;
public SelectEntryWidget (int style) {
this.style = style;
}
protected Item getEntryWidget (QuestionDef question) {
this.question = question;
ChoiceGroup cg = new ChoiceGroup("", style) {
/** Hack #1 & Hack #3**/
// j2me polish refuses to produce events in the case where select items
// are already selected. This code intercepts key presses that toggle
// selection, and clear any existing selection to prevent the supression
// of the appropriate commands.
// Hack #3 is due to the fact that multiple choice items won't fire updates
// unless they haven't been selected by default. The return true here for them
// ensures that the system knows that fires on multi-select always signify
// a capture.
// NOTE: These changes are only necessary for Polish versions > 2.0.5 as far
// as I can tell. I have tested them on 2.0.4 and 2.0.7 and the changes
// were compatibly with both
protected boolean handleKeyReleased(int keyCode, int gameAction) {
boolean gameActionIsFire = getScreen().isGameActionFire(
keyCode, gameAction);
if (gameActionIsFire) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
if(this.choiceType != ChoiceGroup.MULTIPLE) {
//Hack
choiceItem.isSelected = false;
}
}
boolean superReturn = super.handleKeyReleased(keyCode, gameAction);
if(gameActionIsFire && this.choiceType == ChoiceGroup.MULTIPLE) {
//Hack
return true;
} else {
return superReturn;
}
}
public int getScrollHeight() {
return super.getScrollHeight();
}
/** Hack #2 **/
//This is a slight UI hack that is in place to make the choicegroup properly
//intercept 'up' and 'down' inputs. Essentially Polish is very broken when it comes
//to scrolling nested containers, and this function properly takes the parent (Widget) position
//into account as well as the choicegroup's
// I have tested this change with Polish 2.0.4 on Nokia Phones and the emulators and it works
// correctly. It also works correctly on Polish 2.0.7 on the emulator, but I have not attempted
// to use it on a real nokia phone.
public int getRelativeScrollYOffset() {
if (!this.enableScrolling && this.parent instanceof Container) {
// Clayton Sims - Feb 9, 2009 : Had to go through and modify this code again.
// The offsets are now accumulated through all of the parent containers, not just
// one.
Item walker = this.parent;
int offset = 0;
//Walk our parent containers and accumulate their offsets.
while(walker instanceof Container) {
// Clayton Sims - Apr 3, 2009 :
// If the container can scroll, it's relativeY is useless, it's in a frame and
// the relativeY isn't actually applicable.
// Actually, this should almost certainly _just_ break out of the loop if
// we hit something that scrolls, but if we have multiple scrolling containers
// nested, someone _screwed up_.
if(!MoreUIAccess.isScrollingContainer((Container)walker)) {
offset += walker.relativeY;
}
walker = walker.getParent();
}
//The value returned here (The + offest part) is the fix.
int absOffset = ((Container)this.parent).getScrollYOffset() + this.relativeY + offset;
return absOffset;
// Clayton Sims - Feb 10, 2009 : Rolled back because it doesn't work on the 3110c, apparently!
// Fixing soon.
//return ((Container)this.parent).getScrollYOffset() + this.relativeY + this.parent.relativeY;
}
int offset = this.targetYOffset;
//#ifdef polish.css.scroll-mode
if (!this.scrollSmooth) {
offset = this.yOffset;
}
//#endif
return offset;
}
/** Hack #4! **/
//Clayton Sims - Jun 16, 2009
// Once again we're in the land of hacks.
// This particular hack is responsible for making it so that when a widget is
// brought up on the screen, its selected value (if one exists), is currently
// highlighted. This vastly improves the back/forward usability.
// Only Tested on Polish 2.0.4
public Style focus (Style newStyle, int direction) {
Style retStyle = super.focus(newStyle, direction);
if(this.getSelectedIndex() > -1) {
this.focus(this.getSelectedIndex());
}
return retStyle;
}
};
for (int i = 0; i < question.getSelectItems().size(); i++){
cg.append("", null);
}
this.choicegroup = cg;
return cg;
}
protected ChoiceGroup choiceGroup () {
//return (ChoiceGroup)entryWidget;
return this.choicegroup;
}
protected void updateWidget (QuestionDef question) {
for (int i = 0; i < choiceGroup().size(); i++) {
choiceGroup().getItem(i).setText((String)question.getSelectItems().keyAt(i));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.