answer stringlengths 17 10.2M |
|---|
package com.myjeeva.digitalocean.pojo;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import com.google.gson.annotations.Expose;
/**
* Represents DomainRecord (TLD) Record attributes of DigitalOcean DNS. Revised as per v2 API data
* structure.
*
* @author Jeevanandam M. (jeeva@myjeeva.com)
*/
public class DomainRecord extends RateLimitBase {
private static final long serialVersionUID = 5656335027984698525L;
private Integer id;
@Expose
private String type;
@Expose
private String name;
@Expose
private String data;
@Expose
private Integer priority;
@Expose
private Integer port;
@Expose
private Integer weight;
@Expose
private Integer ttl;
public DomainRecord() {
// Default Constructor
}
public DomainRecord(String name) {
this.name = name;
}
public DomainRecord(String name, String type) {
this(name, null, type, null, null, null);
}
public DomainRecord(String name, String data, String type) {
this(name, data, type, null, null, null);
}
public DomainRecord(String name, String data, String type, Integer priority, Integer port,
Integer weight) { this(name, data, type, priority, null, null, null); }
public DomainRecord(String name, String data, String type, Integer priority, Integer port,
Integer weight, Integer ttl) {
this.name = name;
this.data = data;
this.type = type;
this.priority = priority;
this.port = port;
this.weight = weight;
this.ttl = ttl;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the data
*/
public String getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(String data) {
this.data = data;
}
/**
* @return the priority
*/
public Integer getPriority() {
return priority;
}
/**
* @param priority the priority to set
*/
public void setPriority(Integer priority) {
this.priority = priority;
}
/**
* @return the port
*/
public Integer getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(Integer port) {
this.port = port;
}
/**
* @return the weight
*/
public Integer getWeight() {
return weight;
}
/**
* @param weight the weight to set
*/
public void setWeight(Integer weight) {
this.weight = weight;
}
/**
* @return the TTL, in seconds
*/
public Integer getTtl() {
return ttl;
}
/**
* @param ttl the TTL, in seconds
*/
public void setTtl(Integer ttl) {
this.ttl = ttl;
}
} |
package com.setycz.AnotherDustsMod;
import com.setycz.AnotherDustsMod.Crusher.BlockCrusher;
import com.setycz.AnotherDustsMod.Crusher.BlockCrusherOn;
import com.setycz.AnotherDustsMod.Crusher.CrusherRegistry;
import com.setycz.AnotherDustsMod.Crusher.TileEntityCrusher;
import com.setycz.AnotherDustsMod.Dust.ItemDust;
import com.setycz.AnotherDustsMod.InventoryBlock.TileEntityGuiHandler;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
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.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Method;
@Mod(
modid = ModAnotherDusts.MODID,
name = ModAnotherDusts.MODNAME,
version = ModAnotherDusts.VERSION,
acceptedMinecraftVersions = "1.8.9"
)
public class ModAnotherDusts {
public static final String MODID = "anotherdusts";
public static final String VERSION = "1.1";
public static final String MODNAME = "Another Dusts";
public static final String TCONSTRUCT = "tconstruct";
@Mod.Instance(MODID)
public static ModAnotherDusts instance;
public static final Logger log = LogManager.getLogger(MODID);
public final static AnotherDustsTab tab = new AnotherDustsTab();
public final static Item iron_dust = new ItemDust().setColor(14794665).setUnlocalizedName("iron_dust").setCreativeTab(tab);
public final static Item gold_dust = new ItemDust().setColor(16444747).setUnlocalizedName("gold_dust").setCreativeTab(tab);
public final static Block crusher = new BlockCrusher().setUnlocalizedName("crusher").setCreativeTab(tab);
public final static Block crusher_on = new BlockCrusherOn().setUnlocalizedName("crusher_on").setLightLevel(0.875F);
public static TileEntityGuiHandler guiHandler = new TileEntityGuiHandler();
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
NetworkRegistry.INSTANCE.registerGuiHandler(instance, guiHandler);
}
@EventHandler
public void init(FMLInitializationEvent event) {
log.info("Crushing vanila resources.");
registerDust(event, iron_dust, Items.iron_ingot, 0);
registerDust(event, gold_dust, Items.gold_ingot, 0);
registerBlock(event, crusher);
registerBlock(event, crusher_on);
GameRegistry.registerTileEntity(TileEntityCrusher.class, "anotherDustsCrusher");
GameRegistry.addRecipe(
new ItemStack(crusher),
"FFF", "FFF", "PRP",
'F', Items.flint, 'P', Blocks.piston, 'R', Blocks.furnace);
CrusherRegistry.registerRecipe(Blocks.iron_ore, 0, iron_dust, 0, 2);
CrusherRegistry.registerRecipe(Blocks.gold_ore, 0, gold_dust, 0, 2);
CrusherRegistry.registerRecipe(Blocks.coal_ore, 0, Items.coal, 0, 2);
CrusherRegistry.registerRecipe(Blocks.lapis_ore, 0, Items.dye, EnumDyeColor.BLUE.getDyeDamage(), 9);
CrusherRegistry.registerRecipe(Blocks.diamond_ore, 0, Items.diamond, 0, 2);
CrusherRegistry.registerRecipe(Blocks.emerald_ore, 0, Items.emerald, 0, 2);
CrusherRegistry.registerRecipe(Blocks.quartz_ore, 0, Items.quartz, 0, 2);
CrusherRegistry.registerRecipe(Blocks.redstone_ore, 0, Items.redstone, 0, 6);
registerTConstruct(event);
}
private void registerTConstruct(FMLInitializationEvent event) {
if(!Loader.isModLoaded(TCONSTRUCT)) {
return;
}
log.info("Tinkers Construct mod detected, crushing even more dusts.");
Item tIngots = GameRegistry.findItem(TCONSTRUCT, "ingots");
Block tOre = GameRegistry.findBlock(TCONSTRUCT, "ore");
Item cobalt_dust = new ItemDust().setColor(2306186).setUnlocalizedName("cobalt_dust").setCreativeTab(tab);
registerDust(event, cobalt_dust, tIngots, 0);
CrusherRegistry.registerRecipe(tOre, 0, cobalt_dust, 0, 2);
Item ardite_dust = new ItemDust().setColor(11019543).setUnlocalizedName("ardite_dust").setCreativeTab(tab);
registerDust(event, ardite_dust, tIngots, 1);
CrusherRegistry.registerRecipe(tOre, 1, ardite_dust, 0, 2);
try {
Class tinkerRegistryClass = Class.forName("slimeknights.tconstruct.library.TinkerRegistry");
Method m = tinkerRegistryClass.getDeclaredMethod("registerMelting", String.class, Fluid.class, int.class);
m.invoke(null, getItemName(iron_dust), FluidRegistry.getFluid("iron"), 144);
m.invoke(null, getItemName(gold_dust), FluidRegistry.getFluid("gold"), 144);
m.invoke(null, getItemName(cobalt_dust), FluidRegistry.getFluid("cobalt"), 144);
m.invoke(null, getItemName(ardite_dust), FluidRegistry.getFluid("ardite"), 144);
}
catch (Exception e) {
log.error("Cannot register melting recipes for crushed resources.", e);
}
}
@EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
private void registerDust(FMLInitializationEvent event, Item dust, Item ingot, int ingotMeta) {
registerItem(event, dust);
GameRegistry.addSmelting(dust, new ItemStack(ingot, 1, ingotMeta), 1f);
OreDictionary.registerOre(getItemName(dust), dust);
}
private void registerBlock(FMLInitializationEvent event, Block block) {
GameRegistry.registerBlock(block, block.getUnlocalizedName().substring(5));
if (event.getSide() == Side.CLIENT) {
Item crusherItem = Item.getItemFromBlock(block);
registerItemModel(crusherItem);
}
}
private void registerItem(FMLInitializationEvent event, Item item) {
GameRegistry.registerItem(item, getItemName(item));
if (event.getSide() == Side.CLIENT) {
registerItemModel(item);
}
}
private void registerItemModel(Item item) {
ModelResourceLocation resourceLocation = new ModelResourceLocation(MODID + ":" + getItemName(item), "inventory");
Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item, 0, resourceLocation);
}
private String getItemName(Item dust) {
return dust.getUnlocalizedName().substring(5);
}
} |
package com.soasta.jenkins;
import java.io.IOException;
import java.util.regex.Pattern;
import jenkins.model.Jenkins;
import hudson.AbortException;
import hudson.FilePath;
import hudson.ProxyConfiguration;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
public abstract class AbstractSCommandBuilder extends Builder {
/**
* URL of {@link CloudTestServer}.
*/
private final String url;
public AbstractSCommandBuilder(String url) {
this.url = url;
}
public CloudTestServer getServer() {
return CloudTestServer.get(url);
}
public String getUrl() {
return url;
}
protected ArgumentListBuilder getSCommandArgs(AbstractBuild<?, ?> build, BuildListener listener) throws IOException, InterruptedException {
CloudTestServer s = getServer();
if (s == null)
throw new AbortException("No TouchTest server is configured in the system configuration.");
// Download SCommand, if needed.
// We remember the location for next time, since this might be called
// more than once for a single build step (e.g. TestCompositionRunner
// with a list of compositions).
// As far as I know, this null check does not need to be thread-safe.
FilePath scommand = new SCommandInstaller(s).scommand(build.getBuiltOn(), listener);
ArgumentListBuilder args = new ArgumentListBuilder();
args.add(scommand)
.add("url=" + s.getUrl())
.add("username="+s.getUsername())
.addMasked("password=" + s.getPassword());
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
if (proxyConfig != null && proxyConfig.name != null) {
// Jenkins is configured to use a proxy server.
// Extract the destination CloudTest host.
String host = s.getUrl().getHost();
// Check if the proxy applies for this destination host.
// This code is more or less copied from ProxyConfiguration.createProxy() :-(.
boolean isNonProxyHost = false;
for (Pattern p : proxyConfig.getNoProxyHostPatterns()) {
if (p.matcher(host).matches()) {
// It's a match.
// Don't use the proxy.
isNonProxyHost = true;
// No need to continue checking the list.
break;
}
}
if (!isNonProxyHost) {
// Add the SCommand proxy parameters.
args.add("httpproxyhost=" + proxyConfig.name)
.add("httpproxyport=" + proxyConfig.port);
// If there are proxy credentials, add those too.
if (proxyConfig.getUserName() != null) {
args.add("httpproxyusername=" + proxyConfig.getUserName())
.addMasked("httpproxypassword=" + proxyConfig.getPassword());
}
}
}
return args;
}
} |
package com.spaceapplications.yamcs.scpi;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Commander {
private static String COL_FORMAT = "%-20s %s";
private Optional<Command> context = Optional.empty();
private static class Command {
private static final String DEFAULT_PROMPT = "$ ";
private String cmd;
private String description;
private BiFunction<Command, String, String> exec;
private String prompt = DEFAULT_PROMPT;
public static Command of(String cmd, String description, BiFunction<Command, String, String> exec) {
Command c = new Command();
c.cmd = cmd;
c.description = description;
c.exec = exec;
return c;
}
public String cmd() {
return cmd;
}
public void setPrompt(String prompt) {
this.prompt = prompt;
}
public String prompt() {
return prompt;
}
public String description() {
return description;
}
public String execute(String cmd) {
String args = cmd.replaceFirst(this.cmd, "").trim();
return exec.apply(this, args);
}
}
private List<Command> commands = new ArrayList<>();
public Commander(Config config) {
commands.add(Command.of("device list", "List available devices to manage.", (command, na) -> {
String header = String.format("Available devices:\n" + COL_FORMAT + "\n", "ID", "DESCRIPTION");
String devList = config.devices.entrySet().stream()
.map(set -> String.format(COL_FORMAT, set.getKey(), set.getValue().description))
.collect(Collectors.joining("\n"));
return header + devList;
}));
commands.add(Command.of("device inspect", "Print device configuration details.", (command, deviceId) -> {
return Optional.ofNullable(config.devices).map(devices -> devices.get(deviceId)).map(Config::dump)
.orElse(MessageFormat.format("device \"{0}\" not found", deviceId));
}));
commands.add(Command.of("device connect", "Connect and interact with a given device.", (command, deviceId) -> {
String prompt = "device:" + deviceId + Command.DEFAULT_PROMPT;
command.setPrompt(prompt);
Command contextCmd = Command.of("", "", (na, cmd) -> cmd.isEmpty() ? "" : deviceId + "(" + cmd + ")");
contextCmd.setPrompt("device:" + deviceId + Command.DEFAULT_PROMPT);
context = Optional.of(contextCmd);
return "connect to: " + deviceId;
}));
commands.add(Command.of("help", "Prints this description.", (command, na) -> {
return "Available commands:\n" + commands.stream().map(c -> String.format(COL_FORMAT, c.cmd(), c.description()))
.collect(Collectors.joining("\n"));
}));
}
public String confirm() {
return "Connected. Run help for more info." + "\r\n$ ";
}
public String execute(String cmd) {
return context.map(command -> exec(command, cmd)).orElse(execMatching(cmd));
}
private String execMatching(String cmd) {
return commands.stream().filter(command -> cmd.startsWith(command.cmd())).findFirst()
.map(command -> exec(command, cmd))
.orElse(cmd.isEmpty() ? Command.DEFAULT_PROMPT : cmd + ": command not found\n" + Command.DEFAULT_PROMPT);
}
private String exec(Command command, String cmd) {
return cmd.isEmpty() ? command.prompt() : command.execute(cmd) + "\n" + command.prompt();
}
} |
package com.teamid;
import com.teamid.repository.CinemaRepository;
import com.teamid.repository.MovieRepository;
import com.teamid.repository.ScheduleRepository;
import com.teamid.repository.TicketRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@SpringBootApplication
@EnableRedisHttpSession
public class TicketBookingBackEndApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(TicketBookingBackEndApplication.class);
app.setWebEnvironment(true);
app.run(args);
}
@Bean
public CommandLineRunner init(CinemaRepository cinemaRepository,
MovieRepository movieRepository,
ScheduleRepository scheduleRepository,
TicketRepository ticketRepository) {
return args -> {
// DataUtils.addTestData(cinemaRepository, movieRepository, scheduleRepository, ticketRepository);
};
}
} |
package com.telekom.m2m.cot.restsdk.event;
import com.google.gson.Gson;
import com.telekom.m2m.cot.restsdk.CloudOfThingsRestClient;
import com.telekom.m2m.cot.restsdk.util.ExtensibleObject;
import com.telekom.m2m.cot.restsdk.util.Filter;
import com.telekom.m2m.cot.restsdk.util.GsonUtils;
public class EventApi {
private final CloudOfThingsRestClient cloudOfThingsRestClient;
private static final String CONTENT_TYPE = "application/vnd.com.nsn.cumulocity.event+json;charset=UTF-8;ver=0.9";
private final Gson gson = GsonUtils.createGson();
/**
* Internal Constructor.
*
* @param cloudOfThingsRestClient the configured rest client.
*/
public EventApi(CloudOfThingsRestClient cloudOfThingsRestClient) {
this.cloudOfThingsRestClient = cloudOfThingsRestClient;
}
/**
* Retrives a specific Event.
* @param eventId of the desired Event.
* @return the Event (or null if not found).
*/
public Event getEvent(String eventId) {
String response = cloudOfThingsRestClient.getResponse(eventId, "event/events/", CONTENT_TYPE);
Event event = new Event(gson.fromJson(response, ExtensibleObject.class));
return event;
}
/**
* Stores a Event.
* @param event the event to create.
* @return the created event with the ID.
*/
public Event createEvent(Event event) {
String json = gson.toJson(event);
String id = cloudOfThingsRestClient.doRequestWithIdResponse(json, "event/events/", CONTENT_TYPE);
event.setId(id);
return event;
}
/**
* Deletes a Event.
* @param event the Event to delete
*/
public void deleteEvent(Event event) {
cloudOfThingsRestClient.delete(event.getId(), "event/events/");
}
/**
* Retrieves Events.
*
* @return the found Events.
*/
public EventCollection getEvents() {
return new EventCollection(cloudOfThingsRestClient);
}
/**
* Retrieves Events filtered by criteria.
*
* @param filters filters of event attributes.
* @return the EventCollections to navigate through the results.
* @since 0.2.0
*/
public EventCollection getEvents(Filter.FilterBuilder filters) {
return new EventCollection(filters, cloudOfThingsRestClient);
}
/**
* Deletes a collection of Events by criteria.
*
* @param filters filters of Event attributes.
*/
public void deleteEvents(Filter.FilterBuilder filters) {
cloudOfThingsRestClient.delete("", "event/events?" + filters.buildFilter() + "&x=");
}
} |
// Getdown - application installer, patcher and launcher
// provided that the following conditions are met:
// with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.threerings.getdown.launcher;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import com.samskivert.util.StringUtil;
import com.samskivert.swing.util.SwingUtil;
import static com.threerings.getdown.Log.log;
/**
* The main application entry point for Getdown.
*/
public class GetdownApp
{
public static void main (String[] argArray)
{
// maybe they specified the appdir in a system property
int aidx = 0;
List<String> args = Arrays.asList(argArray);
String adarg = System.getProperty("appdir");
// if not, check for a command line argument
if (StringUtil.isBlank(adarg)) {
if (args.isEmpty()) {
System.err.println("Usage: java -jar getdown.jar app_dir [app_id] [app args]");
System.exit(-1);
}
adarg = args.get(aidx++);
}
// look for a specific app identifier
String appId = (aidx < args.size()) ? args.get(aidx++) : null;
// pass along anything after that as app args
String[] appArgs = (aidx < args.size())
? args.subList(aidx, args.size()).toArray(new String[0]) : null;
// ensure a valid directory was supplied
File appDir = new File(adarg);
if (!appDir.exists() || !appDir.isDirectory()) {
log.warning("Invalid app_dir '" + adarg + "'.");
System.exit(-1);
}
// pipe our output into a file in the application directory
if (System.getProperty("no_log_redir") == null) {
File logFile = new File(appDir, "launcher.log");
try {
PrintStream logOut = new PrintStream(
new BufferedOutputStream(new FileOutputStream(logFile)), true);
System.setOut(logOut);
System.setErr(logOut);
} catch (IOException ioe) {
log.warning("Unable to redirect output to '" + logFile + "': " + ioe);
}
}
// record a few things for posterity
log.info("
log.info("-- OS Name: " + System.getProperty("os.name"));
log.info("-- OS Arch: " + System.getProperty("os.arch"));
log.info("-- OS Vers: " + System.getProperty("os.version"));
log.info("-- Java Vers: " + System.getProperty("java.version"));
log.info("-- Java Home: " + System.getProperty("java.home"));
log.info("-- User Name: " + System.getProperty("user.name"));
log.info("-- User Home: " + System.getProperty("user.home"));
log.info("-- Cur dir: " + System.getProperty("user.dir"));
log.info("
try {
Getdown app = new Getdown(appDir, appId, null, null, appArgs) {
@Override
protected Container createContainer () {
// create our user interface, and display it
String title = StringUtil.isBlank(_ifc.name) ? "" : _ifc.name;
if (_frame == null) {
_frame = new JFrame(title);
_frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing (WindowEvent evt) {
handleWindowClose();
}
});
_frame.setResizable(false);
} else {
_frame.setTitle(title);
_frame.getContentPane().removeAll();
}
if (_ifc.iconImages != null) {
ArrayList<Image> icons = new ArrayList<Image>();
for (String path : _ifc.iconImages) {
Image img = loadImage(path);
if (img == null) {
log.warning("Error loading icon image", "path", path);
} else {
icons.add(img);
}
}
if (icons.isEmpty()) {
log.warning("Failed to load any icons", "iconImages", _ifc.iconImages);
} else {
SwingUtil.setFrameIcons(_frame, icons);
}
}
_frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
return _frame.getContentPane();
}
@Override
protected void showContainer () {
if (_frame != null) {
_frame.pack();
SwingUtil.centerWindow(_frame);
_frame.setVisible(true);
}
}
@Override
protected void disposeContainer () {
if (_frame != null) {
_frame.dispose();
_frame = null;
}
}
@Override
protected void exit (int exitCode) {
System.exit(exitCode);
}
protected JFrame _frame;
};
app.start();
} catch (Exception e) {
log.warning("main() failed.", e);
}
}
} |
package com.treasure_data.jdbc.command;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import org.msgpack.MessagePack;
import org.msgpack.unpacker.Unpacker;
import com.treasure_data.client.ClientException;
import com.treasure_data.client.TreasureDataClient;
import com.treasure_data.jdbc.JDBCURLParser;
import com.treasure_data.jdbc.TDConnection;
import com.treasure_data.jdbc.TDResultSet;
import com.treasure_data.jdbc.TDResultSetBase;
import com.treasure_data.jdbc.Config;
import com.treasure_data.logger.TreasureDataLogger;
import com.treasure_data.model.AuthenticateRequest;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.GetJobResultRequest;
import com.treasure_data.model.GetJobResultResult;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobResult;
import com.treasure_data.model.JobResult2;
import com.treasure_data.model.JobSummary;
import com.treasure_data.model.SubmitJobRequest;
import com.treasure_data.model.SubmitJobResult;
import com.treasure_data.model.TableSummary;
public class TDClientAPI implements ClientAPI {
private static final Logger LOG = Logger.getLogger(TDClientAPI.class
.getName());
private TreasureDataClient client;
private JDBCURLParser.Desc desc;
private Properties props;
private Database database;
private int maxRows = 5000;
public TDClientAPI(TDConnection conn) throws SQLException {
this(null, new TreasureDataClient(conn.getProperties()), conn
.getProperties(), conn.getDatabase(), conn.getMaxRows());
}
public TDClientAPI(JDBCURLParser.Desc desc, TDConnection conn) throws SQLException {
this(desc, new TreasureDataClient(conn.getProperties()), conn
.getProperties(), conn.getDatabase(), conn.getMaxRows());
}
public TDClientAPI(TreasureDataClient client, Properties props,
Database database) throws SQLException {
this(null, client, props, database, 5000);
}
public TDClientAPI(JDBCURLParser.Desc desc, TreasureDataClient client,
Properties props, Database database, int maxRows) throws SQLException {
this.client = client;
this.props = props;
this.database = database;
this.maxRows = maxRows;
this.desc = desc;
try {
checkCredentials();
} catch (ClientException e) {
throw new SQLException(e);
}
{
Properties sysprops = System.getProperties();
if (sysprops.getProperty(Config.TD_LOGGER_AGENTMODE) == null) {
sysprops.setProperty(Config.TD_LOGGER_AGENTMODE, "false");
}
if (sysprops.getProperty(Config.TD_LOGGER_API_KEY) == null) {
String apiKey = client.getTreasureDataCredentials().getAPIKey();
sysprops.setProperty(Config.TD_LOGGER_API_KEY, apiKey);
}
}
}
private void checkCredentials() throws ClientException {
String apiKey = client.getTreasureDataCredentials().getAPIKey();
if (apiKey != null) {
return;
}
if (props == null) {
return;
}
String user = props.getProperty("user");
String password = props.getProperty("password");
client.authenticate(new AuthenticateRequest(user, password));
}
public List<DatabaseSummary> showDatabases() throws ClientException {
return client.listDatabases();
}
public DatabaseSummary showDatabase() throws ClientException {
List<DatabaseSummary> databases = client.listDatabases();
for (DatabaseSummary db : databases) {
if (db.getName().equals(database.getName())) {
return db;
}
}
return null;
}
public List<TableSummary> showTables() throws ClientException {
return client.listTables(database);
}
public boolean drop(String table) throws ClientException {
client.deleteTable(database.getName(), table);
return true;
}
public boolean create(String table) throws ClientException {
client.createTable(database, table);
return true;
}
public boolean insert(String tableName, Map<String, Object> record)
throws ClientException {
TreasureDataLogger logger = TreasureDataLogger.getLogger(database
.getName());
return logger.log(tableName, record);
}
public TDResultSetBase select(String sql) throws ClientException {
return select(sql, 0);
}
public TDResultSetBase select(String sql, int queryTimeout)
throws ClientException {
TDResultSetBase rs = null;
Job job;
if (desc == null || desc.type == null) {
job = new Job(database, sql); // It's, by default, executed by hive.
} else {
job = new Job(database, desc.type, sql, null);
}
SubmitJobRequest request = new SubmitJobRequest(job);
SubmitJobResult result = client.submitJob(request);
job = result.getJob();
if (job != null) {
rs = new TDResultSet(this, maxRows, job, queryTimeout);
}
return rs;
}
public JobSummary waitJobResult(Job job) throws ClientException {
String jobID = job.getJobID();
while (true) {
JobSummary.Status stat = client.showJobStatus(job);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Job status: " + stat);
}
if (stat == JobSummary.Status.SUCCESS) {
LOG.fine("Job worked successfully.");
break;
} else if (stat == JobSummary.Status.ERROR) {
JobSummary js = client.showJob(job);
String msg = String.format(
"Job '%s' failed: got Job status 'error'", jobID);
LOG.severe(msg);
if (js.getDebug() != null) {
msg = msg + "\n" + js.getDebug().getStderr();
LOG.severe("cmdout:");
LOG.severe(js.getDebug().getCmdout());
LOG.severe("stderr:");
LOG.severe(js.getDebug().getStderr());
}
throw new ClientException(msg);
} else if (stat == JobSummary.Status.KILLED) {
String msg = String.format(
"Job '%s' failed: got Job status 'killed'", jobID);
LOG.severe(msg);
throw new ClientException(msg);
}
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
return null;
}
}
return client.showJob(job);
}
public Unpacker getJobResult(Job job) throws ClientException {
GetJobResultRequest request = new GetJobResultRequest(
new JobResult(job));
GetJobResultResult result = client.getJobResult(request);
return result.getJobResult().getResult();
}
public ExtUnpacker getJobResult2(Job job) throws ClientException {
File file = null;
int retryCount = 0;
int retryCountThreshold = Integer.parseInt(props.getProperty(
Config.TD_JDBC_RESULT_RETRYCOUNT_THRESHOLD,
Config.TD_JDBC_RESULT_RETRYCOUNT_THRESHOLD_DEFAULTVALUE));
while (true) {
try {
LOG.info("write the result to file");
file = writeJobResultToTempFile(job);
break;
} catch (Throwable t) {
LOG.warning("cought exception: message = " + t.getMessage());
t.printStackTrace();
// catch ClientException, IOException
if (!(retryCount < retryCountThreshold)) {
throw new ClientException(
"re-try out writing: threashold = "
+ retryCountThreshold);
}
retryCount++;
LOG.info("re-try writing: imcremented retryCount = "
+ retryCount);
long retryWaitTime = Long.parseLong(props.getProperty(
Config.TD_JDBC_RESULT_RETRY_WAITTIME,
Config.TD_JDBC_RESULT_RETRY_WAITTIME_DEFAULTVALUE));
try {
LOG.info("wait for re-try: timeout = " + retryWaitTime);
Thread.sleep(retryWaitTime);
} catch (InterruptedException e) {
// ignore
}
}
}
if (file == null) {
throw new ClientException("cannot write job result: file is null.");
}
// return the data in the temp file
try {
LOG.info("read the result to file: path = "
+ file.getAbsolutePath());
InputStream fin = new GZIPInputStream(new BufferedInputStream(
new FileInputStream(file)));
return new ExtUnpacker(file,
new MessagePack().createUnpacker(new BufferedInputStream(
fin)));
} catch (IOException e) {
throw new ClientException(e);
}
}
private File writeJobResultToTempFile(Job job) throws ClientException,
IOException {
GetJobResultRequest request = new GetJobResultRequest(new JobResult2(
job));
GetJobResultResult result = client.getJobResult(request);
// download data of job result and write it to temp file
long readSize = 0;
long resultSize = result.getJobResult().getResultSize();
LOG.info("check the size of the job result: size = " + resultSize);
InputStream rin = new BufferedInputStream(
((JobResult2) result.getJobResult()).getResultInputStream());
File file = null;
OutputStream fout = null;
try {
file = File.createTempFile("td-jdbc-", ".tmp");
LOG.info("created temp file: " + file.getAbsolutePath());
fout = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[1024];
int len;
while ((len = rin.read(buf)) != -1) {
readSize += len;
fout.write(buf, 0, len);
}
fout.flush();
LOG.info("read the size of the job result: " + readSize);
if (readSize < resultSize) {
throw new IOException("Cannot read all data of the job result");
}
LOG.info("finished writing file");
return file;
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
// ignore
}
}
if (rin != null) {
try {
rin.close();
} catch (IOException e) {
// ignore
}
}
}
}
public boolean flush() {
TreasureDataLogger logger = TreasureDataLogger.getLogger(database
.getName());
logger.flush();
return true;
}
public void close() throws ClientException {
TreasureDataLogger logger = TreasureDataLogger.getLogger(database
.getName());
if (logger != null) {
logger.flush();
logger.close();
}
}
} |
package com.youcruit.onfido.api.checks;
import java.io.IOException;
import java.net.URI;
import com.youcruit.onfido.api.applicants.ApplicantId;
import com.youcruit.onfido.api.http.OnfidoHttpClient;
public class CheckClient {
public final OnfidoHttpClient httpClient;
public CheckClient(final OnfidoHttpClient httpClient) {
this.httpClient = httpClient;
}
public Check createCheck(CreateCheckRequest checkRequest, ApplicantId applicantId) throws IOException {
URI uri = httpClient.pathToUri("applicants", applicantId.getId(), "checks");
return httpClient.sync(uri, checkRequest, OnfidoHttpClient.Method.POST, Check.class);
}
public Check getCheck(ApplicantId applicantId, CheckId checkId) throws IOException {
URI uri = httpClient.pathToUri("applicants", applicantId.getId(), "checks", checkId.getId());
return httpClient.sync(uri, null, OnfidoHttpClient.Method.GET, Check.class);
}
} |
package net.runelite.client.plugins.demonicgorilla;
import com.google.common.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.AnimationID;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.HeadIcon;
import net.runelite.api.Hitsplat;
import net.runelite.api.NPC;
import net.runelite.api.NpcID;
import net.runelite.api.Player;
import net.runelite.api.Projectile;
import net.runelite.api.ProjectileID;
import net.runelite.api.coords.WorldArea;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.HitsplatApplied;
import net.runelite.api.events.NpcDespawned;
import net.runelite.api.events.NpcSpawned;
import net.runelite.api.events.PlayerDespawned;
import net.runelite.api.events.PlayerSpawned;
import net.runelite.api.events.ProjectileMoved;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.ui.overlay.Overlay;
@PluginDescriptor(
name = "Demonic Gorillas"
)
@Slf4j
public class DemonicGorillaPlugin extends Plugin
{
@Inject
private Client client;
@Inject
private DemonicGorillaOverlay overlay;
@Getter
private Map<NPC, DemonicGorilla> gorillas;
private int tickCounter;
private List<WorldPoint> recentBoulders;
private List<PendingGorillaAttack> pendingAttacks;
private Map<Player, MemorizedPlayer> memorizedPlayers;
@Override
protected void startUp() throws Exception
{
tickCounter = 0;
gorillas = new HashMap<>();
recentBoulders = new ArrayList<>();
pendingAttacks = new ArrayList<>();
memorizedPlayers = new HashMap<>();
}
@Override
protected void shutDown() throws Exception
{
gorillas = null;
recentBoulders = null;
pendingAttacks = null;
memorizedPlayers = null;
}
@Override
public Overlay getOverlay()
{
return overlay;
}
private void clear()
{
recentBoulders.clear();
pendingAttacks.clear();
gorillas.clear();
memorizedPlayers.clear();
}
private void resetPlayers()
{
memorizedPlayers.clear();
for (Player player : client.getPlayers())
{
memorizedPlayers.put(player, new MemorizedPlayer(player));
}
}
public static boolean isNpcGorilla(int npcId)
{
return npcId == NpcID.DEMONIC_GORILLA ||
npcId == NpcID.DEMONIC_GORILLA_7145 ||
npcId == NpcID.DEMONIC_GORILLA_7146 ||
npcId == NpcID.DEMONIC_GORILLA_7147 ||
npcId == NpcID.DEMONIC_GORILLA_7148 ||
npcId == NpcID.DEMONIC_GORILLA_7149;
}
private void checkGorillaAttackStyleSwitch(DemonicGorilla gorilla,
final DemonicGorilla.AttackStyle... protectedStyles)
{
if (gorilla.getAttacksUntilSwitch() <= 0 ||
gorilla.getNextPosibleAttackStyles().size() == 0)
{
gorilla.setNextPosibleAttackStyles(Arrays
.stream(DemonicGorilla.ALL_REGULAR_ATTACK_STYLES)
.filter(x -> Arrays.stream(protectedStyles).noneMatch(y -> x == y))
.collect(Collectors.toList()));
gorilla.setAttacksUntilSwitch(DemonicGorilla.ATTACKS_PER_SWITCH);
gorilla.setChangedAttackStyleThisTick(true);
}
}
private DemonicGorilla.AttackStyle getProtectedStyle(Player player)
{
HeadIcon headIcon = player.getOverheadIcon();
if (headIcon == null)
{
return null;
}
switch (headIcon)
{
case MELEE:
return DemonicGorilla.AttackStyle.MELEE;
case RANGED:
return DemonicGorilla.AttackStyle.RANGED;
case MAGIC:
return DemonicGorilla.AttackStyle.MAGIC;
default:
return null;
}
}
private void onGorillaAttack(DemonicGorilla gorilla, final DemonicGorilla.AttackStyle attackStyle)
{
gorilla.setInitiatedCombat(true);
Player target = (Player)gorilla.getNpc().getInteracting();
DemonicGorilla.AttackStyle protectedStyle = null;
if (target != null)
{
protectedStyle = getProtectedStyle(target);
}
boolean correctPrayer =
target == null || // If player is out of memory, assume prayer was correct
attackStyle == protectedStyle;
if (attackStyle == DemonicGorilla.AttackStyle.BOULDER)
{
// The gorilla can't throw boulders when it's meleeing
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x != DemonicGorilla.AttackStyle.MELEE)
.collect(Collectors.toList()));
}
else
{
if (correctPrayer)
{
gorilla.setAttacksUntilSwitch(gorilla.getAttacksUntilSwitch() - 1);
}
else
{
// We're not sure if the attack will hit a 0 or not,
// so we don't know if we should decrease the counter or not,
// so we keep track of the attack here until the damage splat
// has appeared on the player.
int damagesOnTick = tickCounter;
if (attackStyle == DemonicGorilla.AttackStyle.MAGIC)
{
MemorizedPlayer mp = memorizedPlayers.get(target);
WorldArea lastPlayerArea = mp.getLastWorldArea();
if (lastPlayerArea != null)
{
int dist = gorilla.getNpc().getWorldArea().distanceTo(lastPlayerArea);
damagesOnTick += (dist + DemonicGorilla.PROJECTILE_MAGIC_DELAY) /
DemonicGorilla.PROJECTILE_MAGIC_SPEED;
}
}
else if (attackStyle == DemonicGorilla.AttackStyle.RANGED)
{
MemorizedPlayer mp = memorizedPlayers.get(target);
WorldArea lastPlayerArea = mp.getLastWorldArea();
if (lastPlayerArea != null)
{
int dist = gorilla.getNpc().getWorldArea().distanceTo(lastPlayerArea);
damagesOnTick += (dist + DemonicGorilla.PROJECTILE_RANGED_DELAY) /
DemonicGorilla.PROJECTILE_RANGED_SPEED;
}
}
pendingAttacks.add(new PendingGorillaAttack(gorilla, attackStyle, target, damagesOnTick));
}
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x == attackStyle)
.collect(Collectors.toList()));
if (gorilla.getNextPosibleAttackStyles().size() == 0)
{
// Sometimes the gorilla can switch attack style before it's supposed to
// if someone was fighting it earlier and then left, so we just
// reset the counter in that case.
gorilla.setNextPosibleAttackStyles(Arrays
.stream(DemonicGorilla.ALL_REGULAR_ATTACK_STYLES)
.filter(x -> x == attackStyle)
.collect(Collectors.toList()));
gorilla.setAttacksUntilSwitch(DemonicGorilla.ATTACKS_PER_SWITCH -
(correctPrayer ? 1 : 0));
}
}
checkGorillaAttackStyleSwitch(gorilla, protectedStyle);
gorilla.setNextAttackTick(tickCounter + DemonicGorilla.ATTACK_RATE);
}
private void checkGorillaAttacks()
{
for (DemonicGorilla gorilla : gorillas.values())
{
Player interacting = (Player)gorilla.getNpc().getInteracting();
MemorizedPlayer mp = memorizedPlayers.get(interacting);
if (gorilla.getLastTickInteracting() != null && interacting == null)
{
gorilla.setInitiatedCombat(false);
}
else if (mp != null && mp.getLastWorldArea() != null &&
!gorilla.isInitiatedCombat() &&
tickCounter < gorilla.getNextAttackTick() &&
gorilla.getNpc().getWorldArea().isInMeleeDistance(mp.getLastWorldArea()))
{
gorilla.setInitiatedCombat(true);
gorilla.setNextAttackTick(tickCounter + 1);
}
int animationId = gorilla.getNpc().getAnimation();
if (gorilla.isTakenDamageRecently() &&
tickCounter >= gorilla.getNextAttackTick() + 4)
{
// The gorilla was flinched, so its next attack gets delayed
gorilla.setNextAttackTick(tickCounter + DemonicGorilla.ATTACK_RATE / 2);
gorilla.setInitiatedCombat(true);
if (mp != null && mp.getLastWorldArea() != null &&
!gorilla.getNpc().getWorldArea().isInMeleeDistance(mp.getLastWorldArea()) &&
!gorilla.getNpc().getWorldArea().intersectsWith(mp.getLastWorldArea()))
{
// Gorillas stop meleeing when they get flinched
// and the target isn't in melee distance
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x != DemonicGorilla.AttackStyle.MELEE)
.collect(Collectors.toList()));
checkGorillaAttackStyleSwitch(gorilla, DemonicGorilla.AttackStyle.MELEE,
getProtectedStyle(interacting));
}
}
else if (animationId != gorilla.getLastTickAnimation())
{
if (animationId == AnimationID.DEMONIC_GORILLA_MELEE_ATTACK)
{
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.MELEE);
}
else if (animationId == AnimationID.DEMONIC_GORILLA_MAGIC_ATTACK)
{
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.MAGIC);
}
else if (animationId == AnimationID.DEMONIC_GORILLA_RANGED_ATTACK)
{
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.RANGED);
}
else if (animationId == AnimationID.DEMONIC_GORILLA_AOE_ATTACK && interacting != null)
{
// Note that AoE animation is the same as prayer switch animation
// so we need to check if the prayer was switched or not.
// It also does this animation when it spawns, so
// we need the interacting != null check.
if (gorilla.getOverheadIcon() == gorilla.getLastTickOverheadIcon())
{
// Confirmed, the gorilla used the AoE attack
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.BOULDER);
}
else
{
if (tickCounter >= gorilla.getNextAttackTick())
{
gorilla.setChangedPrayerThisTick(true);
// This part is more complicated because the gorilla may have
// used an attack, but the prayer switch animation takes
// priority over normal attack animations.
int projectileId = gorilla.getRecentProjectileId();
if (projectileId == ProjectileID.DEMONIC_GORILLA_MAGIC)
{
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.MAGIC);
}
else if (projectileId == ProjectileID.DEMONIC_GORILLA_RANGED)
{
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.RANGED);
}
else if (mp != null)
{
WorldArea lastPlayerArea = mp.getLastWorldArea();
if (lastPlayerArea != null &&
interacting != null && recentBoulders.stream()
.anyMatch(x -> x.distanceTo(lastPlayerArea) == 0))
{
// A boulder started falling on the gorillas target,
// so we assume it was the gorilla who shot it
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.BOULDER);
}
else if (mp.getRecentHitsplats().size() > 0)
{
// It wasn't any of the three other attacks,
// but the player took damage, so we assume
// it's a melee attack
onGorillaAttack(gorilla, DemonicGorilla.AttackStyle.MELEE);
}
}
}
// The next attack tick is always delayed if the
// gorilla switched prayer
gorilla.setNextAttackTick(tickCounter + DemonicGorilla.ATTACK_RATE);
gorilla.setChangedPrayerThisTick(true);
}
}
}
if (gorilla.getDisabledMeleeMovementForTicks() > 0)
{
gorilla.setDisabledMeleeMovementForTicks(gorilla.getDisabledMeleeMovementForTicks() - 1);
}
else if (gorilla.isInitiatedCombat() &&
gorilla.getNpc().getInteracting() != null &&
!gorilla.isChangedAttackStyleThisTick() &&
gorilla.getNextPosibleAttackStyles().size() >= 2 &&
gorilla.getNextPosibleAttackStyles().stream()
.anyMatch(x -> x == DemonicGorilla.AttackStyle.MELEE))
{
// If melee is a possibility, we can check if the gorilla
// is or isn't moving toward the player to determine if
// it is actually attempting to melee or not.
// We only run this check if the gorilla is in combat
// because otherwise it attempts to travel to melee
// distance before attacking its target.
if (mp != null && mp.getLastWorldArea() != null && gorilla.getLastWorldArea() != null)
{
WorldArea predictedNewArea = gorilla.getLastWorldArea().calculateNextTravellingPoint(
client, mp.getLastWorldArea(), true, x ->
{
// Gorillas can't normally walk through other gorillas
// or other players
final WorldArea area1 = new WorldArea(x, 1, 1);
return area1 != null &&
gorillas.values().stream().noneMatch(y ->
{
if (y == gorilla)
{
return false;
}
final WorldArea area2 =
y.getNpc().getIndex() < gorilla.getNpc().getIndex() ?
y.getNpc().getWorldArea() : y.getLastWorldArea();
return area2 != null && area1.intersectsWith(area2);
}) &&
memorizedPlayers.values().stream().noneMatch(y ->
{
final WorldArea area2 = y.getLastWorldArea();
return area2 != null && area1.intersectsWith(area2);
});
// There is a special case where if a player walked through
// a gorilla, or a player walked through another player,
// the tiles that were walked through becomes
// walkable, but I didn't feel like it's necessary to handle
// that special case as it should rarely happen.
});
if (predictedNewArea != null)
{
int distance = gorilla.getNpc().getWorldArea().distanceTo(mp.getLastWorldArea());
WorldPoint predictedMovement = predictedNewArea.toWorldPoint();
if (distance <= DemonicGorilla.MAX_ATTACK_RANGE &&
mp != null &&
mp.getLastWorldArea().hasLineOfSightTo(client, gorilla.getLastWorldArea()))
{
if (predictedMovement.distanceTo(gorilla.getLastWorldArea().toWorldPoint()) != 0)
{
if (predictedMovement.distanceTo(gorilla.getNpc().getWorldLocation()) == 0)
{
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x == DemonicGorilla.AttackStyle.MELEE)
.collect(Collectors.toList()));
}
else
{
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x != DemonicGorilla.AttackStyle.MELEE)
.collect(Collectors.toList()));
}
}
else if (tickCounter >= gorilla.getNextAttackTick() &&
gorilla.getRecentProjectileId() == -1 &&
recentBoulders.stream().noneMatch(x -> x.distanceTo(mp.getLastWorldArea()) == 0))
{
gorilla.setNextPosibleAttackStyles(gorilla
.getNextPosibleAttackStyles()
.stream()
.filter(x -> x == DemonicGorilla.AttackStyle.MELEE)
.collect(Collectors.toList()));
}
}
}
}
}
if (gorilla.isTakenDamageRecently())
{
gorilla.setInitiatedCombat(true);
}
if (gorilla.getOverheadIcon() != gorilla.getLastTickOverheadIcon())
{
if (gorilla.isChangedAttackStyleLastTick() ||
gorilla.isChangedAttackStyleThisTick())
{
// Apparently if it changes attack style and changes
// prayer on the same tick or 1 tick apart, it won't
// be able to move for the next 2 ticks if it attempts
// to melee
gorilla.setDisabledMeleeMovementForTicks(2);
}
else
{
// If it didn't change attack style lately,
// it's only for the next 1 tick
gorilla.setDisabledMeleeMovementForTicks(1);
}
}
gorilla.setLastTickAnimation(gorilla.getNpc().getAnimation());
gorilla.setLastWorldArea(gorilla.getNpc().getWorldArea());
gorilla.setLastTickInteracting(gorilla.getNpc().getInteracting());
gorilla.setTakenDamageRecently(false);
gorilla.setChangedPrayerThisTick(false);
gorilla.setChangedAttackStyleLastTick(gorilla.isChangedAttackStyleThisTick());
gorilla.setChangedAttackStyleThisTick(false);
gorilla.setLastTickOverheadIcon(gorilla.getOverheadIcon());
gorilla.setRecentProjectileId(-1);
}
}
@Subscribe
public void onProjectile(ProjectileMoved event)
{
Projectile projectile = event.getProjectile();
int projectileId = projectile.getId();
if (projectileId != ProjectileID.DEMONIC_GORILLA_RANGED &&
projectileId != ProjectileID.DEMONIC_GORILLA_MAGIC &&
projectileId != ProjectileID.DEMONIC_GORILLA_BOULDER)
{
return;
}
// The event fires once before the projectile starts moving,
// and we only want to check each projectile once
if (client.getGameCycle() >= projectile.getStartMovementCycle())
{
return;
}
if (projectileId == ProjectileID.DEMONIC_GORILLA_BOULDER)
{
recentBoulders.add(WorldPoint.fromLocal(client, event.getPosition()));
}
else if (projectileId == ProjectileID.DEMONIC_GORILLA_MAGIC ||
projectileId == ProjectileID.DEMONIC_GORILLA_RANGED)
{
WorldPoint projectileSourcePosition = WorldPoint.fromLocal(
client, projectile.getX1(), projectile.getY1(), client.getPlane());
for (DemonicGorilla gorilla : gorillas.values())
{
if (gorilla.getNpc().getWorldLocation().distanceTo(projectileSourcePosition) == 0)
{
gorilla.setRecentProjectileId(projectile.getId());
}
}
}
}
private void checkPendingAttacks()
{
Iterator<PendingGorillaAttack> it = pendingAttacks.iterator();
while (it.hasNext())
{
PendingGorillaAttack attack = it.next();
if (tickCounter >= attack.getFinishesOnTick())
{
boolean shouldDecreaseCounter = false;
DemonicGorilla gorilla = attack.getAttacker();
MemorizedPlayer target = memorizedPlayers.get(attack.getTarget());
if (target == null)
{
// Player went out of memory, so assume the hit was a 0
shouldDecreaseCounter = true;
}
else if (target.getRecentHitsplats().size() == 0)
{
// No hitsplats was applied. This may happen in some cases
// where the player was out of memory while the
// projectile was travelling. So we assume the hit was a 0.
shouldDecreaseCounter = true;
}
else if (target.getRecentHitsplats().stream()
.anyMatch(x -> x.getHitsplatType() == Hitsplat.HitsplatType.BLOCK))
{
// A blue hitsplat appeared, so we assume the gorilla hit a 0
shouldDecreaseCounter = true;
}
if (shouldDecreaseCounter)
{
gorilla.setAttacksUntilSwitch(gorilla.getAttacksUntilSwitch() - 1);
checkGorillaAttackStyleSwitch(gorilla);
}
it.remove();
}
}
}
private void updatePlayers()
{
for (MemorizedPlayer mp : memorizedPlayers.values())
{
mp.setLastWorldArea(mp.getPlayer().getWorldArea());
mp.getRecentHitsplats().clear();
}
}
@Subscribe
public void onHitsplat(HitsplatApplied event)
{
if (gorillas.isEmpty())
{
return;
}
if (event.getActor() instanceof Player)
{
Player player = (Player)event.getActor();
MemorizedPlayer mp = memorizedPlayers.get(player);
if (mp != null)
{
mp.getRecentHitsplats().add(event.getHitsplat());
}
}
else if (event.getActor() instanceof NPC)
{
DemonicGorilla gorilla = gorillas.get(event.getActor());
Hitsplat.HitsplatType hitsplatType = event.getHitsplat().getHitsplatType();
if (gorilla != null && (hitsplatType == Hitsplat.HitsplatType.BLOCK ||
hitsplatType == Hitsplat.HitsplatType.DAMAGE))
{
gorilla.setTakenDamageRecently(true);
}
}
}
@Subscribe
public void onGameState(GameStateChanged event)
{
GameState gs = event.getGameState();
if (gs == GameState.LOGGING_IN ||
gs == GameState.CONNECTION_LOST ||
gs == GameState.HOPPING)
{
clear();
}
}
@Subscribe
public void onPlayerSpawned(PlayerSpawned event)
{
if (gorillas.isEmpty())
{
return;
}
Player player = event.getPlayer();
memorizedPlayers.put(player, new MemorizedPlayer(player));
}
@Subscribe
public void onPlayerDespawned(PlayerDespawned event)
{
if (gorillas.isEmpty())
{
return;
}
memorizedPlayers.remove(event.getPlayer());
}
@Subscribe
public void onNpcSpawned(NpcSpawned event)
{
NPC npc = event.getNpc();
if (isNpcGorilla(npc.getId()))
{
if (gorillas.isEmpty())
{
// Players are not kept track of when there are no gorillas in
// memory, so we need to add the players that were already in memory.
resetPlayers();
}
gorillas.put(npc, new DemonicGorilla(npc));
}
}
@Subscribe
public void onNpcDespawned(NpcDespawned event)
{
if (gorillas.remove(event.getNpc()) != null && gorillas.isEmpty())
{
clear();
}
}
@Subscribe
public void onGameTick(GameTick event)
{
checkGorillaAttacks();
checkPendingAttacks();
updatePlayers();
recentBoulders.clear();
tickCounter++;
}
} |
package de.craften.craftenlauncher.logic.vm;
import java.awt.image.BufferedImage;
import java.util.Observable;
/**
* "ViewModel" class which offers information around
* the minecraft skin.
* SkinVM notifies all gui clases which handles skin presentation.
* Offers Information about the download status and the downloaded skin
* image file.
*
* @author redbeard
*/
public class SkinVM extends Observable{
private BufferedImage mSkin;
/**
* Offers information about the download status
* @return True if the download is completed.
*/
public boolean wasSkinDownloaded() {
return ( mSkin != null );
}
/**
* Method to set the downloaded skin image.
*
* @param skin has to be not null.
*/
public void setSkinDownloaded(BufferedImage skin) {
this.mSkin = skin;
this.setChanged();
this.notifyObservers();
}
/**
* Returns the downloaded skin image.
*
* @return
*/
public BufferedImage getSkin() {
return mSkin;
}
} |
package de.dhbw.humbuch.viewmodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.google.inject.Inject;
import de.davherrmann.mvvm.ActionHandler;
import de.davherrmann.mvvm.BasicState;
import de.davherrmann.mvvm.State;
import de.davherrmann.mvvm.annotations.AfterVMBinding;
import de.davherrmann.mvvm.annotations.HandlesAction;
import de.davherrmann.mvvm.annotations.ProvidesState;
import de.dhbw.humbuch.model.DAO;
import de.dhbw.humbuch.model.DAO.FireUpdateEvent;
import de.dhbw.humbuch.model.entity.BorrowedMaterial;
import de.dhbw.humbuch.model.entity.Grade;
import de.dhbw.humbuch.model.entity.SchoolYear;
import de.dhbw.humbuch.model.entity.Student;
import de.dhbw.humbuch.model.entity.TeachingMaterial;
public class LendingViewModel {
public interface GenerateMaterialListGrades extends ActionHandler {};
public interface SetBorrowedMaterialsReceived extends ActionHandler {};
public interface DoManualLending extends ActionHandler {};
public interface StudentsWithUnreceivedBorrowedMaterials extends State<Map<Grade, Map<Student, List<BorrowedMaterial>>>> {};
public interface MaterialListGrades extends State<Map<Grade, Map<TeachingMaterial, Integer>>> {};
public interface TeachingMaterials extends State<Collection<TeachingMaterial>> {};
@ProvidesState(StudentsWithUnreceivedBorrowedMaterials.class)
public State<Map<Grade, Map<Student, List<BorrowedMaterial>>>> studentsWithUnreceivedBorrowedMaterials = new BasicState<>(Map.class);
@ProvidesState(MaterialListGrades.class)
public State<Map<Grade, Map<TeachingMaterial, Integer>>> materialListGrades = new BasicState<>(Map.class);
@ProvidesState(TeachingMaterials.class)
public State<Collection<TeachingMaterial>> teachingMaterials = new BasicState<>(Collection.class);
private DAO<Grade> daoGrade;
private DAO<Student> daoStudent;
private DAO<TeachingMaterial> daoTeachingMaterial;
private DAO<BorrowedMaterial> daoBorrowedMaterial;
private DAO<SchoolYear> daoSchoolYear;
private SchoolYear recentlyActiveSchoolYear;
@Inject
public LendingViewModel(DAO<Student> daoStudent, DAO<TeachingMaterial> daoTeachingMaterial, DAO<Grade> daoGrade,
DAO<BorrowedMaterial> daoBorrowedMaterial, DAO<SchoolYear> daoSchoolYear) {
this.daoStudent = daoStudent;
this.daoTeachingMaterial = daoTeachingMaterial;
this.daoGrade = daoGrade;
this.daoBorrowedMaterial = daoBorrowedMaterial;
this.daoSchoolYear = daoSchoolYear;
}
@AfterVMBinding
public void refresh() {
updateSchoolYear();
updateTeachingMaterials();
updateAllStudentsBorrowedMaterials();
}
@HandlesAction(GenerateMaterialListGrades.class)
public void generateMaterialListGrades(Set<Grade> selectedGrades) {
Map<Grade, Map<TeachingMaterial, Integer>> materialList = new TreeMap<Grade, Map<TeachingMaterial, Integer>>();
for (Grade grade : selectedGrades) {
Map<TeachingMaterial, Integer> gradeMap = new TreeMap<TeachingMaterial, Integer>();
for(Student student : daoStudent.findAllWithCriteria(Restrictions.eq("leavingSchool", false), Restrictions.eq("grade", grade))) {
for(BorrowedMaterial borrowedMaterial : student.getUnreceivedBorrowedList()) {
TeachingMaterial teachingMaterial = borrowedMaterial.getTeachingMaterial();
if(gradeMap.containsKey(teachingMaterial)) {
gradeMap.put(teachingMaterial, gradeMap.get(teachingMaterial) + 1);
} else {
gradeMap.put(teachingMaterial, 1);
}
}
}
materialList.put(grade, gradeMap);
}
materialListGrades.set(materialList);
}
@HandlesAction(SetBorrowedMaterialsReceived.class)
public void setBorrowedMaterialsReceived(Collection<BorrowedMaterial> borrowedMaterials) {
for (BorrowedMaterial borrowedMaterial : borrowedMaterials) {
borrowedMaterial.setReceived(true);
daoBorrowedMaterial.update(borrowedMaterial, FireUpdateEvent.NO);
}
daoBorrowedMaterial.fireUpdateEvent();
updateAllStudentsBorrowedMaterials();
}
@HandlesAction(DoManualLending.class)
public void doManualLending(Student student, TeachingMaterial toLend, Date borrowUntil) {
persistBorrowedMaterial(student, toLend, borrowUntil);
updateAllStudentsBorrowedMaterials();
}
private void updateAllStudentsBorrowedMaterials() {
for(Student student : daoStudent.findAllWithCriteria(Restrictions.eq("leavingSchool", false))) {
persistBorrowedMaterials(student, getNewTeachingMaterials(student));
}
updateUnreceivedBorrowedMaterialsState();
}
private void updateTeachingMaterials() {
teachingMaterials.set(daoTeachingMaterial.findAll());
}
private void updateSchoolYear() {
recentlyActiveSchoolYear = daoSchoolYear.findSingleWithCriteria(
Order.desc("toDate"),
Restrictions.le("fromDate", new Date()));
}
private void updateUnreceivedBorrowedMaterialsState() {
Map<Grade, Map<Student, List<BorrowedMaterial>>> unreceivedMap = new TreeMap<Grade, Map<Student, List<BorrowedMaterial>>>();
for (Grade grade : daoGrade.findAll()) {
Map<Student, List<BorrowedMaterial>> studentsWithUnreceivedBorrowedMaterials = new TreeMap<Student, List<BorrowedMaterial>>();
for (Student student : grade.getStudents()) {
if(student.hasUnreceivedBorrowedMaterials()) {
List<BorrowedMaterial> unreceivedBorrowedList = student.getUnreceivedBorrowedList();
Collections.sort(unreceivedBorrowedList);
studentsWithUnreceivedBorrowedMaterials.put(student, unreceivedBorrowedList);
}
}
if(!studentsWithUnreceivedBorrowedMaterials.isEmpty()) {
unreceivedMap.put(grade, studentsWithUnreceivedBorrowedMaterials);
}
}
studentsWithUnreceivedBorrowedMaterials.set(unreceivedMap);
}
private List<TeachingMaterial> getNewTeachingMaterials(Student student) {
Collection<TeachingMaterial> teachingMerterials = daoTeachingMaterial.findAllWithCriteria(
Restrictions.and(
Restrictions.le("fromGrade", student.getGrade().getGrade())
, Restrictions.ge("toGrade", student.getGrade().getGrade())
, Restrictions.le("validFrom", new Date())
, Restrictions.le("fromTerm", recentlyActiveSchoolYear.getRecentlyActiveTerm())
, Restrictions.or(
Restrictions.ge("validUntil", new Date())
, Restrictions.isNull("validUntil"))
));
List<TeachingMaterial> owningTeachingMaterials = getOwningTeachingMaterials(student);
List<TeachingMaterial> toLend = new ArrayList<TeachingMaterial>();
for(TeachingMaterial teachingMaterial : teachingMerterials) {
if(student.getProfile().containsAll(teachingMaterial.getProfile())
&& !owningTeachingMaterials.contains(teachingMaterial)) {
toLend.add(teachingMaterial);
}
}
return toLend;
}
private void persistBorrowedMaterials(Student student, List<TeachingMaterial> teachingMaterials) {
for (TeachingMaterial teachingMaterial : teachingMaterials) {
BorrowedMaterial borrowedMaterial = new BorrowedMaterial.Builder(student, teachingMaterial, new Date()).build();
daoBorrowedMaterial.insert(borrowedMaterial, FireUpdateEvent.NO);
}
if(!teachingMaterials.isEmpty()) {
daoBorrowedMaterial.fireUpdateEvent();
}
}
private void persistBorrowedMaterial(Student student, TeachingMaterial teachingMaterial, Date borrowUntil) {
BorrowedMaterial borrowedMaterial = new BorrowedMaterial.Builder(student, teachingMaterial, new Date()).borrowUntil(borrowUntil).received(true).build();
daoBorrowedMaterial.insert(borrowedMaterial);
}
private List<TeachingMaterial> getOwningTeachingMaterials(Student student) {
List<TeachingMaterial> owning = new ArrayList<TeachingMaterial>();
for(BorrowedMaterial borrowedMaterial : student.getBorrowedList()) {
owning.add(borrowedMaterial.getTeachingMaterial());
}
return owning;
}
} |
package de.iani.cubequest.conditions;
public enum ConditionType {
NEGATED(NegatedQuestCondition.class),
RENAMED(RenamedCondition.class),
MINIMUM_QUEST_LEVEL(MinimumQuestLevelCondition.class),
HAVE_QUEST_STATUS(HaveQuestStatusCondition.class),
SERVER_FLAG(ServerFlagCondition.class),
BE_IN_AREA(BeInAreaCondition.class);
public final Class<? extends QuestCondition> concreteClass;
public static ConditionType match(String s) {
String u = s.toUpperCase();
String l = s.toLowerCase();
try {
return valueOf(u);
} catch (IllegalArgumentException e) {
// ignore
}
if (l.startsWith("min") && l.contains("level")) {
return MINIMUM_QUEST_LEVEL;
}
if (l.contains("status")) {
return HAVE_QUEST_STATUS;
}
if (l.contains("area")) {
return BE_IN_AREA;
}
return null;
}
private ConditionType(Class<? extends QuestCondition> concreteClass) {
this.concreteClass = concreteClass;
}
} |
package de.retest.recheck.review.ignore.io;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import org.apache.commons.lang3.tuple.Pair;
import de.retest.recheck.ignore.JSFilterImpl;
import de.retest.recheck.review.ignore.AttributeFilter;
import de.retest.recheck.review.ignore.AttributeFilter.AttributeFilterLoader;
import de.retest.recheck.review.ignore.AttributeRegexFilter;
import de.retest.recheck.review.ignore.AttributeRegexFilter.AttributeRegexFilterLoader;
import de.retest.recheck.review.ignore.ElementAttributeFilter;
import de.retest.recheck.review.ignore.ElementAttributeFilter.ElementAttributeFilterLoader;
import de.retest.recheck.review.ignore.ElementAttributeRegexFilter;
import de.retest.recheck.review.ignore.ElementAttributeRegexFilter.ElementAttributeRegexFilterLoader;
import de.retest.recheck.review.ignore.ElementFilter;
import de.retest.recheck.review.ignore.ElementFilter.ElementFilterLoader;
import de.retest.recheck.review.ignore.FilterPreserveLineLoader;
import de.retest.recheck.review.ignore.FilterPreserveLineLoader.FilterPreserveLine;
import de.retest.recheck.review.ignore.JSFilterLoader;
import de.retest.recheck.review.ignore.MaxPixelDiffShouldIgnore;
import de.retest.recheck.review.ignore.MaxPixelDiffShouldIgnore.MaxPixelDiffShouldIgnoreLoader;
import de.retest.recheck.review.ignore.matcher.ElementIdMatcher;
import de.retest.recheck.review.ignore.matcher.ElementIdMatcher.ElementIdMatcherLoader;
import de.retest.recheck.review.ignore.matcher.ElementRetestIdMatcher;
import de.retest.recheck.review.ignore.matcher.ElementRetestIdMatcher.ElementRetestIdMatcherLoader;
import de.retest.recheck.review.ignore.matcher.ElementTypeMatcher;
import de.retest.recheck.review.ignore.matcher.ElementTypeMatcher.ElementTypeMatcherLoader;
import de.retest.recheck.review.ignore.matcher.ElementXPathMatcher;
import de.retest.recheck.review.ignore.matcher.ElementXPathMatcher.ElementXpathMatcherLoader;
public class Loaders {
private static final List<Pair<Class<?>, Loader<?>>> registeredLoaders = registerLoaders();
private Loaders() {}
private static List<Pair<Class<?>, Loader<?>>> registerLoaders() {
final List<Pair<Class<?>, Loader<?>>> pairs = new ArrayList<>();
pairs.add( Pair.of( ElementIdMatcher.class, new ElementIdMatcherLoader() ) );
pairs.add( Pair.of( ElementRetestIdMatcher.class, new ElementRetestIdMatcherLoader() ) );
pairs.add( Pair.of( ElementXPathMatcher.class, new ElementXpathMatcherLoader() ) );
pairs.add( Pair.of( ElementTypeMatcher.class, new ElementTypeMatcherLoader() ) );
pairs.add( Pair.of( ElementAttributeFilter.class, new ElementAttributeFilterLoader() ) );
pairs.add( Pair.of( ElementAttributeRegexFilter.class, new ElementAttributeRegexFilterLoader() ) );
pairs.add( Pair.of( AttributeFilter.class, new AttributeFilterLoader() ) );
pairs.add( Pair.of( AttributeRegexFilter.class, new AttributeRegexFilterLoader() ) );
pairs.add( Pair.of( ElementFilter.class, new ElementFilterLoader() ) );
pairs.add( Pair.of( MaxPixelDiffShouldIgnore.class, new MaxPixelDiffShouldIgnoreLoader() ) );
pairs.add( Pair.of( FilterPreserveLine.class, new FilterPreserveLineLoader() ) );
pairs.add( Pair.of( JSFilterImpl.class, new JSFilterLoader() ) );
// This is error handling and should always be last
pairs.add( Pair.of( FilterPreserveLine.class, new ErrorHandlingLoader() ) );
return pairs;
}
public static <T> Loader<T> get( final Class<? extends T> clazz ) {
return (Loader<T>) registeredLoaders.stream()
.filter( pair -> clazz.isAssignableFrom( pair.getLeft() ) )
.findFirst()
.map( Pair::getRight )
.orElseThrow( () -> new UnsupportedOperationException( "No loader registered for " + clazz ) );
}
public static <T> Loader<T> get( final String line ) {
return (Loader<T>) registeredLoaders.stream()
.filter( pair -> pair.getRight().canLoad( line ) )
.findFirst()
.map( Pair::getRight )
.orElseThrow( () -> new UnsupportedOperationException( "No loader registered for " + line ) );
}
public static Stream<String> save( final Stream<?> objects ) {
return objects.map( Loaders::save );
}
private static <T> String save( final T object ) {
final Loader<T> loader = (Loader<T>) get( object.getClass() );
return loader.save( object );
}
public static Stream<?> load( final Stream<String> lines ) {
return lines.map( Loaders::load ).filter( Objects::nonNull );
}
private static <T> T load( final String line ) {
return (T) registeredLoaders.stream()
.map( Pair::getRight )
.filter( loader -> loader.canLoad( line ) )
.findFirst()
.map( loader -> loader.load( line ) )
.orElse( null );
}
} |
package com.neverwinterdp.scribengin.dataflow.tracking;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import com.neverwinterdp.registry.RegistryConfig;
import com.neverwinterdp.scribengin.dataflow.Dataflow;
import com.neverwinterdp.scribengin.dataflow.DataflowDescriptor;
import com.neverwinterdp.scribengin.dataflow.DataflowSubmitter;
import com.neverwinterdp.scribengin.shell.ScribenginShell;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.vm.VMConfig;
import com.neverwinterdp.vm.client.VMClient;
import com.neverwinterdp.vm.client.VMSubmitter;
import com.neverwinterdp.vm.client.shell.CommandInput;
import com.neverwinterdp.vm.client.shell.Shell;
import com.neverwinterdp.vm.client.shell.SubCommand;
public class TrackingLauncher extends SubCommand {
@Parameter(names = "--local-app-home", required = true, description = "Generator num of chunk")
private String localAppHome = null;
@Parameter(names = "--dfs-app-home", description = "Generator num of chunk")
private String dfsAppHome = "/applications/tracking-sample";
@Parameter(names = "--tracking-report-path", description = "Generator num of chunk")
private String trackingReportPath = "/applications/tracking-sample/reports";
@Parameter(names = "--generator-num-of-chunk", description = "Generator num of chunk")
private int generatorNumOfChunks = 10;
@Parameter(names = "--generator-num-of-message-per-chunk", description = "Generator num of message per chunk")
private int generatorNumOfMessagePerChunk = 1000;
@Parameter(names = "--generator-num-of-writer", description = "")
private int generatorNumOfWriter = 3;
@Parameter(names = "--generator-break-in-period", description = "")
private long generatorBreakInPeriod = 50;
@Parameter(names = "--generator-kafka-num-of-partition", description = "")
private int generatorKafkaNumOfPartition = 8;
@Parameter(names = "--generator-kafka-num-of-replication", description = "")
private int generatorKafkaNumOfReplication = 2;
@Parameter(names = "--dataflow-id", description = "")
private String dataflowId = "tracking";
@Parameter(names = "--dataflow-num-of-worker", description = "")
private int numOfWorker = 8;
@Parameter(names = "--dataflow-num-of-executor-per-worker", description = "")
private int numOfExecutorPerWorker = 2;
@Parameter(names = "--validator-num-of-reader", description = "")
private int validatorNumOfReader = 3;
@Parameter(names = "--validator-max-run-time", description = "")
private int validatorMaxRuntime = -1;
public TrackingLauncher(String[] args) throws Exception {
new JCommander(this, args);
}
@Override
public void execute(Shell s, CommandInput cmdInput) throws Exception {
ScribenginShell shell = (ScribenginShell) s;
VMClient vmClient = shell.getVMClient();
vmClient.uploadApp(localAppHome, dfsAppHome);
TrackingDataflowBuilder dflBuilder = new TrackingDataflowBuilder(dataflowId);
dflBuilder.
setNumOfWorker(numOfWorker).
setNumOfExecutorPerWorker(numOfExecutorPerWorker);
dflBuilder.getTrackingConfig().setReportPath(trackingReportPath);
dflBuilder.getTrackingConfig().setGeneratorNumOfWriter(generatorNumOfWriter);
dflBuilder.getTrackingConfig().setGeneratorBreakInPeriod(generatorBreakInPeriod);
dflBuilder.getTrackingConfig().setNumOfChunk(generatorNumOfChunks);
dflBuilder.getTrackingConfig().setNumOfMessagePerChunk(generatorNumOfMessagePerChunk);
dflBuilder.getTrackingConfig().setKafkaZKConnects(registryConfig.getConnect());
dflBuilder.getTrackingConfig().setKafkaNumOfPartition(generatorKafkaNumOfPartition);
dflBuilder.getTrackingConfig().setKafkaNumOfReplication(generatorKafkaNumOfReplication);
if(validatorMaxRuntime < 1) {
validatorMaxRuntime = 180000 + (generatorNumOfMessagePerChunk * generatorNumOfChunks)/3;
}
dflBuilder.getTrackingConfig().setValidatorMaxRuntime(validatorMaxRuntime);
dflBuilder.getTrackingConfig().setValidatorNumOfReader(validatorNumOfReader);
VMConfig vmGeneratorConfig = dflBuilder.buildVMTMGeneratorKafka();
new VMSubmitter(vmClient, dfsAppHome, vmGeneratorConfig).submit().waitForRunning(30000);
Dataflow<TrackingMessage, TrackingMessage> dfl = dflBuilder.buildDataflow();
DataflowDescriptor dflDescriptor = dfl.buildDataflowDescriptor();
System.out.println(JSONSerializer.INSTANCE.toString(dflDescriptor));
new DataflowSubmitter(shell.getScribenginClient(), dfl).submit().waitForRunning(60000);
VMConfig vmValidatorConfig = dflBuilder.buildKafkaVMTMValidator();
new VMSubmitter(vmClient, dfsAppHome, vmValidatorConfig).submit().waitForRunning(30000);
}
@Override
public String getDescription() { return "Tracking app launcher"; }
} |
package us.nineworlds.serenity.ui.browser.music.tracks;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.google.analytics.tracking.android.EasyTracker;
import com.jess.ui.TwoWayGridView;
import us.nineworlds.serenity.R;
import us.nineworlds.serenity.core.model.impl.AudioTrackContentInfo;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author dcarver
*
*/
public class MusicTracksActivity extends Activity implements
OnCompletionListener {
private String key;
private boolean restarted_state = false;
private MediaPlayer mediaPlayer;
private ImageButton playBtn;
private ImageButton nextBtn;
private ImageButton prevBtn;
private SeekBar seekBar;
private TextView currentTime, durationTime;
public static int currentPlayingItem = 0;
private MediaController mediaController;
private static final int MILLISECONDS_PER_MINUTE = 60000;
private static final int MILLISECONDS_PER_HOUR = 3600000;
private Handler progressHandler = new Handler();
private Runnable playbackRunnable = new Runnable() {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
currentTime.setText(formatDuration(mediaPlayer
.getCurrentPosition()));
durationTime.setText(formatDuration(mediaPlayer
.getDuration()));
setProgress();
}
} catch (IllegalStateException ex) {
}
progressHandler.postDelayed(this, 1000);
}
protected String formatDuration(long duration) {
long tempdur = duration;
long hours = TimeUnit.MILLISECONDS.toHours(duration);
tempdur = tempdur - (hours * MILLISECONDS_PER_HOUR);
long minutes = tempdur / MILLISECONDS_PER_MINUTE;
tempdur = tempdur - (minutes * MILLISECONDS_PER_MINUTE);
long seconds = tempdur / 1000;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
private void setProgress() {
if (mediaPlayer == null) {
return;
}
long position = 0;
try {
position = mediaPlayer.getCurrentPosition();
long duration = mediaPlayer.getDuration();
if (seekBar != null) {
if (duration > 0) {
long pos = 1000L * position / duration;
seekBar.setProgress((int) pos);
}
int percent = 0;
seekBar.setSecondaryProgress(percent * 10);
}
} catch (IllegalStateException ex) {
Log.i(getClass().getName(),
"Player has been either released or in an error state.");
}
}
};
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
key = getIntent().getExtras().getString("key");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
setContentView(R.layout.activity_music_track);
init();
}
protected void init() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
playBtn = (ImageButton) findViewById(R.id.audioPause);
playBtn.setOnClickListener(new PlayButtonListener(mediaPlayer));
seekBar = (SeekBar) findViewById(R.id.mediacontroller_seekbar);
nextBtn = (ImageButton) findViewById(R.id.audioSkipForward);
nextBtn.setOnClickListener(new SkipForwardOnClickListener(mediaPlayer));
prevBtn = (ImageButton) findViewById(R.id.audioSkipBack);
prevBtn.setOnClickListener(new SkipBackOnClickListener(mediaPlayer));
currentTime = (TextView) findViewById(R.id.mediacontroller_time_current);
durationTime = (TextView) findViewById(R.id.mediacontroller_time_total);
progressHandler.postDelayed(playbackRunnable, 1000);
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekBar.setOnSeekBarChangeListener(new AudioTrackPlaybackListener(
mediaPlayer, am, currentTime, durationTime, seekBar));
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
if (restarted_state == false) {
setupMusicAdapters();
}
restarted_state = false;
}
protected void setupMusicAdapters() {
ListView lview = (ListView) findViewById(R.id.audioTracksListview);
lview.setAdapter(new TracksAdapter(this, key));
lview.setOnItemSelectedListener(new TracksOnItemSelectedListener());
lview.setOnItemClickListener(new AudioTrackItemClickListener(
mediaPlayer));
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#finish()
*/
@Override
public void finish() {
super.finish();
if (mediaPlayer != null) {
mediaPlayer.release();
}
progressHandler.removeCallbacks(playbackRunnable);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaPlayer != null) {
try {
if (keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_P) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD ||
keyCode == KeyEvent.KEYCODE_F) {
nextBtn.performClick();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_REWIND ||
keyCode == KeyEvent.KEYCODE_R) {
prevBtn.performClick();
return true;
}
} catch (IllegalStateException ex) {
Toast.makeText(this, "Media Player in illegal state.",
Toast.LENGTH_LONG).show();
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onCompletion(MediaPlayer mp) {
ListView lview = (ListView) findViewById(R.id.audioTracksListview);
int count = lview.getCount();
int nextItem = 0;
if (currentPlayingItem < count) {
nextItem = currentPlayingItem + 1;
} else {
return;
}
if (nextItem >= count) {
return;
}
lview.setSelection(nextItem);
AudioTrackContentInfo track = (AudioTrackContentInfo) lview
.getItemAtPosition(nextItem);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(track.getDirectPlayUrl());
mediaPlayer.prepare();
mediaPlayer.start();
currentPlayingItem = nextItem;
} catch (IllegalStateException ex) {
} catch (IOException ex) {
}
}
} |
package edu.harvard.iq.dataverse;
import javax.persistence.Column;
import javax.persistence.Version;
/**
*
* @author skraffmiller
*/
public class DatasetTopicClass {
private DatasetVersion datasetVersion;
public DatasetVersion getDatasetVersion() {
return datasetVersion;
}
public void setDatasetVersion(DatasetVersion metadata) {
this.datasetVersion = metadata;
}
private int displayOrder;
public int getDisplayOrder() {
return this.displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
private DatasetFieldValue value;
public DatasetFieldValue getValue() {
return this.value;
}
public void setValue(DatasetFieldValue value) {
this.value = value;
}
private Long version;
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
this.version = version;
}
private DatasetFieldValue vocab;
public DatasetFieldValue getVocab() {
return this.vocab;
}
public void setVocab(DatasetFieldValue vocab) {
this.vocab = vocab;
}
private DatasetFieldValue vocabURI;
public DatasetFieldValue getVocabURI() {
return this.vocabURI;
}
public void setVocabURI(DatasetFieldValue vocabURI) {
this.vocabURI = vocabURI;
}
public boolean isEmpty() {/*
return ((value==null || value.getValue().trim().equals(""))
&& (vocab==null || vocab.getValue().trim().equals(""))
&& (vocabURI==null || vocabURI.getValue().trim().equals("")));*/
return false;
}
} |
package edu.jhu.nlp.data.simple;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import edu.jhu.hlt.concrete.Communication;
import edu.jhu.nlp.data.concrete.ConcreteWriter;
import edu.jhu.nlp.data.conll.CoNLL08Sentence;
import edu.jhu.nlp.data.conll.CoNLL08Writer;
import edu.jhu.nlp.data.conll.CoNLL09Sentence;
import edu.jhu.nlp.data.conll.CoNLL09Writer;
import edu.jhu.nlp.data.conll.CoNLLXSentence;
import edu.jhu.nlp.data.conll.CoNLLXWriter;
import edu.jhu.nlp.data.semeval.SemEval2010Sentence;
import edu.jhu.nlp.data.semeval.SemEval2010Writer;
import edu.jhu.nlp.data.simple.AnnoSentenceReader.DatasetType;
import edu.jhu.nlp.features.TemplateLanguage.AT;
public class AnnoSentenceWriter {
public static class AnnoSentenceWriterPrm {
public String name = "";
}
private static final Logger log = Logger.getLogger(AnnoSentenceWriter.class);
private AnnoSentenceWriterPrm prm;
public AnnoSentenceWriter(AnnoSentenceWriterPrm prm) {
this.prm = prm;
}
public void write(File out, DatasetType type, AnnoSentenceCollection sents) throws IOException {
log.info("Writing sentences for " + prm.name + " data of type " + type + " to " + out);
if (type == DatasetType.CONLL_2009) {
CoNLL09Writer cw = new CoNLL09Writer(out);
for (AnnoSentence sent : sents) {
CoNLL09Sentence conllSent = CoNLL09Sentence.fromAnnoSentence(sent);
cw.write(conllSent);
}
cw.close();
} else if (type == DatasetType.CONLL_2008) {
CoNLL08Writer cw = new CoNLL08Writer(out);
for (AnnoSentence sent : sents) {
CoNLL08Sentence conllSent = CoNLL08Sentence.fromAnnoSentence(sent);
cw.write(conllSent);
}
cw.close();
} else if (type == DatasetType.CONLL_X) {
CoNLLXWriter cw = new CoNLLXWriter(out);
for (AnnoSentence sent : sents) {
CoNLLXSentence conllSent = CoNLLXSentence.fromAnnoSentence(sent);
cw.write(conllSent);
}
cw.close();
} else if (type == DatasetType.SEMEVAL_2010) {
SemEval2010Writer sw = new SemEval2010Writer(out);
try {
int i = 0;
for (AnnoSentence sent : sents) {
// Write one SemEval-2010 sentence for each pair of entities.
if (!sent.hasAt(AT.NE_PAIRS)) {
throw new RuntimeException("Sentence missing required annotation: " + AT.NE_PAIRS);
}
if (sent.getNePairs().size() > 0) {
if (!sent.hasAt(AT.REL_LABELS)) {
//throw new RuntimeException("Sentence missing required annotation: " + AT.REL_LABELS);
log.warn("Sentence missing required annotation: " + AT.REL_LABELS);
} else {
List<SemEval2010Sentence> seSents = SemEval2010Sentence.fromAnnoSentence(sent, i++);
for (SemEval2010Sentence seSent : seSents) {
sw.write(seSent);
}
}
}
}
} finally {
sw.close();
}
} else if (type == DatasetType.CONCRETE) {
Communication comm = (Communication) sents.getSourceSents();
ConcreteWriter w = new ConcreteWriter(false);
w.addDependencyParse(sents, comm);
try {
byte[] bytez = new TSerializer(new TBinaryProtocol.Factory()).serialize(comm);
Files.write(Paths.get(out.getAbsolutePath()), bytez);
} catch (TException e) {
throw new RuntimeException(e);
}
} else {
throw new IllegalStateException("Unsupported data type: " + type);
}
}
} |
package edu.ucsf.mousedatabase.Filters;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.ucsf.mousedatabase.HTMLGeneration;
import edu.ucsf.mousedatabase.Log;
/**
* Servlet Filter implementation class LoginFilter
*/
public class LoginFilter implements Filter {
int indexOfCredential = 13;
String keyName = "user_claims";
String typeName = "http://schemas.microsoft.com/identity/claims/objectidentifier";
String envName = "admins";
/**
* Default constructor.
*/
public LoginFilter() {
// TODO Auto-generated constructor stub
Log.Info("made loginFilter");
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
Consumer<String> logConsumer = new Consumer<String>() {
public void accept(String value) {
Log.Info(value);
}
};
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean loggedIn = false;
Log.Info("reached filter");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String credential = System.getenv(envName);
//String data = request.getAuthType();
//Log.Info("user data is : " + data);
String headerName = request.getHeaderNames().toString();
Log.Info("user headerNames: " + headerName);
/*
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length; i++) {
Log.Info(cookies[i].getName());
Log.Info(cookies[i].getValue());
}
Log.Info("cookies logged");
*/
Log.Info("about to log principle");
Map<String, Collection<String>> map = (Map<String, Collection<String>>) request.getUserPrincipal();
if (map != null) {
Log.Info("principle exists!");
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null && value instanceof Collection) {
Collection claims = (Collection) value;
for (Object claim : claims) {
System.out.println(claim);
Log.Info(claim);
}
}
}
} else {
Log.Info("User principle is null");
}
/*for (Object key : map.keySet()) {
if (key == keyName) {
Collection<String> values = map.get(key);
values.forEach(logConsumer);
//String[] useableValues = (String[]) values.toArray();
if (useableValues[indexOfCredential] == credential) { //may need to restructure this
loggedIn = true;
}
}
}*/
/*if(loggedIn) {
// pass the request along the filter chain
chain.doFilter(request, response);
} else {
response.sendRedirect(HTMLGeneration.siteRoot + "accessDenied.jsp");
}*/
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
Log.Info("Starting filter");
}
} |
package es.usc.citius.lab.hipster.algorithm;
import es.usc.citius.lab.hipster.function.CostFunction;
import es.usc.citius.lab.hipster.function.HeuristicFunction;
import es.usc.citius.lab.hipster.function.TransitionFunction;
import es.usc.citius.lab.hipster.node.ADStarNode;
import es.usc.citius.lab.hipster.node.Node;
import es.usc.citius.lab.hipster.node.NodeBuilder;
import es.usc.citius.lab.hipster.node.Transition;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class ADStar<S> implements Iterator<Node<S>> {
private final ADStarNode<S> beginNode;
private final ADStarNode<S> goalNode;
private final TransitionFunction<S> predecessorFunction;
private final TransitionFunction<S> successorFunction;
private final CostFunction<S, Double> costFunction;
private final HeuristicFunction<S, Double> heuristicFunction;
private final NodeBuilder<S, ADStarNode<S>> nodeBuilder;
private Map<S, ADStarNode<S>> open;
private Map<S, ADStarNode<S>> closed;
private Map<S, ADStarNode<S>> incons;
private Queue<ADStarNode<S>> queue;
private Double epsilon = 1.0;
public ADStar(S begin, S goal, TransitionFunction<S> predecessors, TransitionFunction<S> successors, CostFunction<S, Double> costFunction, HeuristicFunction<S, Double> heuristic, NodeBuilder<S, ADStarNode<S>> builder) {
this.nodeBuilder = builder;
this.predecessorFunction = predecessors;
this.successorFunction = successors;
this.costFunction = costFunction;
this.heuristicFunction = heuristic;
this.open = new HashMap<S, ADStarNode<S>>();
this.closed = new HashMap<S, ADStarNode<S>>();
this.incons = new HashMap<S, ADStarNode<S>>();
this.queue = new PriorityQueue<ADStarNode<S>>();
this.beginNode = this.nodeBuilder.node(null, new Transition<S>(null, begin));
this.goalNode = this.nodeBuilder.node(null, new Transition<S>(null, goal));
/*Initialization step*/
this.beginNode.setG(0);
this.beginNode.setKey(new ADStarNode.Key(this.beginNode.getG(), this.beginNode.getV(), this.heuristicFunction.estimate(this.beginNode.transition().to()), this.epsilon));
this.goalNode.setKey(new ADStarNode.Key(this.goalNode.getG(), this.goalNode.getV(), this.heuristicFunction.estimate(this.goalNode.transition().to()), this.epsilon));
insertOpen(beginNode);
}
/**
* Retrieves the most promising node from the open collection, or null if it
* is empty.
*
* @return most promising node
*/
private ADStarNode<S> takePromising() {
while (!this.queue.isEmpty()) {
ADStarNode<S> head = this.queue.peek();
if (!this.open.containsKey(head.transition().to())) {
this.queue.poll();
} else {
return head;
}
}
return null;
}
/**
* Inserts a node in the open queue.
*
* @param node instance of node to add
*/
private void insertOpen(ADStarNode<S> node) {
this.open.put(node.transition().to(), node);
this.queue.offer(node);
}
/**
* Updates the membership of the node to the algorithm queues.
*
* @param node instance of {@link ADStarNode}
*/
private void update(ADStarNode<S> node) {
S state = node.transition().to();
if (Double.compare(node.getV(), node.getG()) != 0) {
if (!this.closed.containsKey(state)) {
node.setKey(new ADStarNode.Key(node.getG(), node.getV(), this.heuristicFunction.estimate(state), this.epsilon));
this.open.put(state, node);
this.queue.offer(node);
} else {
this.incons.put(state, node);
}
} else {
this.open.remove(state);
this.incons.remove(state);
}
}
/**
* As the algorithm is executed iteratively refreshing the changed relations
* between nodes, this method will return always true.
*
* @return always true
*/
public boolean hasNext() {
return takePromising() != null;
}
public Node<S> next() {
/*First node in queue is retrieved.*/
ADStarNode<S> s = takePromising();
if (this.goalNode.compareTo(s) > 0 || this.goalNode.getV() < this.goalNode.getG()) {
/*Loop of ComputeOrImprovePath is true: Actions taken.*/
/*Removes from Open the most promising node.*/
this.open.remove(s.transition().to());
if (s.getV() > s.getG()) {
s.setV(s.getG());
this.closed.put(s.transition().to(), s);
for (Iterator<Transition<S>> it = this.successorFunction.from(s.transition().to()).iterator(); it.hasNext();) {
Transition<S> succesor = it.next();
ADStarNode<S> current = this.nodeBuilder.node(s, succesor);
if (current.getG() > s.getG() + this.costFunction.evaluate(current.transition())) {
current.setPreviousNode(s);
current.setG(current.previousNode().getG() + this.costFunction.evaluate(succesor));
update(current);
}
}
} else {
s.setV(Double.POSITIVE_INFINITY);
update(s);
for (Iterator<Transition<S>> it = this.successorFunction.from(s.transition().to()).iterator(); it.hasNext();) {
Transition<S> succesor = it.next();
ADStarNode<S> current = this.nodeBuilder.node(s, succesor);
if (current.previousNode().equals(s)) {
Double minValue = Double.POSITIVE_INFINITY;
ADStarNode<S> minPredecessorNode = null;
for (Iterator<Transition<S>> it2 = this.predecessorFunction.from(succesor.to()).iterator(); it2.hasNext();) {
Transition<S> predecessor = it2.next();
ADStarNode<S> predecessorNode = this.nodeBuilder.node(current, predecessor);
Double currentValue = predecessorNode.getV() + this.costFunction.evaluate(predecessor);
if (currentValue < minValue) {
minValue = currentValue;
minPredecessorNode = predecessorNode;
}
}
/*Update the parent node to keep the path updated.*/
current.setPreviousNode(minPredecessorNode);
current.setG(current.previousNode().getV() + this.costFunction.evaluate(current.transition()));
update(current);
}
}
}
} else {
/*Executes the changed relations processing and Epsilon updating.*/
}
return s;
}
/**
* Method not supported.
*/
public void remove() {
throw new UnsupportedOperationException();
}
} |
package com.continuuity.data.operation.executor.omid;
import com.continuuity.api.data.*;
import com.continuuity.common.metrics.CMetrics;
import com.continuuity.common.metrics.MetricType;
import com.continuuity.common.utils.ImmutablePair;
import com.continuuity.data.metadata.SerializingMetaDataStore;
import com.continuuity.data.operation.*;
import com.continuuity.data.operation.StatusCode;
import com.continuuity.data.operation.executor.TransactionalOperationExecutor;
import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueFinalize;
import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnack;
import com.continuuity.data.operation.executor.omid.QueueInvalidate.QueueUnenqueue;
import com.continuuity.data.operation.executor.omid.memory.MemoryRowSet;
import com.continuuity.data.operation.ttqueue.*;
import com.continuuity.data.operation.ttqueue.QueueAdmin.GetGroupID;
import com.continuuity.data.operation.ttqueue.QueueAdmin.GetQueueMeta;
import com.continuuity.data.operation.ttqueue.QueueAdmin.QueueMeta;
import com.continuuity.data.table.OVCTableHandle;
import com.continuuity.data.table.OrderedVersionedColumnarTable;
import com.continuuity.data.table.ReadPointer;
import com.continuuity.data.util.TupleMetaDataAnnotator.DequeuePayload;
import com.continuuity.data.util.TupleMetaDataAnnotator.EnqueuePayload;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
@Singleton
public class OmidTransactionalOperationExecutor
implements TransactionalOperationExecutor {
private static final Logger Log
= LoggerFactory.getLogger(OmidTransactionalOperationExecutor.class);
public String getName() {
return "omid(" + tableHandle.getName() + ")";
}
/**
* The Transaction Oracle used by this executor instance.
*/
@Inject
TransactionOracle oracle;
/**
* The {@link OVCTableHandle} handle used to get references to tables.
*/
@Inject
OVCTableHandle tableHandle;
private OrderedVersionedColumnarTable metaTable;
private OrderedVersionedColumnarTable randomTable;
private MetaDataStore metaStore;
private TTQueueTable queueTable;
private TTQueueTable streamTable;
public static boolean DISABLE_QUEUE_PAYLOADS = false;
static int MAX_DEQUEUE_RETRIES = 200;
static long DEQUEUE_RETRY_SLEEP = 5;
// Metrics
private CMetrics cmetric = new CMetrics(MetricType.System);
private static final String METRIC_PREFIX = "omid-opex-";
private void requestMetric(String requestType) {
// TODO rework metric emission to avoid always generating the metric names
cmetric.meter(METRIC_PREFIX + requestType + "-numops", 1);
}
private long begin() { return System.currentTimeMillis(); }
private void end(String requestType, long beginning) {
cmetric.histogram(METRIC_PREFIX + requestType + "-latency",
System.currentTimeMillis() - beginning);
}
private ConcurrentMap<String, CMetrics> queueMetrics =
new ConcurrentHashMap<String, CMetrics>();
private CMetrics getQueueMetric(String group) {
CMetrics metric = queueMetrics.get(group);
if (metric == null) {
queueMetrics.putIfAbsent(group,
new CMetrics(MetricType.FlowSystem, group));
metric = queueMetrics.get(group);
Log.debug("Created new CMetrics for group '" + group + "'.");
}
return metric;
}
private ConcurrentMap<byte[], ImmutablePair<String, String>>
queueMetricNames = new ConcurrentSkipListMap<byte[],
ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR);
private ImmutablePair<String, String> getQueueMetricNames(byte[] queue) {
ImmutablePair<String, String> names = queueMetricNames.get(queue);
if (names == null) {
String name = new String(queue).replace(":", "");
queueMetricNames.putIfAbsent(queue, new ImmutablePair<String, String>
("q.enqueue." + name, "q.ack." + name));
names = queueMetricNames.get(queue);
Log.debug("using metric name '" + names.getFirst() + "' and '"
+ names.getSecond() + "' for queue '" + new String(queue) + "'");
}
return names;
}
private void enqueueMetric(byte[] queue, QueueProducer producer) {
if (producer != null && producer.getProducerName() != null) {
String metricName = getQueueMetricNames(queue).getFirst();
getQueueMetric(producer.getProducerName()).meter(metricName, 1);
}
}
private void ackMetric(byte[] queue, QueueConsumer consumer) {
if (consumer != null && consumer.getGroupName() != null) {
String metricName = getQueueMetricNames(queue).getSecond();
getQueueMetric(consumer.getGroupName()).meter(metricName, 1);
}
}
private CMetrics streamMetric = // we use a global flow group
new CMetrics(MetricType.FlowSystem, "-.-.-.-.-.0");
private ConcurrentMap<byte[], ImmutablePair<String, String>>
streamMetricNames = new ConcurrentSkipListMap<byte[],
ImmutablePair<String, String>>(Bytes.BYTES_COMPARATOR);
private ImmutablePair<String, String> getStreamMetricNames(byte[] stream) {
ImmutablePair<String, String> names = streamMetricNames.get(stream);
if (names == null) {
String name = new String(stream).replace(":", "");
streamMetricNames.putIfAbsent(stream, new ImmutablePair<String, String>(
"stream.enqueue." + name, "stream.storage." + name));
names = streamMetricNames.get(stream);
Log.debug("using metric name '" + names.getFirst() + "' and '"
+ names.getSecond() + "' for stream '" + new String(stream) + "'");
}
return names;
}
private boolean isStream(byte[] queueName) {
return Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX);
}
private int streamSizeEstimate(byte[] streamName, byte[] data) {
// assume HBase uses space for the stream name, the data, and some metadata
return streamName.length + data.length + 50;
}
private void streamMetric(byte[] streamName, byte[] data) {
ImmutablePair<String, String> names = getStreamMetricNames(streamName);
streamMetric.meter(names.getFirst(), 1);
streamMetric.meter(names.getSecond(), streamSizeEstimate(streamName, data));
}
// named table management
// a map of logical table name to existing <real name, table>, caches
// the meta data store and the ovc table handle
// there are three possible states for a table:
// 1. table does not exist or is not known -> no entry
// 2. table is being created -> entry with real name, but null for the table
// 3. table is known -> entry with name and table
ConcurrentMap<ImmutablePair<String,String>,
ImmutablePair<byte[], OrderedVersionedColumnarTable>> namedTables;
// method to find - and if necessary create - a table
OrderedVersionedColumnarTable findRandomTable(
OperationContext context, String name)
throws OperationException {
// check whether it is one of the default tables these are always
// pre-loaded at initializaton and we can just return them
if (null == name)
return this.randomTable;
if ("meta".equals(name))
return this.metaTable;
// look up table in in-memory map. if this returns:
// an actual name and OVCTable, return that OVCTable
ImmutablePair<String, String> tableKey = new
ImmutablePair<String, String>(context.getAccount(), name);
ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable =
this.namedTables.get(tableKey);
if (nameAndTable != null) {
if (nameAndTable.getSecond() != null)
return nameAndTable.getSecond();
// an actual name and null for the table, then sleep/repeat until the look
// up returns non-null for the table. This is the case when some other
// thread in the same process has generated an actual name and is in the
// process of creating that table.
return waitForTableToMaterialize(tableKey);
}
// null: then this table has not been opened by any thread in this
// process. In this case:
// Read the meta data for the logical name from MDS.
MetaDataEntry meta = this.metaStore.get(
context, context.getAccount(), null, "namedTable", name);
if (null != meta) {
return waitForTableToMaterializeInMeta(context, name, meta);
// Null: Nobody has started to create this.
} else {
// Generate a new actual name, and write that name with status Pending
// to MDS in a Compare-and-Swap operation
byte[] actualName = generateActualName(context, name);
MetaDataEntry newMeta = new MetaDataEntry(context.getAccount(), null,
"namedTable", name);
newMeta.addField("actual", actualName);
newMeta.addField("status", "pending");
try {
this.metaStore.add(context, newMeta);
} catch (OperationException e) {
if (e.getStatus() == StatusCode.WRITE_CONFLICT) {
// If C-a-S failed with write conflict, then some other process (or
// thread) has concurrently attempted the same and wins.
return waitForTableToMaterializeInMeta(context, name, meta);
}
else throw e;
}
//C-a-S succeeded, add <actual name, null> to MEM to inform other threads
//in this process to wait (no other thread could have updated in the
// mean-time without updating MDS)
this.namedTables.put(tableKey,
new ImmutablePair<byte[], OrderedVersionedColumnarTable>(
actualName, null));
//Create a new actual table for the actual name. This should never fail.
OrderedVersionedColumnarTable table =
getTableHandle().getTable(actualName);
// Update MDS with the new status Ready. This can be an ordinary Write
newMeta.addField("status", "ready");
this.metaStore.update(context, newMeta);
// because all others are waiting.
// Update MEM with the actual created OVCTable.
this.namedTables.put(tableKey,
new ImmutablePair<byte[], OrderedVersionedColumnarTable>(
actualName, table));
//Return the created table.
return table;
}
}
private byte[] generateActualName(OperationContext context, String name) {
// TODO make this generate a new id every time it is called
return ("random_" + context.getAccount() + "_" + name).getBytes();
}
private OrderedVersionedColumnarTable waitForTableToMaterialize(
ImmutablePair<String, String> tableKey) {
while (true) {
ImmutablePair<byte[], OrderedVersionedColumnarTable> nameAndTable =
this.namedTables.get(tableKey);
if (nameAndTable == null) {
throw new InternalError("In-memory entry went from non-null to null " +
"for named table \"" + tableKey.getSecond() + "\"");
}
if (nameAndTable.getSecond() != null) {
return nameAndTable.getSecond();
}
// sleep a little
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// what the heck should I do?
}
}
// TODO should this time out after some time or number of attempts?
}
OrderedVersionedColumnarTable waitForTableToMaterializeInMeta(
OperationContext context, String name, MetaDataEntry meta)
throws OperationException {
while(true) {
// If this returns: An actual name and status Ready: The table is ready
// to use, open the table, add it to MEM and return it
if ("ready".equals(meta.getTextField("status"))) {
byte[] actualName = meta.getBinaryField("actual");
if (actualName == null)
throw new InternalError("Encountered meta data entry of type " +
"\"namedTable\" without actual name for table name \"" +
name +"\".");
OrderedVersionedColumnarTable table =
getTableHandle().getTable(actualName);
if (table == null)
throw new InternalError("table handle \"" + getTableHandle()
.getName() + "\": getTable returned null for actual table name "
+ "\"" + new String(actualName) + "\"");
// update MEM. This can be ordinary put, because even if some other
// thread updated it in the meantime, it would have put the same table.
ImmutablePair<String, String> tableKey = new
ImmutablePair<String, String>(context.getAccount(), name);
this.namedTables.put(tableKey,
new ImmutablePair<byte[], OrderedVersionedColumnarTable>(
actualName, table));
return table;
}
// An actual name and status Pending: The table is being created. Loop
// and repeat MDS read until status is Ready and see previous case
else if (!"pending".equals(meta.getTextField("status"))) {
throw new InternalError("Found meta data entry with unkown status " +
Objects.toStringHelper(meta.getTextField("status")));
}
// sleep a little
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// what the heck should I do?
}
// reread the meta data, hopefully it has changed to ready
meta = this.metaStore.get(
context, context.getAccount(), null, "namedTable", name);
if (meta == null)
throw new InternalError("Meta data entry went from non-null to null " +
"for table \"" + name + "\"");
// TODO should this time out after some time or number of attempts?
}
}
// Single reads
@Override
public OperationResult<byte[]> execute(OperationContext context,
ReadKey read)
throws OperationException {
initialize();
requestMetric("ReadKey");
long begin = begin();
OperationResult<byte[]> result =
read(context, read, this.oracle.getReadPointer());
end("ReadKey", begin);
return result;
}
OperationResult<byte[]> read(OperationContext context,
ReadKey read, ReadPointer pointer)
throws OperationException {
OrderedVersionedColumnarTable table =
this.findRandomTable(context, read.getTable());
return table.get(read.getKey(), Operation.KV_COL, pointer);
}
@Override
public OperationResult<List<byte[]>> execute(OperationContext context,
ReadAllKeys readKeys)
throws OperationException {
initialize();
requestMetric("ReadAllKeys");
long begin = begin();
OrderedVersionedColumnarTable table =
this.findRandomTable(context, readKeys.getTable());
List<byte[]> result = table.getKeys(readKeys.getLimit(),
readKeys.getOffset(), this.oracle.getReadPointer());
end("ReadKey", begin);
return new OperationResult<List<byte[]>>(result);
}
@Override
public OperationResult<Map<byte[], byte[]>> execute(OperationContext context,
Read read)
throws OperationException {
initialize();
requestMetric("Read");
long begin = begin();
OrderedVersionedColumnarTable table =
this.findRandomTable(context, read.getTable());
OperationResult<Map<byte[], byte[]>> result = table.get(
read.getKey(), read.getColumns(), this.oracle.getReadPointer());
end("Read", begin);
return result;
}
@Override
public OperationResult<Map<byte[], byte[]>>
execute(OperationContext context,
ReadColumnRange readColumnRange) throws OperationException {
initialize();
requestMetric("ReadColumnRange");
long begin = begin();
OrderedVersionedColumnarTable table =
this.findRandomTable(context, readColumnRange.getTable());
OperationResult<Map<byte[], byte[]>> result = table.get(
readColumnRange.getKey(), readColumnRange.getStartColumn(),
readColumnRange.getStopColumn(), readColumnRange.getLimit(),
this.oracle.getReadPointer());
end("ReadColumnRange", begin);
return result;
}
// Administrative calls
@Override
public void execute(OperationContext context,
ClearFabric clearFabric) throws OperationException {
initialize();
requestMetric("ClearFabric");
long begin = begin();
if (clearFabric.shouldClearData()) this.randomTable.clear();
if (clearFabric.shouldClearTables()) {
List<MetaDataEntry> entries = this.metaStore.list(
context, context.getAccount(), null, "namedTable", null);
for (MetaDataEntry entry : entries) {
String name = entry.getId();
OrderedVersionedColumnarTable table = findRandomTable(context, name);
table.clear();
this.namedTables.remove(new ImmutablePair<String,
String>(context.getAccount(),name));
this.metaStore.delete(context, entry.getAccount(),
entry.getApplication(), entry.getType(), entry.getId());
}
}
if (clearFabric.shouldClearMeta()) this.metaTable.clear();
if (clearFabric.shouldClearQueues()) this.queueTable.clear();
if (clearFabric.shouldClearStreams()) this.streamTable.clear();
end("ClearFabric", begin);
}
@Override
public void execute(OperationContext context, OpenTable openTable)
throws OperationException {
initialize();
findRandomTable(context, openTable.getTableName());
}
// Write batches
@Override
public void execute(OperationContext context,
List<WriteOperation> writes)
throws OperationException {
initialize();
requestMetric("WriteOperationBatch");
long begin = begin();
cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_NumReqs", writes.size());
execute(context, writes, startTransaction());
end("WriteOperationBatch", begin);
}
private void executeAsBatch(OperationContext context,
WriteOperation write)
throws OperationException {
execute(context, Collections.singletonList(write));
}
void execute(OperationContext context, List<WriteOperation> writes,
ImmutablePair<ReadPointer,Long> pointer)
throws OperationException {
if (writes.isEmpty()) return;
// Re-order operations (create a copy for now)
List<WriteOperation> orderedWrites = new ArrayList<WriteOperation>(writes);
Collections.sort(orderedWrites, new WriteOperationComparator());
// Execute operations
RowSet rows = new MemoryRowSet();
List<Delete> deletes = new ArrayList<Delete>(writes.size());
List<QueueInvalidate> invalidates = new ArrayList<QueueInvalidate>();
// Track a map from increment operation ids to post-increment values
Map<Long,Long> incrementResults = new TreeMap<Long,Long>();
for (WriteOperation write : orderedWrites) {
// See if write operation is an enqueue, and if so, update serialized data
if (write instanceof QueueEnqueue) {
processEnqueue((QueueEnqueue)write, incrementResults);
}
WriteTransactionResult writeTxReturn =
dispatchWrite(context, write, pointer);
if (!writeTxReturn.success) {
// Write operation failed
cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedWrites", 1);
abortTransaction(context, pointer, deletes, invalidates);
throw new OmidTransactionException(
writeTxReturn.statusCode, writeTxReturn.message);
} else {
// Write was successful. Store delete if we need to abort and continue
deletes.addAll(writeTxReturn.deletes);
if (writeTxReturn.invalidate != null) {
// Queue operation
invalidates.add(writeTxReturn.invalidate);
} else {
// Normal write operation
rows.addRow(write.getKey());
}
// See if write operation was an Increment, and if so, add result to map
if (write instanceof Increment) {
incrementResults.put(write.getId(), writeTxReturn.incrementValue);
}
}
}
// All operations completed successfully, commit transaction
if (!commitTransaction(pointer, rows)) {
// Commit failed, abort
cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_FailedCommits", 1);
abortTransaction(context, pointer, deletes, invalidates);
throw new OmidTransactionException(StatusCode.WRITE_CONFLICT,
"Commit of transaction failed, transaction aborted");
}
// If last operation was an ack, finalize it
if (orderedWrites.get(orderedWrites.size() - 1) instanceof QueueAck) {
QueueAck ack = (QueueAck)orderedWrites.get(orderedWrites.size() - 1);
QueueFinalize finalize = new QueueFinalize(ack.getKey(),
ack.getEntryPointer(), ack.getConsumer(), ack.getNumGroups());
finalize.execute(getQueueTable(ack.getKey()), pointer);
}
// Transaction was successfully committed, emit metrics
// - for the transaction
cmetric.meter(
METRIC_PREFIX + "WriteOperationBatch_SuccessfulTransactions", 1);
// for each queue operation (enqueue or ack)
for (QueueInvalidate invalidate : invalidates)
if (invalidate instanceof QueueUnenqueue) {
QueueUnenqueue unenqueue = (QueueUnenqueue)invalidate;
QueueProducer producer = unenqueue.producer;
enqueueMetric(unenqueue.queueName, producer);
if (isStream(unenqueue.queueName))
streamMetric(unenqueue.queueName, unenqueue.data);
} else if (invalidate instanceof QueueUnack) {
QueueUnack unack = (QueueUnack)invalidate;
QueueConsumer consumer = unack.consumer;
ackMetric(unack.queueName, consumer);
}
}
/**
* Deserializes enqueue data into enqueue payload, checks if any fields are
* marked to contain increment values, construct a dequeue payload, update any
* fields necessary, and finally update the enqueue data to contain a dequeue
* payload.
*/
private void processEnqueue(QueueEnqueue enqueue,
Map<Long, Long> incrementResults) throws OperationException {
if (DISABLE_QUEUE_PAYLOADS) return;
// Deserialize enqueue payload
byte [] enqueuePayloadBytes = enqueue.getData();
EnqueuePayload enqueuePayload;
try {
enqueuePayload = EnqueuePayload.read(enqueuePayloadBytes);
} catch (IOException e) {
// Unable to deserialize the enqueue payload, fatal error (if queues are
// not using payloads, change DISABLE_QUEUE_PAYLOADS=true
e.printStackTrace();
throw new RuntimeException(e);
}
Map<String,Long> fieldsToIds = enqueuePayload.getOperationIds();
Map<String,Long> fieldsToValues = new TreeMap<String,Long>();
// For every field-to-id mapping, find increment result
for (Map.Entry<String,Long> fieldAndId : fieldsToIds.entrySet()) {
String field = fieldAndId.getKey();
Long operationId = fieldAndId.getValue();
Long incrementValue = incrementResults.get(operationId);
if (incrementValue == null) {
throw new OperationException(StatusCode.INTERNAL_ERROR,
"Field specified as containing an increment result but no " +
"matching increment operation found");
}
// Store field-to-value in map for dequeue payload
fieldsToValues.put(field, incrementValue);
}
// Serialize dequeue payload and overwrite enqueue data
try {
enqueue.setData(DequeuePayload.write(fieldsToValues,
enqueuePayload.getSerializedTuple()));
} catch (IOException e) {
// Fatal error serializing dequeue payload
e.printStackTrace();
throw new RuntimeException(e);
}
}
public OVCTableHandle getTableHandle() {
return this.tableHandle;
}
static final List<Delete> noDeletes = Collections.emptyList();
private class WriteTransactionResult {
final boolean success;
final int statusCode;
final String message;
final List<Delete> deletes;
final QueueInvalidate invalidate;
Long incrementValue;
WriteTransactionResult(boolean success, int status, String message,
List<Delete> deletes, QueueInvalidate invalidate) {
this.success = success;
this.statusCode = status;
this.message = message;
this.deletes = deletes;
this.invalidate = invalidate;
}
// successful, one delete to undo
WriteTransactionResult(Delete delete) {
this(true, StatusCode.OK, null, Collections.singletonList(delete), null);
}
// successful increment, one delete to undo
WriteTransactionResult(Delete delete, Long incrementValue) {
this(true, StatusCode.OK, null, Collections.singletonList(delete), null);
this.incrementValue = incrementValue;
}
// successful, one queue operation to invalidate
WriteTransactionResult(QueueInvalidate invalidate) {
this(true, StatusCode.OK, null, noDeletes, invalidate);
}
// failure with status code and message, nothing to undo
WriteTransactionResult(int status, String message) {
this(false, status, message, noDeletes, null);
}
}
/**
* Actually perform the various write operations.
*/
private WriteTransactionResult dispatchWrite(
OperationContext context, WriteOperation write,
ImmutablePair<ReadPointer,Long> pointer) throws OperationException {
if (write instanceof Write) {
return write(context, (Write)write, pointer);
} else if (write instanceof Delete) {
return write(context, (Delete)write, pointer);
} else if (write instanceof Increment) {
return write(context, (Increment)write, pointer);
} else if (write instanceof CompareAndSwap) {
return write(context, (CompareAndSwap)write, pointer);
} else if (write instanceof QueueEnqueue) {
return write((QueueEnqueue)write, pointer);
} else if (write instanceof QueueAck) {
return write((QueueAck)write, pointer);
}
return new WriteTransactionResult(StatusCode.INTERNAL_ERROR,
"Unknown write operation " + write.getClass().getName());
}
WriteTransactionResult write(OperationContext context, Write write,
ImmutablePair<ReadPointer,Long> pointer) throws OperationException {
initialize();
requestMetric("Write");
long begin = begin();
OrderedVersionedColumnarTable table =
this.findRandomTable(context, write.getTable());
table.put(write.getKey(), write.getColumns(),
pointer.getSecond(), write.getValues());
end("Write", begin);
return new WriteTransactionResult(
new Delete(write.getTable(), write.getKey(), write.getColumns()));
}
WriteTransactionResult write(OperationContext context, Delete delete,
ImmutablePair<ReadPointer, Long> pointer) throws OperationException {
initialize();
requestMetric("Delete");
long begin = begin();
OrderedVersionedColumnarTable table =
this.findRandomTable(context, delete.getTable());
table.deleteAll(delete.getKey(), delete.getColumns(),
pointer.getSecond());
end("Delete", begin);
return new WriteTransactionResult(
new Undelete(delete.getTable(), delete.getKey(), delete.getColumns()));
}
WriteTransactionResult write(OperationContext context, Increment increment,
ImmutablePair<ReadPointer,Long> pointer) throws OperationException {
initialize();
requestMetric("Increment");
long begin = begin();
Long incrementValue;
try {
@SuppressWarnings("unused")
OrderedVersionedColumnarTable table =
this.findRandomTable(context, increment.getTable());
Map<byte[],Long> map =
table.increment(increment.getKey(),
increment.getColumns(), increment.getAmounts(),
pointer.getFirst(), pointer.getSecond());
incrementValue = map.values().iterator().next();
} catch (OperationException e) {
return new WriteTransactionResult(e.getStatus(), e.getMessage());
}
end("Increment", begin);
return new WriteTransactionResult(
new Delete(increment.getTable(), increment.getKey(),
increment.getColumns()), incrementValue);
}
WriteTransactionResult write(OperationContext context, CompareAndSwap write,
ImmutablePair<ReadPointer,Long> pointer) throws OperationException {
initialize();
requestMetric("CompareAndSwap");
long begin = begin();
try {
OrderedVersionedColumnarTable table =
this.findRandomTable(context, write.getTable());
table.compareAndSwap(write.getKey(),
write.getColumn(), write.getExpectedValue(), write.getNewValue(),
pointer.getFirst(), pointer.getSecond());
} catch (OperationException e) {
return new WriteTransactionResult(e.getStatus(), e.getMessage());
}
end("CompareAndSwap", begin);
return new WriteTransactionResult(
new Delete(write.getTable(), write.getKey(), write.getColumn()));
}
// TTQueues
/**
* EnqueuePayload operations always succeed but can be rolled back.
*
* They are rolled back with an invalidate.
*/
WriteTransactionResult write(QueueEnqueue enqueue,
ImmutablePair<ReadPointer, Long> pointer) throws OperationException {
initialize();
requestMetric("QueueEnqueue");
long begin = begin();
EnqueueResult result = getQueueTable(enqueue.getKey()).enqueue(
enqueue.getKey(), enqueue.getData(), pointer.getSecond());
end("QueueEnqueue", begin);
return new WriteTransactionResult(
new QueueUnenqueue(enqueue.getKey(), enqueue.getData(),
enqueue.getProducer(), result.getEntryPointer()));
}
WriteTransactionResult write(QueueAck ack,
@SuppressWarnings("unused") ImmutablePair<ReadPointer, Long> pointer)
throws OperationException {
initialize();
requestMetric("QueueAck");
long begin = begin();
try {
getQueueTable(ack.getKey()).ack(ack.getKey(),
ack.getEntryPointer(), ack.getConsumer());
} catch (OperationException e) {
// Ack failed, roll back transaction
return new WriteTransactionResult(StatusCode.ILLEGAL_ACK,
"Attempt to ack a dequeue of a different consumer");
} finally {
end("QueueAck", begin);
}
return new WriteTransactionResult(
new QueueUnack(ack.getKey(), ack.getEntryPointer(), ack.getConsumer()));
}
@Override
public DequeueResult execute(OperationContext context,
QueueDequeue dequeue)
throws OperationException {
initialize();
requestMetric("QueueDequeue");
long begin = begin();
int retries = 0;
long start = System.currentTimeMillis();
TTQueueTable queueTable = getQueueTable(dequeue.getKey());
while (retries < MAX_DEQUEUE_RETRIES) {
DequeueResult result = queueTable.dequeue(dequeue.getKey(),
dequeue.getConsumer(), dequeue.getConfig(),
this.oracle.getReadPointer());
if (result.shouldRetry()) {
retries++;
try {
if (DEQUEUE_RETRY_SLEEP > 0) Thread.sleep(DEQUEUE_RETRY_SLEEP);
} catch (InterruptedException e) {
e.printStackTrace();
// continue in loop
}
continue;
}
end("QueueDequeue", begin);
return result;
}
long end = System.currentTimeMillis();
end("QueueDequeue", begin);
throw new OperationException(StatusCode.TOO_MANY_RETRIES,
"Maximum retries (retried " + retries + " times over " + (end-start) +
" millis");
}
@Override
public long execute(OperationContext context,
GetGroupID getGroupId)
throws OperationException {
initialize();
requestMetric("GetGroupID");
long begin = begin();
TTQueueTable table = getQueueTable(getGroupId.getQueueName());
long groupid = table.getGroupID(getGroupId.getQueueName());
end("GetGroupID", begin);
return groupid;
}
@Override
public OperationResult<QueueMeta> execute(OperationContext context,
GetQueueMeta getQueueMeta)
throws OperationException {
initialize();
requestMetric("GetQueueMeta");
long begin = begin();
TTQueueTable table = getQueueTable(getQueueMeta.getQueueName());
QueueMeta queueMeta = table.getQueueMeta(getQueueMeta.getQueueName());
end("GetQueueMeta", begin);
return new OperationResult<QueueMeta>(queueMeta);
}
ImmutablePair<ReadPointer, Long> startTransaction() {
requestMetric("StartTransaction");
return this.oracle.getNewPointer();
}
boolean commitTransaction(ImmutablePair<ReadPointer, Long> pointer,
RowSet rows) throws OmidTransactionException {
requestMetric("CommitTransaction");
return this.oracle.commit(pointer.getSecond(), rows);
}
private void abortTransaction(OperationContext context,
ImmutablePair<ReadPointer, Long> pointer,
List<Delete> deletes,
List<QueueInvalidate> invalidates)
throws OperationException {
// Perform queue invalidates
cmetric.meter(METRIC_PREFIX + "WriteOperationBatch_AbortedTransactions", 1);
for (QueueInvalidate invalidate : invalidates) {
invalidate.execute(getQueueTable(invalidate.queueName), pointer);
}
// Perform deletes
for (Delete delete : deletes) {
assert(delete != null);
OrderedVersionedColumnarTable table =
this.findRandomTable(context, delete.getTable());
if (delete instanceof Undelete) {
table.undeleteAll(delete.getKey(), delete.getColumns(),
pointer.getSecond());
} else {
table.delete(delete.getKey(), delete.getColumns(),
pointer.getSecond());
}
}
// Notify oracle
this.oracle.aborted(pointer.getSecond());
}
// Single Write Operations (Wrapped and called in a transaction batch)
@SuppressWarnings("unused")
private void unsupported(String msg) {
throw new RuntimeException(msg);
}
@Override
public void execute(OperationContext context,
Write write) throws OperationException {
executeAsBatch(context, write);
}
@Override
public void execute(OperationContext context,
Delete delete) throws OperationException {
executeAsBatch(context, delete);
}
@Override
public void execute(OperationContext context,
Increment inc) throws OperationException {
executeAsBatch(context, inc);
}
@Override
public void execute(OperationContext context,
CompareAndSwap cas) throws OperationException {
executeAsBatch(context, cas);
}
@Override
public void execute(OperationContext context,
QueueAck ack) throws OperationException {
executeAsBatch(context, ack);
}
@Override
public void execute(OperationContext context,
QueueEnqueue enqueue) throws OperationException {
executeAsBatch(context, enqueue);
}
private TTQueueTable getQueueTable(byte[] queueName) {
if (Bytes.startsWith(queueName, TTQueue.QUEUE_NAME_PREFIX))
return this.queueTable;
if (Bytes.startsWith(queueName, TTQueue.STREAM_NAME_PREFIX))
return this.streamTable;
// by default, use queue table
return this.queueTable;
}
/**
* A utility method that ensures this class is properly initialized before
* it can be used. This currently entails creating real objects for all
* our table handlers.
*/
private synchronized void initialize() throws OperationException {
if (this.randomTable == null) {
this.metaTable = this.tableHandle.getTable(Bytes.toBytes("meta"));
this.randomTable = this.tableHandle.getTable(Bytes.toBytes("random"));
this.queueTable = this.tableHandle.getQueueTable(Bytes.toBytes("queues"));
this.streamTable = this.tableHandle.getStreamTable(Bytes.toBytes("streams"));
this.namedTables = Maps.newConcurrentMap();
this.metaStore = new SerializingMetaDataStore(this);
}
}
} // end of OmitTransactionalOperationExecutor |
package eu.socialsensor.sfc.streams.store;
import java.io.IOException;
import java.util.Queue;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.domain.Item.Operation;
/**
* Class for storing items to databases
*
*
* @author manosetro
* @email manosetro@iti.gr
* @author ailiakop
* @email ailiakop@iti.gr
*
*/
public class Consumer extends Thread{
private boolean isAlive = true;
private StreamUpdateStorage store = null;
private Queue<Item> queue;
public Consumer(Queue<Item> queue,StreamUpdateStorage store){
this.store = store;
this.queue = queue;
}
/**
* Stores an item if the latter is found waiting in the queue
*/
public void run() {
Item item = null;
while (isAlive) {
try {
item = poll();
if (item == null){
continue;
}else {
dump(item);
}
} catch(IOException e) {
e.printStackTrace();
}
}
//empty queue
while ((item = poll()) != null) {
try {
dump(item);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Stores an item to all available databases
* @param item
* @throws IOException
*/
private void dump(Item item) throws IOException {
//dump update to store
if (store != null) {
if (item.getOperation() == Operation.NEW) {
store.store(item);
}
else if (item.getOperation() == Operation.UPDATE) {
store.update(item);
}
else if (item.getOperation() == Operation.DELETED) {
store.delete(item.getId());
}
else {
System.out.println(item.getOperation() + ": Not supported operation");
}
}
}
/**
* Polls an item from the queue
* @return
*/
private Item poll() {
synchronized (queue) {
if (!queue.isEmpty()) {
Item item = queue.remove();
return item;
}
try {
queue.wait(1000);
} catch (InterruptedException e) {
}
return null;
}
}
/**
* Adds an item to the queue in order to be stored
* @param item
*/
public synchronized void update(Item item) {
synchronized(queue) {
queue.add(item);
}
}
/**
* Stops the consumer thread
* and closes all storages in case they have
* not yet been closed
*/
public synchronized void die() {
isAlive = false;
if(store != null){
store.close();
}
}
} |
package com.infinityraider.agricraft.plugins.industrialforegoing;
import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import java.util.List;
public class AgriPlantRecollectable extends PlantRecollectable {
protected AgriPlantRecollectable() {
super(AgriCraft.instance.getModId());
this.setRegistryName(AgriCraft.instance.getModId(), "plant_recollectable");
}
@Override
public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
}
@Override
public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
List<ItemStack> drops = Lists.newArrayList();
AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
return drops;
}
@Override
public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
return true;
}
} |
package fi.csc.microarray.client;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import fi.csc.microarray.client.dialog.RenameDialog;
import fi.csc.microarray.client.selection.DataSelectionManager;
import fi.csc.microarray.client.selection.DatasetChoiceEvent;
import fi.csc.microarray.client.visualisation.VisualisationMethod;
import fi.csc.microarray.client.visualisation.VisualisationMethodChangedEvent;
import fi.csc.microarray.client.visualisation.VisualisationToolBar;
import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.databeans.DataItem;
import fi.csc.microarray.module.chipster.ChipsterInputTypes;
import fi.csc.microarray.wizard.WizardPlugin;
public class MicroarrayMenuBar extends JMenuBar implements PropertyChangeListener {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(MicroarrayMenuBar.class);
private SwingClientApplication application;
private JMenu fileMenu = null;
private JMenu importMenu = null;
private JMenuItem directImportMenuItem = null;
private JMenuItem importFromURLMenuItem = null;
private JMenuItem importFromClipboardMenuItem = null;
private JMenuItem openWorkflowsMenuItem = null;
private JMenuItem addDirMenuItem = null;
private JMenuItem exportMenuItem = null;
private JMenuItem quitMenuItem = null;
private JMenu editMenu = null;
private JMenuItem renameMenuItem = null;
private JMenuItem deleteMenuItem = null;
private JMenu viewMenu = null;
private JMenuItem restoreViewMenuItem = null;
private JMenu fontSizeMenu = null;
private JMenu wizardMenu = null;
private JMenu workflowsMenu = null;
private JMenuItem wizardMenuItem = null;
private JMenu helpInfoMenu = null;
private JMenuItem aboutMenuItem = null;
private JMenuItem contentMenuItem;
private JMenuItem startedMenuItem;
private JMenuItem saveWorkflowMenuItem;
private JMenuItem saveSnapshotMenuItem;
private JMenu recentWorkflowMenu;
private JMenuItem loadSnapshotMenuItem;
private JMenuItem taskListMenuItem;
private JMenuItem clearSessionMenuItem;
private JMenuItem selectAllMenuItem;
private JMenuItem historyMenuItem;
//private JMenuItem duplicateMenuItem;
private JMenuItem maximiseVisualisationMenuItem;
private JMenuItem visualiseMenuItem;
private JMenuItem detachMenuItem;
private JMenu visualisationMenu;
private JMenuItem loadOldWorkspaceMenuItem;
public MicroarrayMenuBar(SwingClientApplication application) {
this.application = application;
add(getFileMenu());
add(getEditMenu());
add(getViewMenu());
add(getWizardMenu());
add(getWorkflowsMenu());
add(getHelpInfoMenu());
application.addPropertyChangeListener(this);
}
public void updateMenuStatus() {
logger.debug("updating menubar when selected is " + application.getSelectionManager().getSelectedItem());
DataSelectionManager selectionManager = application.getSelectionManager();
DataBean selectedDataBean = selectionManager.getSelectedDataBean();
boolean somethingSelected = selectionManager.getSelectedItem() != null;
boolean normalisedDataSelected = false;
if (selectedDataBean != null) {
normalisedDataSelected = ChipsterInputTypes.GENE_EXPRS.isTypeOf(selectedDataBean);
}
historyMenuItem.setEnabled(selectedDataBean != null &&
application.getSelectionManager().getSelectedDataBeans().size() == 1);
visualiseMenuItem.setEnabled(selectedDataBean != null);
VisualisationMethod method = application.getVisualisationFrameManager().getFrame(FrameType.MAIN).getMethod();
visualisationMenu.setEnabled(method != null && method != VisualisationMethod.NONE);
recentWorkflowMenu.setEnabled(normalisedDataSelected && workflowsMenu.getItemCount() > 0);
openWorkflowsMenuItem.setEnabled(normalisedDataSelected);
saveWorkflowMenuItem.setEnabled(normalisedDataSelected);
exportMenuItem.setEnabled(somethingSelected);
renameMenuItem.setEnabled(somethingSelected);
deleteMenuItem.setEnabled(somethingSelected);
/*
VisualisationToolBar visToolBar =
application.getVisualisationFrameManager().getVisualisationToolBar();
duplicateMenuItem.setText(visToolBar.getSplitText());
//Maximisation doesn't make events and the text wont stay up to date
maximiseVisualisationMenuItem.setText(visToolBar.getMaximiseButtonText());*/
}
/**
* This method initializes fileMenu
*
* @return javax.swing.JMenu
*/
private JMenu getFileMenu() {
if (fileMenu == null) {
fileMenu = new JMenu();
fileMenu.setText("File");
fileMenu.setMnemonic('F');
fileMenu.add(getDirectImportMenuItem());
fileMenu.add(getAddDirMenuItem());
fileMenu.add(getImportMenu());
fileMenu.addSeparator();
fileMenu.add(getExportMenuItem());
fileMenu.addSeparator();
fileMenu.add(getLoadSnapshotMenuItem());
fileMenu.add(getSaveSnapshotMenuItem());
fileMenu.add(getClearSessionMenuItem());
fileMenu.add(getLoadOldWorkspaceMenuItem());
fileMenu.addSeparator();
fileMenu.add(getQuitMenuItem());
}
return fileMenu;
}
private JMenu getImportMenu() {
if (importMenu == null) {
importMenu = new JMenu();
importMenu.setText("Import from");
importMenu.add(getImportFromURLMenuItem());
importMenu.add(getImportFromClipboardMenuItem());
}
return importMenu;
}
/**
* This method initializes importMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getDirectImportMenuItem() {
if (directImportMenuItem == null) {
directImportMenuItem = new JMenuItem();
directImportMenuItem.setText("Import files...");
directImportMenuItem.setAccelerator(KeyStroke.getKeyStroke('I',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
directImportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.openFileImport();
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return directImportMenuItem;
}
private JMenuItem getImportFromURLMenuItem() {
if (importFromURLMenuItem == null) {
importFromURLMenuItem = new JMenuItem();
importFromURLMenuItem.setText("URL...");
importFromURLMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.openURLImport();
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return importFromURLMenuItem;
}
private JMenuItem getOpenWorkflowMenuItem() {
if (openWorkflowsMenuItem == null) {
openWorkflowsMenuItem = new JMenuItem();
openWorkflowsMenuItem.setText("Open and run...");
openWorkflowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
File workflow = application.openWorkflow();
addRecentWorkflow(workflow);
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return openWorkflowsMenuItem;
}
private void addRecentWorkflow(File file){
if(file != null){ //if the fileChooser is cancelled
//Check if this exists already
for(int i = 0; i < recentWorkflowMenu.getItemCount(); i++){
JMenuItem menuItem = recentWorkflowMenu.getItem(i);
if(menuItem.getText().equals(file.getName())){
recentWorkflowMenu.remove(menuItem);
}
}
recentWorkflowMenu.add(createRunWorkflowMenuItem(file));
}
}
private JMenuItem getImportFromClipboardMenuItem() {
if (importFromClipboardMenuItem == null) {
importFromClipboardMenuItem = new JMenuItem();
importFromClipboardMenuItem.setText("clipboard...");
importFromClipboardMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.openClipboardImport();
} catch (Exception me) {
application.reportException(me);
}
}
});
}
return importFromClipboardMenuItem;
}
private JMenuItem getExportMenuItem() {
if (exportMenuItem == null) {
exportMenuItem = new JMenuItem();
exportMenuItem.setText("Export dataset(s) or folder...");
exportMenuItem.setAccelerator(KeyStroke.getKeyStroke('E',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
// exportMenuItem.setIcon(VisualConstants.EXPORT_MENUICON);
exportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.exportSelectedItems();
}
});
}
return exportMenuItem;
}
/**
* This method initializes quitMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getQuitMenuItem() {
if (quitMenuItem == null) {
quitMenuItem = new JMenuItem();
quitMenuItem.setText("Quit");
quitMenuItem.setAccelerator(KeyStroke.getKeyStroke('Q',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
quitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.quit();
}
});
}
return quitMenuItem;
}
/**
* This method initializes editMenu
*
* @return javax.swing.JMenu
*/
private JMenu getEditMenu() {
if (editMenu == null) {
editMenu = new JMenu();
editMenu.setText("Edit");
editMenu.setMnemonic('E');
editMenu.add(getRenameMenuItem());
editMenu.add(getDeleteMenuItem());
editMenu.add(getHistoryMenuItem());
editMenu.addSeparator();
editMenu.add(getSelectAllMenuItem());
}
return editMenu;
}
private JMenuItem getHistoryMenuItem() {
if (historyMenuItem == null) {
historyMenuItem = new JMenuItem();
historyMenuItem.setText("Show history...");
historyMenuItem.setIcon(VisualConstants.GENERATE_HISTORY_ICON);
historyMenuItem.setAccelerator(KeyStroke.getKeyStroke('H',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
historyMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
DataBean data = application.getSelectionManager().getSelectedDataBean();
if (data != null) {
application.showHistoryScreenFor(data);
}
}
});
}
return historyMenuItem;
}
/**
* This method initializes renameMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getRenameMenuItem() {
if (renameMenuItem == null) {
renameMenuItem = new JMenuItem();
renameMenuItem.setText("Rename selected item...");
renameMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
renameMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
new RenameDialog(application, application.getSelectionManager().getSelectedItem());
}
});
}
return renameMenuItem;
}
/**
* This method initializes deleteMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getDeleteMenuItem() {
if (deleteMenuItem == null) {
deleteMenuItem = new JMenuItem();
deleteMenuItem.setText("Delete selected item");
deleteMenuItem.setIcon(VisualConstants.DELETE_MENUICON);
deleteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.deleteDatas(application.getSelectionManager().getSelectedDataBeans().toArray(new DataItem[0]));
}
});
}
return deleteMenuItem;
}
private JMenuItem getSelectAllMenuItem(){
if(selectAllMenuItem == null) {
selectAllMenuItem = new JMenuItem();
selectAllMenuItem.setText("Select all");
selectAllMenuItem.setAccelerator(KeyStroke.getKeyStroke('A',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
selectAllMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.selectAllItems();
}
});
}
return selectAllMenuItem;
}
/**
* This method initializes wizardMenu
*
* @return javax.swing.JMenu
*/
private JMenu getWizardMenu() {
if (wizardMenu == null) {
wizardMenu = new JMenu();
wizardMenu.setText("Wizard");
wizardMenu.setMnemonic('W');
wizardMenu.add(getWizardMenuItem());
}
return wizardMenu;
}
private JMenu getWorkflowsMenu() {
if (workflowsMenu == null) {
workflowsMenu = new JMenu();
workflowsMenu.setText("Workflow");
workflowsMenu.add(getOpenWorkflowMenuItem());
workflowsMenu.add(getRecentWorkflowMenu());
workflowsMenu.add(getSaveWorkflowMenuItem());
}
return workflowsMenu;
}
private JMenuItem getTaskListMenuItem() {
if (taskListMenuItem == null) {
taskListMenuItem = new JMenuItem();
taskListMenuItem.setText("Tasks...");
taskListMenuItem.setAccelerator(KeyStroke.getKeyStroke('T',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
taskListMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.flipTaskListVisibility(false);
}
});
}
return taskListMenuItem;
}
private JMenuItem getSaveWorkflowMenuItem() {
if (saveWorkflowMenuItem == null) {
saveWorkflowMenuItem = new JMenuItem();
saveWorkflowMenuItem.setText("Save starting from selected...");
saveWorkflowMenuItem.setEnabled(false);
saveWorkflowMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
File workflow = application.saveWorkflow();
addRecentWorkflow(workflow);
}
});
}
return saveWorkflowMenuItem;
}
private JMenu getRecentWorkflowMenu() {
if (recentWorkflowMenu == null) {
recentWorkflowMenu = new JMenu();
recentWorkflowMenu.setText("Run recent");
List<File> workflows = application.getWorkflows();
for (File workflow : workflows) {
addRecentWorkflow(workflow);
}
}
return recentWorkflowMenu;
}
private JMenuItem createRunWorkflowMenuItem(final File scriptName) {
JMenuItem runWorkflowMenuItem = new JMenuItem();
runWorkflowMenuItem.setText(scriptName.getName());
runWorkflowMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.runWorkflow(scriptName);
}
});
return runWorkflowMenuItem;
}
private JMenuItem getWizardMenuItem() {
if (wizardMenuItem == null) {
wizardMenuItem = new JMenuItem();
wizardMenuItem.setText("Affymetrix");
wizardMenuItem.setAccelerator(KeyStroke.getKeyStroke('W',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
wizardMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
WizardPlugin wiz = new WizardPlugin(application);
wiz.show();
}
});
}
return wizardMenuItem;
}
/**
* This method initializes viewMenu
*
* @return javax.swing.JMenu
*/
private JMenu getViewMenu() {
if (viewMenu == null) {
viewMenu = new JMenu();
viewMenu.setText("View");
viewMenu.add(getRestoreViewMenuItem());
viewMenu.addSeparator();
viewMenu.add(getVisualiseMenutItem());
viewMenu.add(getVisualisationwMenu());
viewMenu.addSeparator();
viewMenu.add(getFontSize());
viewMenu.addSeparator();
viewMenu.add(getTaskListMenuItem());
}
return viewMenu;
}
private JMenu getVisualisationwMenu() {
if (visualisationMenu == null) {
visualisationMenu = new JMenu();
visualisationMenu.setText("Visualisation");
visualisationMenu.add(getMaximiseVisualisationMenuItem());
//visualisationMenu.add(getDuplicateMenuItem());
visualisationMenu.add(getDetachMenuItem());
}
return visualisationMenu;
}
private JMenuItem getDetachMenuItem() {
if(detachMenuItem == null){
detachMenuItem = new JMenuItem();
detachMenuItem.setText("Detach");
detachMenuItem.setAccelerator(KeyStroke.getKeyStroke('N',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
detachMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
VisualisationToolBar visToolBar =
application.getVisualisationFrameManager().getVisualisationToolBar();
visToolBar.detach();
}
});
}
return detachMenuItem;
}
// private JMenuItem getDuplicateMenuItem() {
// if(duplicateMenuItem == null){
// duplicateMenuItem = new JMenuItem();
// duplicateMenuItem.setText("Duplicate/Close");
// duplicateMenuItem.setAccelerator(KeyStroke.getKeyStroke('D',
// Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
// duplicateMenuItem.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent e) {
// VisualisationToolBar visToolBar =
// application.getVisualisationFrameManager().getVisualisationToolBar();
// visToolBar.split();
// return duplicateMenuItem;
private JMenuItem getMaximiseVisualisationMenuItem() {
if(maximiseVisualisationMenuItem == null){
maximiseVisualisationMenuItem = new JMenuItem();
maximiseVisualisationMenuItem.setText("Maximise/Restore");
maximiseVisualisationMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0));
maximiseVisualisationMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
VisualisationToolBar visToolBar =
application.getVisualisationFrameManager().getVisualisationToolBar();
visToolBar.maximiseOrRestoreVisualisation();
}
});
}
return maximiseVisualisationMenuItem;
}
private JMenuItem getVisualiseMenutItem() {
if(visualiseMenuItem == null){
visualiseMenuItem = new JMenuItem();
visualiseMenuItem.setText("Visualise selected");
visualiseMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
visualiseMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
application.visualiseWithBestMethod(FrameType.MAIN);
}
});
}
return visualiseMenuItem;
}
/**
* This method initializes restoreViewMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getRestoreViewMenuItem() {
if (restoreViewMenuItem == null) {
restoreViewMenuItem = new JMenuItem();
restoreViewMenuItem.setText("Restore default");
restoreViewMenuItem.setIcon(VisualConstants.DEFAULT_VIEW_MENUICON);
restoreViewMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.restoreDefaultView();
}
});
}
return restoreViewMenuItem;
}
/**
* This method initializes helpInfoMenu. Name was chosen because
* getHelpMenu() causes conflict.
*
* @return javax.swing.JMenu
*/
private JMenu getHelpInfoMenu() {
if (helpInfoMenu == null) {
helpInfoMenu = new JMenu();
helpInfoMenu.setText("Help");
helpInfoMenu.setMnemonic('H');
helpInfoMenu.add(getStartedMenuItem());
helpInfoMenu.add(getContentMenuItem());
helpInfoMenu.add(getAboutMenuItem());
}
return helpInfoMenu;
}
private JMenuItem getLoadOldWorkspaceMenuItem() {
if (loadOldWorkspaceMenuItem == null) {
loadOldWorkspaceMenuItem = new JMenuItem();
loadOldWorkspaceMenuItem.setText("Open workspace (session) saved with Chipster 1.1");
loadOldWorkspaceMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.loadOldSnapshot();
} catch (Exception exp) {
application.reportException(exp);
}
}
});
}
return loadOldWorkspaceMenuItem;
}
private JMenuItem getContentMenuItem() {
if (contentMenuItem == null) {
contentMenuItem = new JMenuItem();
contentMenuItem.setText("User manual");
contentMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
contentMenuItem.setIcon(VisualConstants.HELP_MENUICON);
contentMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp("chipster-manual/index.html");
}
});
}
return contentMenuItem;
}
private JMenuItem getStartedMenuItem() {
if (startedMenuItem == null) {
startedMenuItem = new JMenuItem();
startedMenuItem.setText("Getting started");
startedMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp("chipster-manual/basic-functionality.html");
}
});
}
return startedMenuItem;
}
/**
* This method initializes aboutMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getAboutMenuItem() {
if (aboutMenuItem == null) {
aboutMenuItem = new JMenuItem();
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.viewHelp("chipster-manual/about.html");
}
});
}
return aboutMenuItem;
}
private JMenu getFontSize() {
if (fontSizeMenu == null) {
fontSizeMenu = new JMenu();
fontSizeMenu.setText("Text size");
//FIXME L&F Theme is lost when the font is changed
//fontSizeMenu.setEnabled(false);
JMenuItem norm = new JMenuItem("Normal");
JMenuItem inc = new JMenuItem("Increase");
JMenuItem dec = new JMenuItem("Decrease");
inc.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS,
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
dec.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS,
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
norm.setAccelerator(KeyStroke.getKeyStroke('0',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
fontSizeMenu.add(inc);
fontSizeMenu.add(dec);
fontSizeMenu.addSeparator();
fontSizeMenu.add(norm);
norm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(
VisualConstants.DEFAULT_FONT_SIZE);
}
});
dec.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(
application.getFontSize()-1);
}
});
inc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.setFontSize(
application.getFontSize()+1);
}
});
}
return fontSizeMenu;
}
private JMenuItem getClearSessionMenuItem() {
if(clearSessionMenuItem == null){
clearSessionMenuItem = new JMenuItem();
clearSessionMenuItem.setText("New session");
/*clearSessionMenuItem.setAccelerator(KeyStroke.getKeyStroke('N',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));*/
clearSessionMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
application.clearSession();
}
});
}
return clearSessionMenuItem;
}
private JMenuItem getLoadSnapshotMenuItem() {
if (loadSnapshotMenuItem == null) {
loadSnapshotMenuItem = new JMenuItem();
loadSnapshotMenuItem.setText("Open session...");
loadSnapshotMenuItem.setAccelerator(KeyStroke.getKeyStroke('O',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
loadSnapshotMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
application.loadSession();
} catch (Exception ioe) {
application.reportException(ioe);
}
}
});
}
return loadSnapshotMenuItem;
}
private JMenuItem getSaveSnapshotMenuItem() {
if (saveSnapshotMenuItem == null) {
saveSnapshotMenuItem = new JMenuItem();
saveSnapshotMenuItem.setText("Save session...");
saveSnapshotMenuItem.setAccelerator(KeyStroke.getKeyStroke('S',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ), false));
saveSnapshotMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.saveSession();
}
});
}
return saveSnapshotMenuItem;
}
/**
* This method initializes jMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getAddDirMenuItem() {
if (addDirMenuItem == null) {
addDirMenuItem = new JMenuItem();
addDirMenuItem.setText("Import folder...");
addDirMenuItem.setAccelerator(KeyStroke.getKeyStroke('I',
Toolkit.getDefaultToolkit( ).getMenuShortcutKeyMask( ) | InputEvent.SHIFT_DOWN_MASK, false));
addDirMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
application.openDirectoryImportDialog();
}
});
}
return addDirMenuItem;
}
public void propertyChange(PropertyChangeEvent evt) {
if (evt instanceof DatasetChoiceEvent ||
evt instanceof VisualisationMethodChangedEvent) {
updateMenuStatus();
}
}
} |
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.set;
import java.io.StringReader;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessorAbstract;
import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.buddycloud.channelserver.pubsub.model.NodeAffiliation;
import org.buddycloud.channelserver.pubsub.model.NodeItem;
import org.buddycloud.channelserver.pubsub.model.NodeSubscription;
import org.buddycloud.channelserver.pubsub.subscription.Subscriptions;
import org.buddycloud.channelserver.utils.node.item.payload.Buddycloud;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.SAXReader;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import org.xmpp.resultsetmanagement.ResultSet;
public class ItemDelete extends PubSubElementProcessorAbstract {
private static final Logger LOGGER = Logger.getLogger(ItemDelete.class);
private final BlockingQueue<Packet> outQueue;
private final ChannelManager channelManager;
private String itemId;
private NodeItem nodeItem;
private Element parsedPayload;
public ItemDelete(BlockingQueue<Packet> outQueue,
ChannelManager channelManager) {
this.outQueue = outQueue;
this.channelManager = channelManager;
}
@Override
public void process(Element elm, JID actor, IQ reqIQ, Element rsm)
throws InterruptedException, NodeStoreException {
element = elm;
request = reqIQ;
response = IQ.createResultIQ(request);
node = element.attributeValue("node");
this.actor = actor;
if (null == this.actor) this.actor = request.getFrom();
if (!channelManager.isLocalNode(node)) {
makeRemoteRequest();
return;
}
try {
if (!validNodeProvided() || !nodeExists() || !itemIdProvided()
|| !itemExists() || !validPayload() || !canDelete()) {
outQueue.put(response);
return;
}
deleteReplies();
deleteItem();
outQueue.put(response);
sendNotifications();
return;
} catch (NodeStoreException e) {
logger.error(e);
setErrorCondition(PacketError.Type.wait,
PacketError.Condition.internal_server_error);
} catch (NullPointerException e) {
logger.error(e);
setErrorCondition(PacketError.Type.modify,
PacketError.Condition.bad_request);
} catch (IllegalArgumentException e) {
logger.error(e);
setErrorCondition(PacketError.Type.modify, PacketError.Condition.bad_request);
}
outQueue.put(response);
}
private void deleteReplies() {
if (null == nodeItem.getInReplyTo()) {
return;
}
}
private void sendNotifications() throws NodeStoreException {
try {
String notify = request.getElement().element("pubsub")
.element("retract").attributeValue("notify");
if ((notify != null) && (notify.equals("false") || notify.equals("0"))) {
return;
}
ResultSet<NodeSubscription> subscriptions = channelManager
.getNodeSubscriptionListeners(node);
Message notification = getNotificationMessage();
for (NodeSubscription subscription : subscriptions) {
logger.debug("Subscription [node: " + subscription.getNodeId() + ", listener: "
+ subscription.getListener() + ", subscription: " + subscription.getSubscription() + "]");
if (subscription.getSubscription().equals(
Subscriptions.subscribed)) {
notification.setTo(subscription.getListener());
outQueue.put(notification.createCopy());
}
}
Collection<JID> admins = getAdminUsers();
for (JID admin : admins) {
notification.setTo(admin);
outQueue.put(notification.createCopy());
}
} catch (NullPointerException e) {
logger.error(e);
return;
} catch (InterruptedException e) {
logger.error(e);
return;
}
}
private Message getNotificationMessage() {
Message notification = new Message();
notification.setType(Message.Type.headline);
notification.getElement().addAttribute("remote-server-discover", "false");
Element event = notification.addChildElement("event",
JabberPubsub.NS_PUBSUB_EVENT);
Element items = event.addElement("items");
items.addAttribute("node", node);
Element retract = items.addElement("retract");
retract.addAttribute("id", itemId);
return notification;
}
private void deleteItem() throws NodeStoreException {
channelManager.deleteNodeItemById(node, itemId);
}
private boolean canDelete() throws NodeStoreException {
if (!userOwnsItem() && !userManagesNode()) {
setErrorCondition(PacketError.Type.auth,
PacketError.Condition.forbidden);
return false;
}
return true;
}
private boolean userOwnsItem() {
try {
return parsedPayload.element("author").elementText("name")
.equals(actor.toBareJID());
} catch (NullPointerException e) {
return false;
}
}
private boolean userManagesNode() throws NodeStoreException {
return channelManager.getNodeMembership(node,
actor).getAffiliation().canAuthorize();
}
private boolean validPayload() {
try {
SAXReader xmlReader = new SAXReader();
xmlReader.setMergeAdjacentText(true);
xmlReader.setStringInternEnabled(true);
xmlReader.setStripWhitespaceText(true);
parsedPayload = xmlReader.read(
new StringReader(nodeItem.getPayload())).getRootElement();
return true;
} catch (Exception e) {
LOGGER.error(e);
setErrorCondition(PacketError.Type.wait,
PacketError.Condition.internal_server_error);
return false;
}
}
private boolean itemExists() throws NodeStoreException {
nodeItem = channelManager.getNodeItem(node, itemId);
if (nodeItem != null) {
return true;
}
setErrorCondition(PacketError.Type.cancel,
PacketError.Condition.item_not_found);
return false;
}
private boolean itemIdProvided() {
itemId = request.getElement().element("pubsub").element("retract")
.element("item").attributeValue("id");
if (itemId != null && !itemId.equals("")) {
return true;
}
response.setType(IQ.Type.error);
Element nodeIdRequired = new DOMElement("item-required", new Namespace(
"", JabberPubsub.NS_PUBSUB_ERROR));
Element badRequest = new DOMElement(
PacketError.Condition.bad_request.toXMPP(), new Namespace("",
JabberPubsub.NS_XMPP_STANZAS));
Element error = new DOMElement("error");
error.addAttribute("type", PacketError.Type.modify.toXMPP());
error.add(badRequest);
error.add(nodeIdRequired);
response.setChildElement(error);
return false;
}
private boolean nodeExists() throws NodeStoreException {
if ((false == channelManager.isLocalNode(node))
|| (false == channelManager.nodeExists(node))) {
setErrorCondition(PacketError.Type.cancel,
PacketError.Condition.item_not_found);
return false;
}
return true;
}
private boolean validNodeProvided() {
if (node != null && !node.equals("")) {
return true;
}
response.setType(IQ.Type.error);
Element nodeIdRequired = new DOMElement("nodeid-required",
new Namespace("", JabberPubsub.NS_PUBSUB_ERROR));
Element badRequest = new DOMElement(
PacketError.Condition.bad_request.toXMPP(), new Namespace("",
JabberPubsub.NS_XMPP_STANZAS));
Element error = new DOMElement("error");
error.addAttribute("type", "modify");
error.add(badRequest);
error.add(nodeIdRequired);
response.setChildElement(error);
return false;
}
private void makeRemoteRequest() throws InterruptedException {
request.setTo(new JID(node.split("/")[2]).getDomain());
request.getElement()
.element("pubsub")
.addElement("actor", Buddycloud.NS)
.addText(actor.toBareJID());
outQueue.put(request);
}
public boolean accept(Element elm) {
return elm.getName().equals("retract");
}
} |
package fr.liglab.mining.internals;
import fr.liglab.mining.CountersHandler;
import fr.liglab.mining.CountersHandler.TopLCMCounters;
import fr.liglab.mining.internals.Dataset.TransactionsIterable;
import fr.liglab.mining.internals.Selector.WrongFirstParentException;
import fr.liglab.mining.io.FileFilteredReader;
import fr.liglab.mining.io.FileReader;
import fr.liglab.mining.io.PerItemTopKCollector;
import gnu.trove.map.hash.TIntIntHashMap;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import javax.xml.ws.Holder;
import org.omg.CORBA.IntHolder;
/**
* Represents an LCM recursion step. Its also acts as a Dataset factory.
*/
public final class ExplorationStep implements Cloneable {
public static boolean verbose = false;
public static boolean ultraVerbose = false;
public static boolean LOG_EPSILONS = false;
// expressed in starter items base
public static int INSERT_UNCLOSED_UP_TO_ITEM = Integer.MAX_VALUE;
@SuppressWarnings("boxing")
public static int USE_SPARSE_COUNTERS_FROM_ITEM = Integer.valueOf(System.getProperty("lcm.sparse.from",
Integer.toString(Integer.MAX_VALUE)));
public static boolean INSERT_UNCLOSED_FOR_FUTURE_EXTENSIONS = false;
public static boolean BASELINE_MODE = false;
public final static String KEY_VIEW_SUPPORT_THRESHOLD = "toplcm.threshold.view";
public final static String KEY_LONG_TRANSACTIONS_THRESHOLD = "toplcm.threshold.long";
/**
* @see longTransactionsMode
*/
static int LONG_TRANSACTION_MODE_THRESHOLD = Integer.parseInt(System.getProperty(KEY_LONG_TRANSACTIONS_THRESHOLD,
"2000"));
/**
* When projecting on a item having a support count above
* VIEW_SUPPORT_THRESHOLD%, projection will be a DatasetView
*/
static double VIEW_SUPPORT_THRESHOLD = Double.parseDouble(System.getProperty(KEY_VIEW_SUPPORT_THRESHOLD, "0.15"));
/**
* When set to true we stick to a complete LCMv2 implementation, with
* predictive prefix-preservation tests and compressions at all steps.
* Setting this to false is better when mining top-k-per-item patterns.
*/
public static boolean LCM_STYLE = false;
public static boolean COMPRESS_LVL1 = false;
/**
* Extension item that led to this recursion step. Already included in
* "pattern".
*/
public final int core_item;
public Dataset dataset;
public DatasetProvider datasetProvider;
public final Counters counters;
/**
* Selectors chain - may be null when empty
*/
protected Selector selectChain;
public final FrequentsIterator candidates;
/**
* When an extension fails first-parent test, it ends up in this map. Keys
* are non-first-parent items associated to their actual first parent.
*/
private final TIntIntHashMap failedFPTests;
/**
* Start exploration on a dataset contained in a file.
*
* @param minimumSupport
* @param path
* to an input file in ASCII format. Each line should be a
* transaction containing space-separated item IDs.
*/
public ExplorationStep(int minimumSupport, String path, int k) {
this.core_item = Integer.MAX_VALUE;
this.selectChain = null;
FileReader reader = new FileReader(path);
Holder<int[]> renamingHolder = new Holder<int[]>();
DenseCounters firstCounters = new DenseCounters(minimumSupport, reader, renamingHolder);
this.counters = firstCounters;
reader.close(renamingHolder.value);
Dataset dataset = new Dataset(this.counters, reader, this.counters.getMinSupport(),
this.counters.getMaxFrequent());
this.dataset = dataset;
this.candidates = this.counters.getExtensionsIterator();
this.failedFPTests = new TIntIntHashMap();
this.datasetProvider = new DatasetProvider(this);
ExplorationStep.findUnclosedInsertionBound(firstCounters.getSupportCounts(), minimumSupport + k);
}
protected static void findUnclosedInsertionBound(int[] supportCounts, int supportBound) {
int i = 0;
while (i < supportCounts.length && supportCounts[i] >= supportBound) {
i++;
}
INSERT_UNCLOSED_UP_TO_ITEM = i;
//System.err.println("INSERT_UNCLOSED_UP_TO_ITEM = "+INSERT_UNCLOSED_UP_TO_ITEM);
}
public ExplorationStep(int minimumSupport, FileFilteredReader reader, int maxItem, int[] reverseGlobalRenaming,
Holder<int[]> renaming) {
this.core_item = Integer.MAX_VALUE;
this.selectChain = null;
this.counters = new DenseCounters(minimumSupport, reader, maxItem + 1, null, maxItem + 1,
reverseGlobalRenaming, new int[] {});
renaming.value = this.counters.compressRenaming(reverseGlobalRenaming);
reader.close(renaming.value);
this.dataset = new Dataset(this.counters, reader, this.counters.getMinSupport(), this.counters.getMaxFrequent());
if (this.counters.getPattern().length > 0) {
for (int i = 0; i < this.counters.getPattern().length; i++) {
this.counters.getPattern()[i] = reverseGlobalRenaming[this.counters.getPattern()[i]];
}
}
this.candidates = this.counters.getExtensionsIterator();
this.failedFPTests = new TIntIntHashMap();
}
/**
* Start exploration on one of Hadoop's sub-dataset
*
* @param minimumSupport
* @param transactions
* @param maxItem
* @param reverseRenaming
*/
public ExplorationStep(int minimumSupport, Iterable<TransactionReader> transactions, int maxItem,
int[] reverseRenaming) {
this.core_item = Integer.MAX_VALUE;
this.selectChain = null;
this.counters = new DenseCounters(minimumSupport, transactions.iterator(), maxItem + 1, null, maxItem + 1,
reverseRenaming, new int[] {});
Iterator<TransactionReader> trans = transactions.iterator();
int[] renaming = this.counters.compressRenaming(reverseRenaming);
trans = new TransactionsRenamingDecorator(trans, renaming);
this.dataset = new Dataset(this.counters, trans, this.counters.getMinSupport(), this.counters.getMaxFrequent());
// FIXME
// from here we actually instantiated 3 times the dataset's size
// once in dataset.transactions, one in dataset.tidLists (both are OK)
// and
// worse, once again in transactions.cached
if (this.counters.getPattern().length > 0) {
for (int i = 0; i < this.counters.getPattern().length; i++) {
this.counters.getPattern()[i] = reverseRenaming[this.counters.getPattern()[i]];
}
}
this.candidates = this.counters.getExtensionsIterator();
this.failedFPTests = new TIntIntHashMap();
}
private ExplorationStep(int core_item, Dataset dataset, Counters counters, Selector selectChain,
FrequentsIterator candidates, TIntIntHashMap failedFPTests) {
super();
this.core_item = core_item;
this.dataset = dataset;
this.counters = counters;
this.selectChain = selectChain;
this.candidates = candidates;
this.failedFPTests = failedFPTests;
}
/**
* Finds an extension for current pattern in current dataset and returns the
* corresponding ExplorationStep (extensions are enumerated by ascending
* item IDs - in internal rebasing) Returns null when all valid extensions
* have been generated If it has not been done before, this method will
* perform the preliminary breadth-first exploration
*/
public ExplorationStep next(PerItemTopKCollector collector) {
if (this.candidates == null) {
return null;
}
while (true) {
ExplorationStep res;
int candidate = this.candidates.next();
if (candidate < 0) {
return null;
} else {
res = this.doDepthExplorationFromScratch(candidate, collector);
// / FIXME: isn't this dead code ?
if (LOG_EPSILONS) {
synchronized (System.out) {
if (res != null && res.counters != null && this.counters != null
&& this.counters.getPattern() != null && this.counters.getPattern().length == 0) {
System.out.println(candidate + " " + res.counters.getMinSupport());
}
}
}
}
if (res != null) {
return res;
}
}
}
/*
* No loop here, we need to see that we did the counters for all items, even
* if they fail with fptest for instance
*/
public Counters nextPreprocessed(PerItemTopKCollector collector, IntHolder candidateHolder, IntHolder boundHolder) {
if (this.candidates == null) {
candidateHolder.value = -1;
return null;
}
int candidate = this.candidates.next();
if (candidate < 0) {
candidateHolder.value = -1;
return null;
} else {
candidateHolder.value = candidate;
return this.prepareExploration(candidate, collector, boundHolder);
}
}
/**
* Instantiate state for a valid extension.
*
* @param parent
* @param extension
* a first-parent extension from parent step
* @param candidateCounts
* extension's counters from parent step
* @param support
* previously-computed extension's support
*/
@SuppressWarnings("boxing")
protected ExplorationStep(ExplorationStep parentEs, Dataset parentDataset, int extension, Counters candidateCounts,
TransactionsIterable support) {
this.core_item = extension;
this.counters = candidateCounts;
int[] reverseRenaming = parentEs.counters.getReverseRenaming();
if (verbose) {
if (parentEs.counters.getPattern().length == 0 || ultraVerbose) {
System.err
.format("{\"time\":\"%1$tY/%1$tm/%1$td %1$tk:%1$tM:%1$tS\",\"thread\":%2$d,\"pattern\":%3$s,\"extension_internal\":%4$d,\"extension\":%5$d}\n",
Calendar.getInstance(), Thread.currentThread().getId(),
Arrays.toString(parentEs.counters.getPattern()), extension, reverseRenaming[extension]);
}
}
if (this.counters.getNbFrequents() == 0 || this.counters.getDistinctTransactionsCount() == 0) {
this.candidates = null;
this.failedFPTests = null;
this.selectChain = null;
this.dataset = null;
} else {
this.failedFPTests = new TIntIntHashMap();
this.dataset = instanciateDatasetAndPickSelectors(parentEs, parentDataset, support);
this.candidates = this.counters.getExtensionsIterator();
}
}
private Dataset instanciateDatasetAndPickSelectors(ExplorationStep parentExplorationStep, Dataset parentDataset,
TransactionsIterable support) {
final double supportRate = this.counters.getDistinctTransactionsCount()
/ (double) parentDataset.getStoredTransactionsCount();
final int averageLen = this.counters.getDistinctTransactionLengthSum()
/ this.counters.getDistinctTransactionsCount();
if (averageLen < LONG_TRANSACTION_MODE_THRESHOLD && supportRate > VIEW_SUPPORT_THRESHOLD) {
copySelectChainWithoutFPT(parentExplorationStep.selectChain);
return new DatasetView(parentDataset, this.counters, support, this.core_item,
this.counters.getMinSupport(), this.counters.getMaxFrequent());
} else {
if (averageLen > LONG_TRANSACTION_MODE_THRESHOLD) {
copySelectChainWithFPT(parentExplorationStep.selectChain);
} else {
copySelectChainWithoutFPT(parentExplorationStep.selectChain);
}
final int[] renaming;
renaming = this.counters.compressSortRenaming(null);
TransactionsRenamingDecorator filtered = new TransactionsRenamingDecorator(support.iterator(), renaming);
// FIXME the last argument is now obsolete
Dataset dataset = new Dataset(this.counters, filtered, Integer.MAX_VALUE, this.counters.getMinSupport(),
this.counters.getMaxFrequent());
return dataset;
}
}
private void copySelectChainWithFPT(Selector chain) {
if (chain == null) {
this.selectChain = FirstParentTest.getTailInstance();
} else if (chain.contains(FirstParentTest.class)) {
this.selectChain = chain.copy();
} else {
this.selectChain = chain.append(FirstParentTest.getTailInstance());
}
}
private void copySelectChainWithoutFPT(Selector chain) {
if (chain == null) {
this.selectChain = null;
} else if (chain.contains(FirstParentTest.class)) {
// /// FIXME: this is not really correct
// /// that selectChain stuff is not adapated
this.selectChain = chain.copy(null);
} else {
this.selectChain = chain.copy();
}
}
public int getFailedFPTest(final int item) {
synchronized (this.failedFPTests) {
return this.failedFPTests.get(item);
}
}
private void addFailedFPTest(final int item, final int firstParent) {
synchronized (this.failedFPTests) {
this.failedFPTests.put(item, firstParent);
}
CountersHandler.increment(TopLCMCounters.FailedFPTests);
}
public void appendSelector(Selector s) {
if (this.selectChain == null) {
this.selectChain = s;
} else {
this.selectChain = this.selectChain.append(s);
}
}
public int getCatchedWrongFirstParentCount() {
if (this.failedFPTests == null) {
return 0;
} else {
return this.failedFPTests.size();
}
}
public ExplorationStep copy() {
return new ExplorationStep(core_item, dataset.clone(), counters.clone(), selectChain, candidates, failedFPTests);
}
protected Counters prepareExploration(int candidate, PerItemTopKCollector collector, IntHolder boundHolder) {
return prepareExploration(candidate, collector, boundHolder, false);
}
protected Counters prepareExploration(int candidate, PerItemTopKCollector collector, IntHolder boundHolder,
boolean regeneratedInResume) {
try {
if (selectChain.select(candidate, ExplorationStep.this)) {
Counters candidateCounts;
boolean restart;
boundHolder.value = Math.min(this.counters.getSupportCount(candidate) - collector.getK(),
boundHolder.value);
do {
restart = false;
Dataset suggestedDataset = this.datasetProvider.getDatasetForItem(candidate, boundHolder.value);
TransactionsIterable support = suggestedDataset.getSupport(candidate);
if ((this.counters.pattern == null || this.counters.pattern.length == 0)
&& candidate >= USE_SPARSE_COUNTERS_FROM_ITEM) {
candidateCounts = new SparseCounters(suggestedDataset.getMinSup(), support.iterator(),
candidate, suggestedDataset.getIgnoredItems(), suggestedDataset.getMaxItem(),
counters.getReverseRenaming(), counters.getPattern());
} else {
candidateCounts = new DenseCounters(suggestedDataset.getMinSup(), support.iterator(),
candidate, suggestedDataset.getIgnoredItems(), suggestedDataset.getMaxItem(),
counters.getReverseRenaming(), counters.getPattern());
}
int greatest = Integer.MIN_VALUE;
for (int i = 0; i < candidateCounts.getClosure().length; i++) {
if (candidateCounts.getClosure()[i] > greatest) {
greatest = candidateCounts.getClosure()[i];
}
}
if (greatest > candidate) {
collector.collect(candidateCounts.getTransactionsCount(), candidateCounts.getPattern());
throw new WrongFirstParentException(candidate, greatest);
}
if (!regeneratedInResume) {
collector.collect(candidateCounts.getTransactionsCount(), candidateCounts.getPattern());
}
// this meanse that for candidate <
// INSERT_UNCLOSED_UP_TO_ITEM we always use the dataset of
// minimum support
if (candidate < INSERT_UNCLOSED_UP_TO_ITEM) {
boundHolder.value = candidateCounts.insertUnclosedPatterns(collector,
INSERT_UNCLOSED_FOR_FUTURE_EXTENSIONS);
if (boundHolder.value < suggestedDataset.getMinSup()
&& suggestedDataset.getMinSup() > this.counters.getMinSupport()) {
restart = true;
// says let's switch to the next dataset
CountersHandler.increment(TopLCMCounters.RedoCounters);
boundHolder.value = suggestedDataset.getMinSup() - 1;
}
}
} while (restart);
// here we know that counters are ok for candidate, but not
// necessarily for all items < candidate
return candidateCounts;
}
} catch (WrongFirstParentException e) {
addFailedFPTest(e.extension, e.firstParent);
}
return null;
}
public ExplorationStep resumeExploration(Counters candidateCounts, int candidate, PerItemTopKCollector collector,
int countersMinSupportVerification) {
// check that the counters we made are also ok for all items < candidate
if (candidateCounts.getMinSupport() > countersMinSupportVerification &&
candidateCounts.getMinSupport() > this.counters.getMinSupport()) {
CountersHandler.increment(TopLCMCounters.RedoCounters);
candidateCounts = prepareExploration(candidate, collector, new IntHolder(countersMinSupportVerification),
true);
}
if (candidate < INSERT_UNCLOSED_UP_TO_ITEM) {
candidateCounts.raiseMinimumSupport(collector, !BASELINE_MODE);
if (LOG_EPSILONS) {
synchronized (System.out) {
if (this.counters != null && this.counters.getPattern() != null
&& this.counters.getPattern().length == 0) {
System.out.println(candidate + " " + candidateCounts.getMinSupport());
}
}
}
}
Dataset dataset = this.datasetProvider.getDatasetForSupportThreshold(candidateCounts.getMinSupport());
ExplorationStep next = new ExplorationStep(this, dataset, candidate, candidateCounts,
dataset.getSupport(candidate));
return next;
}
protected ExplorationStep doDepthExplorationFromScratch(int candidate, PerItemTopKCollector collector) {
try {
if (selectChain.select(candidate, ExplorationStep.this)) {
TransactionsIterable support = dataset.getSupport(candidate);
Counters candidateCounts;
if ((this.counters.pattern == null || this.counters.pattern.length == 0)
&& candidate >= USE_SPARSE_COUNTERS_FROM_ITEM) {
candidateCounts = new SparseCounters(counters.getMinSupport(), support.iterator(), candidate,
dataset.getIgnoredItems(), counters.getMaxFrequent(), counters.getReverseRenaming(),
counters.getPattern());
} else {
candidateCounts = new DenseCounters(counters.getMinSupport(), support.iterator(), candidate,
dataset.getIgnoredItems(), counters.getMaxFrequent(), counters.getReverseRenaming(),
counters.getPattern());
}
int greatest = Integer.MIN_VALUE;
for (int i = 0; i < candidateCounts.getClosure().length; i++) {
if (candidateCounts.getClosure()[i] > greatest) {
greatest = candidateCounts.getClosure()[i];
}
}
if (greatest > candidate) {
collector.collect(candidateCounts.getTransactionsCount(), candidateCounts.getPattern());
throw new WrongFirstParentException(candidate, greatest);
}
collector.collect(candidateCounts.getTransactionsCount(), candidateCounts.getPattern());
// not inserting unclosed patterns on purpose, we are not at a
// starter
// not even raising minimum support, that's how crazy we are
// if we're here we're either not a starter or a starter that's
// not likely to fill its topk
// candidateCounts.raiseMinimumSupport(collector,
// !BASELINE_MODE);
ExplorationStep next = new ExplorationStep(this, this.dataset, candidate, candidateCounts, support);
return next;
}
} catch (WrongFirstParentException e) {
addFailedFPTest(e.extension, e.firstParent);
}
return null;
}
} |
package org.spongepowered.api.data.manipulator.immutable.tileentity;
import org.spongepowered.api.block.tileentity.Banner;
import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.mutable.tileentity.BannerData;
import org.spongepowered.api.data.meta.PatternLayer;
import org.spongepowered.api.data.value.immutable.ImmutablePatternListValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.type.DyeColor;
/**
* An {@link ImmutableDataManipulator} handling the various information for a
* {@link Banner} including the {@link PatternLayer}s that customize the
* {@link Banner}.
*/
public interface ImmutableBannerData extends ImmutableDataManipulator<ImmutableBannerData, BannerData> {
/**
* Gets the {@link ImmutableValue} for the base {@link DyeColor}.
*
* @return The immutable value for the base color
*/
ImmutableValue<DyeColor> baseColor();
/**
* Gets the {@link ImmutablePatternListValue} of all patterns for the
* {@link Banner}.
*
* @return The immutable pattern list
*/
ImmutablePatternListValue patterns();
} |
package info.faceland.strife.menus;
import com.tealcube.minecraft.bukkit.TextUtils;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import info.faceland.strife.stats.StrifeStat;
import ninja.amp.ampmenus.events.ItemClickEvent;
import ninja.amp.ampmenus.items.MenuItem;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Wool;
import java.util.ArrayList;
import java.util.List;
public class LevelupMenuItem extends MenuItem {
private final StrifePlugin plugin;
private final StrifeStat stat;
public LevelupMenuItem(StrifePlugin plugin, StrifeStat strifeStat) {
super(strifeStat.getChatColor() + strifeStat.getName(), new Wool().toItemStack(),
TextUtils.color(strifeStat.getDescription()).split("/n"));
this.plugin = plugin;
this.stat = strifeStat;
}
@Override
public ItemStack getFinalIcon(Player player) {
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
int level = champion.getLevel(stat);
ItemStack itemStack;
if (level != 0) {
itemStack = new Wool(stat.getDyeColor()).toItemStack(Math.min(level, 64));
} else {
itemStack = new Wool(DyeColor.GRAY).toItemStack(1);
}
ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
itemMeta.setDisplayName(getDisplayName() + " [" + level + "/" + champion.getMaximumStatLevel() + "]");
List<String> lore = new ArrayList<>(getLore());
if (champion.getUnusedStatPoints() == 0) {
lore.add(ChatColor.RED + "No unused points.");
} else if (level >= champion.getMaximumStatLevel()) {
lore.add(ChatColor.RED + "Point cap reached.");
} else {
lore.add(ChatColor.YELLOW + "Click to upgrade!");
}
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
return itemStack;
}
@Override
public void onItemClick(ItemClickEvent event) {
super.onItemClick(event);
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
if (champion.getUnusedStatPoints() < 1) {
return;
}
int currentLevel = champion.getLevel(stat);
if (currentLevel + 1 > champion.getMaximumStatLevel()) {
return;
}
champion.setLevel(stat, currentLevel + 1);
champion.setUnusedStatPoints(champion.getUnusedStatPoints() - 1);
plugin.getChampionManager().removeChampion(champion.getUniqueId());
plugin.getChampionManager().addChampion(champion);
champion.getStatAttributeValues();
champion.getCache().recombine();
AttributeHandler.updateHealth(champion.getPlayer(), champion.getCache().getAttribute(StrifeAttribute.HEALTH));
event.setWillUpdate(true);
}
} |
package org.carlspring.strongbox.security.certificates;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class KeyStores
{
private static final ProxyAuthenticator authenticator = new ProxyAuthenticator();
static
{
Authenticator.setDefault(authenticator);
}
private static KeyStore load(final File fileName,
final char[] password)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException
{
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
if (fileName == null)
{
keyStore.load(null, password);
return keyStore;
}
final InputStream is = new FileInputStream(fileName);
try
{
keyStore.load(is, password);
return keyStore;
}
finally
{
is.close();
}
}
private static KeyStore store(final File fileName,
final char[] password,
final KeyStore keyStore)
throws IOException,
CertificateException,
NoSuchAlgorithmException,
KeyStoreException
{
final OutputStream os = new FileOutputStream(fileName);
try
{
keyStore.store(os, password);
return keyStore;
}
finally
{
os.close();
}
}
public static KeyStore createNew(final File fileName,
final char[] password)
throws KeyStoreException,
CertificateException,
NoSuchAlgorithmException,
IOException
{
return store(fileName, password, load(null, password));
}
public static KeyStore changePassword(final File fileName,
final char[] oldPassword,
final char[] newPassword)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException
{
return store(fileName, newPassword, load(fileName, oldPassword));
}
public static Map<String, Certificate> listCertificates(final File fileName,
final char[] password)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException
{
final KeyStore keyStore = load(fileName, password);
final Map<String, Certificate> certificates = new HashMap<String, Certificate>();
final Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements())
{
final String alias = aliases.nextElement();
certificates.put(alias, keyStore.getCertificate(alias));
}
return certificates;
}
public static KeyStore removeCertificates(final File fileName,
final char[] password,
final InetAddress host,
final int port)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException
{
final KeyStore keyStore = load(fileName, password);
final String prefix = host.getCanonicalHostName() + ":" + Integer.toString(port);
final Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements())
{
final String alias = aliases.nextElement();
if (alias.startsWith(prefix))
{
keyStore.deleteEntry(alias);
}
}
return store(fileName, password, keyStore);
}
public static KeyStore addCertificates(final File fileName,
final char[] password,
final InetAddress host,
final int port)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException,
KeyManagementException
{
final KeyStore keyStore = load(fileName, password);
final String prefix = host.getCanonicalHostName() + ":" + Integer.toString(port);
final X509Certificate [] chain = remoteCertificateChain(host, port);
for (final X509Certificate cert : chain)
{
keyStore.setCertificateEntry(prefix + "_" + cert.getSubjectDN().getName(), cert);
}
return store(fileName, password, keyStore);
}
public static KeyStore addHttpsCertificates(final File fileName,
final char[] password,
final Proxy httpProxy,
final PasswordAuthentication credentials,
final String host,
final int port)
throws CertificateException,
NoSuchAlgorithmException,
KeyStoreException,
IOException,
KeyManagementException
{
final KeyStore keyStore = load(fileName, password);
final String prefix = host + ":" + Integer.toString(port);
final ChainCaptureTrustManager tm = new ChainCaptureTrustManager();
final SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ tm }, null);
final URL url = new URL("https", host, port, "/");
final HttpsURLConnection conn = (HttpsURLConnection) (httpProxy != null ?
url.openConnection(httpProxy) :
url.openConnection());
conn.setSSLSocketFactory(ctx.getSocketFactory());
if (credentials != null)
{
ProxyAuthenticator.credentials.set(credentials);
}
try
{
conn.connect();
for (final X509Certificate cert : tm.chain)
{
keyStore.setCertificateEntry(prefix + "_" + cert.getSubjectDN().getName(), cert);
}
return store(fileName, password, keyStore);
}
finally
{
ProxyAuthenticator.credentials.remove();
conn.disconnect();
}
}
public static KeyStore addSslCertificates(final File fileName,
final char[] password,
final Proxy socksProxy,
final PasswordAuthentication credentials,
final String host,
final int port)
throws KeyStoreException,
IOException,
CertificateException,
NoSuchAlgorithmException,
KeyManagementException
{
final KeyStore keyStore = load(fileName, password);
final String prefix = host + ":" + Integer.toString(port);
final X509Certificate [] chain = remoteCertificateChain(socksProxy, credentials, host, port);
for (final X509Certificate cert : chain)
{
keyStore.setCertificateEntry(prefix + "_" + cert.getSubjectDN().getName(), cert);
}
return store(fileName, password, keyStore);
}
private static X509Certificate[] remoteCertificateChain(final InetAddress address,
final int port)
throws NoSuchAlgorithmException,
IOException,
KeyStoreException,
KeyManagementException
{
final ChainCaptureTrustManager tm = new ChainCaptureTrustManager();
final SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ tm }, null);
final SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket(address, port);
try
{
socket.startHandshake();
socket.close();
}
catch (final SSLException ignore) // non trusted certificates should be returned as well
{
}
return tm.chain;
}
private static X509Certificate[] remoteCertificateChain(final Proxy socksProxy,
final PasswordAuthentication credentials,
final String host,
final int port)
throws NoSuchAlgorithmException,
IOException,
KeyStoreException,
KeyManagementException
{
final ChainCaptureTrustManager tm = new ChainCaptureTrustManager();
final SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ tm }, null);
if (credentials != null)
{
ProxyAuthenticator.credentials.set(credentials);
}
final Socket proxySocket = socksProxy != null ? new Socket(socksProxy) : null;
if (proxySocket != null)
{
proxySocket.connect(new InetSocketAddress(host, port));
}
try
{
handshake(ctx, proxySocket, host, port);
return tm.chain;
}
finally
{
ProxyAuthenticator.credentials.remove();
if (proxySocket != null && !proxySocket.isClosed())
{
proxySocket.close();
}
}
}
private static void handshake(final SSLContext ctx,
final Socket proxySocket,
final String host,
final int port) throws IOException
{
final SSLSocket socket = (SSLSocket)(proxySocket == null ?
ctx.getSocketFactory().createSocket(host, port) :
ctx.getSocketFactory().createSocket(proxySocket, host, port, true));
try
{
socket.startHandshake();
}
catch (final SSLException ignore) // non trusted certificates should be returned as well
{
}
finally
{
socket.close();
}
}
private static class ChainCaptureTrustManager
implements X509TrustManager
{
private X509Certificate[] chain;
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(final X509Certificate[] chain,
final String authType)
throws CertificateException
{
throw new UnsupportedOperationException();
}
@Override
public void checkServerTrusted(final X509Certificate[] chain,
final String authType)
throws CertificateException
{
this.chain = chain;
}
}
private static class ProxyAuthenticator
extends Authenticator
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return credentials.get();
}
static final ThreadLocal<PasswordAuthentication> credentials = new ThreadLocal<PasswordAuthentication>();
}
} |
package io.mycat.config.loader.xml;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;
import io.mycat.config.model.rule.RuleConfig;
import io.mycat.route.function.TableRuleAware;
import io.mycat.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.config.loader.SchemaLoader;
import io.mycat.config.model.DBHostConfig;
import io.mycat.config.model.DataHostConfig;
import io.mycat.config.model.DataNodeConfig;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.TableConfig;
import io.mycat.config.model.TableConfigMap;
import io.mycat.config.model.rule.TableRuleConfig;
import io.mycat.config.util.ConfigException;
import io.mycat.config.util.ConfigUtil;
import io.mycat.route.function.AbstractPartitionAlgorithm;
import io.mycat.util.DecryptUtil;
import io.mycat.util.SplitUtil;
/**
* @author mycat
*/
@SuppressWarnings("unchecked")
public class XMLSchemaLoader implements SchemaLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(XMLSchemaLoader.class);
private final static String DEFAULT_DTD = "/schema.dtd";
private final static String DEFAULT_XML = "/schema.xml";
private final Map<String, TableRuleConfig> tableRules;
private final Map<String, DataHostConfig> dataHosts;
private final Map<String, DataNodeConfig> dataNodes;
private final Map<String, SchemaConfig> schemas;
public XMLSchemaLoader(String schemaFile, String ruleFile) {
//rule.xml
XMLRuleLoader ruleLoader = new XMLRuleLoader(ruleFile);
//tableRulesSchemarule
this.tableRules = ruleLoader.getTableRules();
//ruleLoader
ruleLoader = null;
this.dataHosts = new HashMap<String, DataHostConfig>();
this.dataNodes = new HashMap<String, DataNodeConfig>();
this.schemas = new HashMap<String, SchemaConfig>();
//schema
this.load(DEFAULT_DTD, schemaFile == null ? DEFAULT_XML : schemaFile);
}
public XMLSchemaLoader() {
this(null, null);
}
@Override
public Map<String, TableRuleConfig> getTableRules() {
return tableRules;
}
@Override
public Map<String, DataHostConfig> getDataHosts() {
return (Map<String, DataHostConfig>) (dataHosts.isEmpty() ? Collections.emptyMap() : dataHosts);
}
@Override
public Map<String, DataNodeConfig> getDataNodes() {
return (Map<String, DataNodeConfig>) (dataNodes.isEmpty() ? Collections.emptyMap() : dataNodes);
}
@Override
public Map<String, SchemaConfig> getSchemas() {
return (Map<String, SchemaConfig>) (schemas.isEmpty() ? Collections.emptyMap() : schemas);
}
private void load(String dtdFile, String xmlFile) {
InputStream dtd = null;
InputStream xml = null;
try {
dtd = XMLSchemaLoader.class.getResourceAsStream(dtdFile);
xml = XMLSchemaLoader.class.getResourceAsStream(xmlFile);
Element root = ConfigUtil.getDocument(dtd, xml).getDocumentElement();
//DataHost
loadDataHosts(root);
//DataNode
loadDataNodes(root);
//Schema
loadSchemas(root);
} catch (ConfigException e) {
throw e;
} catch (Exception e) {
throw new ConfigException(e);
} finally {
if (dtd != null) {
try {
dtd.close();
} catch (IOException e) {
}
}
if (xml != null) {
try {
xml.close();
} catch (IOException e) {
}
}
}
}
private void loadSchemas(Element root) {
NodeList list = root.getElementsByTagName("schema");
for (int i = 0, n = list.getLength(); i < n; i++) {
Element schemaElement = (Element) list.item(i);
String name = schemaElement.getAttribute("name");
String dataNode = schemaElement.getAttribute("dataNode");
String checkSQLSchemaStr = schemaElement.getAttribute("checkSQLschema");
String sqlMaxLimitStr = schemaElement.getAttribute("sqlMaxLimit");
int sqlMaxLimit = -1;
//sql
if (sqlMaxLimitStr != null && !sqlMaxLimitStr.isEmpty()) {
sqlMaxLimit = Integer.parseInt(sqlMaxLimitStr);
}
// check dataNode already exists or not,schemadatanode
String defaultDbType = null;
//dataNode
if (dataNode != null && !dataNode.isEmpty()) {
List<String> dataNodeLst = new ArrayList<String>(1);
dataNodeLst.add(dataNode);
checkDataNodeExists(dataNodeLst);
String dataHost = dataNodes.get(dataNode).getDataHost();
defaultDbType = dataHosts.get(dataHost).getDbType();
} else {
dataNode = null;
}
//schematables
Map<String, TableConfig> tables = loadTables(schemaElement);
//schema
if (schemas.containsKey(name)) {
throw new ConfigException("schema " + name + " duplicated!");
}
// tabledataNodetabledataNode
if (dataNode == null && tables.size() == 0) {
throw new ConfigException(
"schema " + name + " didn't config tables,so you must set dataNode property!");
}
SchemaConfig schemaConfig = new SchemaConfig(name, dataNode,
tables, sqlMaxLimit, "true".equalsIgnoreCase(checkSQLSchemaStr));
//DBsql
if (defaultDbType != null) {
schemaConfig.setDefaultDataNodeDbType(defaultDbType);
if (!"mysql".equalsIgnoreCase(defaultDbType)) {
schemaConfig.setNeedSupportMultiDBType(true);
}
}
// mysql
for (TableConfig tableConfig : tables.values()) {
if (isHasMultiDbType(tableConfig)) {
schemaConfig.setNeedSupportMultiDBType(true);
break;
}
}
//dataNodeDB
Map<String, String> dataNodeDbTypeMap = new HashMap<>();
for (String dataNodeName : dataNodes.keySet()) {
DataNodeConfig dataNodeConfig = dataNodes.get(dataNodeName);
String dataHost = dataNodeConfig.getDataHost();
DataHostConfig dataHostConfig = dataHosts.get(dataHost);
if (dataHostConfig != null) {
String dbType = dataHostConfig.getDbType();
dataNodeDbTypeMap.put(dataNodeName, dbType);
}
}
schemaConfig.setDataNodeDbTypeMap(dataNodeDbTypeMap);
schemas.put(name, schemaConfig);
}
}
/**
* , YYYYMMYYYYMMDD
*
* YYYYMM yyyymm,2015,01,60
* YYYYMMDD: yyyymmdd,2015,01,10,50
*
* @param tableNameElement
* @param tableNameSuffixElement
* @return
*/
private String doTableNameSuffix(String tableNameElement, String tableNameSuffixElement) {
String newTableName = tableNameElement;
String[] params = tableNameSuffixElement.split(",");
String suffixFormat = params[0].toUpperCase();
if ( suffixFormat.equals("YYYYMM") ) {
int yyyy = Integer.parseInt( params[1] );
int mm = Integer.parseInt( params[2] );
int mmEndIdx = Integer.parseInt( params[3] );
SimpleDateFormat yyyyMMSDF = new SimpleDateFormat("yyyyMM");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, yyyy );
cal.set(Calendar.MONTH, mm - 1 );
cal.set(Calendar.DATE, 0 );
StringBuffer tableNameBuffer = new StringBuffer();
for(int mmIdx = 0; mmIdx <= mmEndIdx; mmIdx++) {
tableNameBuffer.append( tableNameElement );
tableNameBuffer.append( yyyyMMSDF.format(cal.getTime()) );
cal.add(Calendar.MONTH, 1);
if ( mmIdx != mmEndIdx) {
tableNameBuffer.append(",");
}
}
newTableName = tableNameBuffer.toString();
} else if ( suffixFormat.equals("YYYYMMDD") ) {
int yyyy = Integer.parseInt( params[1] );
int mm = Integer.parseInt( params[2] );
int dd = Integer.parseInt( params[3] );
int ddEndIdx = Integer.parseInt( params[4] );
SimpleDateFormat yyyyMMddSDF = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, yyyy );
cal.set(Calendar.MONTH, mm - 1 );
cal.set(Calendar.DATE, dd );
StringBuffer tableNameBuffer = new StringBuffer();
for(int ddIdx = 0; ddIdx <= ddEndIdx; ddIdx++) {
tableNameBuffer.append( tableNameElement );
tableNameBuffer.append( yyyyMMddSDF.format(cal.getTime()) );
cal.add(Calendar.DATE, 1);
if ( ddIdx != ddEndIdx) {
tableNameBuffer.append(",");
}
}
newTableName = tableNameBuffer.toString();
}
return newTableName;
}
private Map<String, TableConfig> loadTables(Element node) {
// Map<String, TableConfig> tables = new HashMap<String, TableConfig>();
// [`] BEN GONG
Map<String, TableConfig> tables = new TableConfigMap();
NodeList nodeList = node.getElementsByTagName("table");
for (int i = 0; i < nodeList.getLength(); i++) {
Element tableElement = (Element) nodeList.item(i);
String tableNameElement = tableElement.getAttribute("name").toUpperCase();
//TODO:,
String tableNameSuffixElement = tableElement.getAttribute("nameSuffix").toUpperCase();
if ( !"".equals( tableNameSuffixElement ) ) {
if( tableNameElement.split(",").length > 1 ) {
throw new ConfigException("nameSuffix " + tableNameSuffixElement + ", require name parameter cannot multiple breaks!");
}
tableNameElement = doTableNameSuffix(tableNameElement, tableNameSuffixElement);
}
String[] tableNames = tableNameElement.split(",");
String primaryKey = tableElement.hasAttribute("primaryKey") ? tableElement.getAttribute("primaryKey").toUpperCase() : null;
//sequence handler
boolean autoIncrement = false;
if (tableElement.hasAttribute("autoIncrement")) {
autoIncrement = Boolean.parseBoolean(tableElement.getAttribute("autoIncrement"));
}
boolean needAddLimit = true;
if (tableElement.hasAttribute("needAddLimit")) {
needAddLimit = Boolean.parseBoolean(tableElement.getAttribute("needAddLimit"));
}
//typeglobal
String tableTypeStr = tableElement.hasAttribute("type") ? tableElement.getAttribute("type") : null;
int tableType = TableConfig.TYPE_GLOBAL_DEFAULT;
if ("global".equalsIgnoreCase(tableTypeStr)) {
tableType = TableConfig.TYPE_GLOBAL_TABLE;
}
//dataNodedataNode
String dataNode = tableElement.getAttribute("dataNode");
TableRuleConfig tableRule = null;
if (tableElement.hasAttribute("rule")) {
String ruleName = tableElement.getAttribute("rule");
tableRule = tableRules.get(ruleName);
if (tableRule == null) {
throw new ConfigException("rule " + ruleName + " is not found!");
}
}
boolean ruleRequired = false;
if (tableElement.hasAttribute("ruleRequired")) {
ruleRequired = Boolean.parseBoolean(tableElement.getAttribute("ruleRequired"));
}
if (tableNames == null) {
throw new ConfigException("table name is not found!");
}
//distributedataNode
String distPrex = "distribute(";
boolean distTableDns = dataNode.startsWith(distPrex);
if (distTableDns) {
dataNode = dataNode.substring(distPrex.length(), dataNode.length() - 1);
}
String subTables = tableElement.getAttribute("subTables");
for (int j = 0; j < tableNames.length; j++) {
String tableName = tableNames[j];
TableRuleConfig tableRuleConfig=tableRule ;
if(tableRuleConfig!=null) {
//TableRuleAwarefunction
RuleConfig rule= tableRuleConfig.getRule();
if(rule.getRuleAlgorithm() instanceof TableRuleAware) {
tableRuleConfig = (TableRuleConfig) ObjectUtil.copyObject(tableRuleConfig);
tableRules.remove(tableRuleConfig.getName()) ;
String newRuleName = tableRuleConfig.getName() + "_" + tableName;
tableRuleConfig. setName(newRuleName);
TableRuleAware tableRuleAware= (TableRuleAware) tableRuleConfig.getRule().getRuleAlgorithm();
tableRuleAware.setRuleName(newRuleName);
tableRuleAware.setTableName(tableName);
tableRuleConfig.getRule().getRuleAlgorithm().init();
tableRules.put(newRuleName,tableRuleConfig);
}
}
TableConfig table = new TableConfig(tableName, primaryKey,
autoIncrement, needAddLimit, tableType, dataNode,
getDbType(dataNode),
(tableRuleConfig != null) ? tableRuleConfig.getRule() : null,
ruleRequired, null, false, null, null,subTables);
checkDataNodeExists(table.getDataNodes());
if(table.getRule() != null) {
checkRuleSuitTable(table);
}
if (distTableDns) {
distributeDataNodes(table.getDataNodes());
}
if (tables.containsKey(table.getName())) {
throw new ConfigException("table " + tableName + " duplicated!");
}
//map
tables.put(table.getName(), table);
}
//tableName
if (tableNames.length == 1) {
TableConfig table = tables.get(tableNames[0]);
// process child tables
processChildTables(tables, table, dataNode, tableElement);
}
}
return tables;
}
/**
* distribute datanodes in multi hosts,means ,dn1 (host1),dn100
* (host2),dn300(host3),dn2(host1),dn101(host2),dn301(host3)...etc
* hostdatanodehosthost1dn1,dn2host2dn100dn101host3dn300dn301,
* host 0->dn1 (host1),1->dn100(host2),2->dn300(host3),3->dn2(host1),4->dn101(host2),5->dn301(host3)
*
* @param theDataNodes
*/
private void distributeDataNodes(ArrayList<String> theDataNodes) {
Map<String, ArrayList<String>> newDataNodeMap = new HashMap<String, ArrayList<String>>(dataHosts.size());
for (String dn : theDataNodes) {
DataNodeConfig dnConf = dataNodes.get(dn);
String host = dnConf.getDataHost();
ArrayList<String> hostDns = newDataNodeMap.get(host);
hostDns = (hostDns == null) ? new ArrayList<String>() : hostDns;
hostDns.add(dn);
newDataNodeMap.put(host, hostDns);
}
ArrayList<String> result = new ArrayList<String>(theDataNodes.size());
boolean hasData = true;
while (hasData) {
hasData = false;
for (ArrayList<String> dns : newDataNodeMap.values()) {
if (!dns.isEmpty()) {
result.add(dns.remove(0));
hasData = true;
}
}
}
theDataNodes.clear();
theDataNodes.addAll(result);
}
private Set<String> getDbType(String dataNode) {
Set<String> dbTypes = new HashSet<>();
String[] dataNodeArr = SplitUtil.split(dataNode, ',', '$', '-');
for (String node : dataNodeArr) {
DataNodeConfig datanode = dataNodes.get(node);
DataHostConfig datahost = dataHosts.get(datanode.getDataHost());
dbTypes.add(datahost.getDbType());
}
return dbTypes;
}
private Set<String> getDataNodeDbTypeMap(String dataNode) {
Set<String> dbTypes = new HashSet<>();
String[] dataNodeArr = SplitUtil.split(dataNode, ',', '$', '-');
for (String node : dataNodeArr) {
DataNodeConfig datanode = dataNodes.get(node);
DataHostConfig datahost = dataHosts.get(datanode.getDataHost());
dbTypes.add(datahost.getDbType());
}
return dbTypes;
}
private boolean isHasMultiDbType(TableConfig table) {
Set<String> dbTypes = table.getDbTypes();
for (String dbType : dbTypes) {
if (!"mysql".equalsIgnoreCase(dbType)) {
return true;
}
}
return false;
}
private void processChildTables(Map<String, TableConfig> tables,
TableConfig parentTable, String dataNodes, Element tableNode) {
// parse child tables
NodeList childNodeList = tableNode.getChildNodes();
for (int j = 0; j < childNodeList.getLength(); j++) {
Node theNode = childNodeList.item(j);
if (!theNode.getNodeName().equals("childTable")) {
continue;
}
Element childTbElement = (Element) theNode;
String cdTbName = childTbElement.getAttribute("name").toUpperCase();
String primaryKey = childTbElement.hasAttribute("primaryKey") ? childTbElement.getAttribute("primaryKey").toUpperCase() : null;
boolean autoIncrement = false;
if (childTbElement.hasAttribute("autoIncrement")) {
autoIncrement = Boolean.parseBoolean(childTbElement.getAttribute("autoIncrement"));
}
boolean needAddLimit = true;
if (childTbElement.hasAttribute("needAddLimit")) {
needAddLimit = Boolean.parseBoolean(childTbElement.getAttribute("needAddLimit"));
}
String subTables = childTbElement.getAttribute("subTables");
//joinparent
String joinKey = childTbElement.getAttribute("joinKey").toUpperCase();
String parentKey = childTbElement.getAttribute("parentKey").toUpperCase();
TableConfig table = new TableConfig(cdTbName, primaryKey,
autoIncrement, needAddLimit,
TableConfig.TYPE_GLOBAL_DEFAULT, dataNodes,
getDbType(dataNodes), null, false, parentTable, true,
joinKey, parentKey, subTables);
if (tables.containsKey(table.getName())) {
throw new ConfigException("table " + table.getName() + " duplicated!");
}
tables.put(table.getName(), table);
processChildTables(tables, table, dataNodes, childTbElement);
}
}
private void checkDataNodeExists(Collection<String> nodes) {
if (nodes == null || nodes.size() < 1) {
return;
}
for (String node : nodes) {
if (!dataNodes.containsKey(node)) {
throw new ConfigException("dataNode '" + node + "' is not found!");
}
}
}
/**
* , dataNode<br>
* :<br>
* {@code
* <table name="hotnews" primaryKey="ID" autoIncrement="true" dataNode="dn1,dn2"
rule="mod-long" />
* }
* <br>
* :<br>
* {@code
* <function name="mod-long" class="io.mycat.route.function.PartitionByMod">
<!-- how many data nodes -->
<property name="count">3</property>
</function>
* }
* <br>
* shard table datanode(2) < function count(3)
*/
private void checkRuleSuitTable(TableConfig tableConf) {
AbstractPartitionAlgorithm function = tableConf.getRule().getRuleAlgorithm();
int suitValue = function.suitableFor(tableConf);
switch(suitValue) {
case -1:
throw new ConfigException("Illegal table conf : table [ " + tableConf.getName() + " ] rule function [ "
+ tableConf.getRule().getFunctionName() + " ] partition size : " + tableConf.getRule().getRuleAlgorithm().getPartitionNum() + " > table datanode size : "
+ tableConf.getDataNodes().size() + ", please make sure table datanode size = function partition size");
case 0:
// table datanode size == rule function partition size
break;
case 1:
// ,warn log
LOGGER.warn("table conf : table [ {} ] rule function [ {} ] partition size : {} < table datanode size : {} , this cause some datanode to be redundant",
new String[]{
tableConf.getName(),
tableConf.getRule().getFunctionName(),
String.valueOf(tableConf.getRule().getRuleAlgorithm().getPartitionNum()),
String.valueOf(tableConf.getDataNodes().size())
});
break;
}
}
private void loadDataNodes(Element root) {
//DataNode
NodeList list = root.getElementsByTagName("dataNode");
for (int i = 0, n = list.getLength(); i < n; i++) {
Element element = (Element) list.item(i);
String dnNamePre = element.getAttribute("name");
String databaseStr = element.getAttribute("database");
String host = element.getAttribute("dataHost");
if (empty(dnNamePre) || empty(databaseStr) || empty(host)) {
throw new ConfigException("dataNode " + dnNamePre + " define error ,attribute can't be empty");
}
//dnNamesname,databasesdatabase,hostStringsdataHost',', '$', '-'database*dataHost=name
//dataHostdatabasedataHostdatabase
//<dataNode name="dn1$0-75" dataHost="localhost$1-10" database="db$0-759" />
//localhost1dn1$0-75,localhost2dn1$0-75db$76-151
String[] dnNames = io.mycat.util.SplitUtil.split(dnNamePre, ',', '$', '-');
String[] databases = io.mycat.util.SplitUtil.split(databaseStr, ',', '$', '-');
String[] hostStrings = io.mycat.util.SplitUtil.split(host, ',', '$', '-');
if (dnNames.length > 1 && dnNames.length != databases.length * hostStrings.length) {
throw new ConfigException("dataNode " + dnNamePre
+ " define error ,dnNames.length must be=databases.length*hostStrings.length");
}
if (dnNames.length > 1) {
List<String[]> mhdList = mergerHostDatabase(hostStrings, databases);
for (int k = 0; k < dnNames.length; k++) {
String[] hd = mhdList.get(k);
String dnName = dnNames[k];
String databaseName = hd[1];
String hostName = hd[0];
createDataNode(dnName, databaseName, hostName);
}
} else {
createDataNode(dnNamePre, databaseStr, host);
}
}
}
/**
* DataHostDatabaseDataHostDatabase
* @param hostStrings
* @param databases
* @return
*/
private List<String[]> mergerHostDatabase(String[] hostStrings, String[] databases) {
List<String[]> mhdList = new ArrayList<>();
for (int i = 0; i < hostStrings.length; i++) {
String hostString = hostStrings[i];
for (int i1 = 0; i1 < databases.length; i1++) {
String database = databases[i1];
String[] hd = new String[2];
hd[0] = hostString;
hd[1] = database;
mhdList.add(hd);
}
}
return mhdList;
}
private void createDataNode(String dnName, String database, String host) {
DataNodeConfig conf = new DataNodeConfig(dnName, database, host);
if (dataNodes.containsKey(conf.getName())) {
throw new ConfigException("dataNode " + conf.getName() + " duplicated!");
}
if (!dataHosts.containsKey(host)) {
throw new ConfigException("dataNode " + dnName + " reference dataHost:" + host + " not exists!");
}
dataHosts.get(host).addDataNode(conf.getName());
dataNodes.put(conf.getName(), conf);
}
private boolean empty(String dnName) {
return dnName == null || dnName.length() == 0;
}
private DBHostConfig createDBHostConf(String dataHost, Element node,
String dbType, String dbDriver, int maxCon, int minCon, String filters, long logTime) {
String nodeHost = node.getAttribute("host");
String nodeUrl = node.getAttribute("url");
String user = node.getAttribute("user");
String password = node.getAttribute("password");
String usingDecrypt = node.getAttribute("usingDecrypt");
String passwordEncryty= DecryptUtil.DBHostDecrypt(usingDecrypt, nodeHost, user, password);
String weightStr = node.getAttribute("weight");
int weight = "".equals(weightStr) ? PhysicalDBPool.WEIGHT : Integer.parseInt(weightStr) ;
String ip = null;
int port = 0;
if (empty(nodeHost) || empty(nodeUrl) || empty(user)) {
throw new ConfigException(
"dataHost "
+ dataHost
+ " define error,some attributes of this element is empty: "
+ nodeHost);
}
if ("native".equalsIgnoreCase(dbDriver)) {
int colonIndex = nodeUrl.indexOf(':');
ip = nodeUrl.substring(0, colonIndex).trim();
port = Integer.parseInt(nodeUrl.substring(colonIndex + 1).trim());
} else {
URI url;
try {
url = new URI(nodeUrl.substring(5));
} catch (Exception e) {
throw new ConfigException("invalid jdbc url " + nodeUrl + " of " + dataHost);
}
ip = url.getHost();
port = url.getPort();
}
DBHostConfig conf = new DBHostConfig(nodeHost, ip, port, nodeUrl, user, passwordEncryty,password);
conf.setDbType(dbType);
conf.setMaxCon(maxCon);
conf.setMinCon(minCon);
conf.setFilters(filters);
conf.setLogTime(logTime);
conf.setWeight(weight);
return conf;
}
private void loadDataHosts(Element root) {
NodeList list = root.getElementsByTagName("dataHost");
for (int i = 0, n = list.getLength(); i < n; ++i) {
Element element = (Element) list.item(i);
String name = element.getAttribute("name");
if (dataHosts.containsKey(name)) {
throw new ConfigException("dataHost name " + name + "duplicated!");
}
int maxCon = Integer.parseInt(element.getAttribute("maxCon"));
int minCon = Integer.parseInt(element.getAttribute("minCon"));
/**
*
* 1. balance="0", writeHost
* 2. balance="1" readHost stand by writeHost select
* 3. balance="2" writeHostreadhost
* 4. balance="3" wiriterHost readhost writerHost
*/
int balance = Integer.parseInt(element.getAttribute("balance"));
/**
*
* -1
* 1
* 2 MySQL
* show slave status
* 3 MySQL galary cluster
*/
String switchTypeStr = element.getAttribute("switchType");
int switchType = switchTypeStr.equals("") ? -1 : Integer.parseInt(switchTypeStr);
String slaveThresholdStr = element.getAttribute("slaveThreshold");
int slaveThreshold = slaveThresholdStr.equals("") ? -1 : Integer.parseInt(slaveThresholdStr);
// tempReadHostAvailable 0
String tempReadHostAvailableStr = element.getAttribute("tempReadHostAvailable");
boolean tempReadHostAvailable = !tempReadHostAvailableStr.equals("") && Integer.parseInt(tempReadHostAvailableStr) > 0;
/**
*
* 0 - writeHost
*/
String writeTypStr = element.getAttribute("writeType");
int writeType = "".equals(writeTypStr) ? PhysicalDBPool.WRITE_ONLYONE_NODE : Integer.parseInt(writeTypStr);
String dbDriver = element.getAttribute("dbDriver");
String dbType = element.getAttribute("dbType");
String filters = element.getAttribute("filters");
String logTimeStr = element.getAttribute("logTime");
String slaveIDs = element.getAttribute("slaveIDs");
long logTime = "".equals(logTimeStr) ? PhysicalDBPool.LONG_TIME : Long.parseLong(logTimeStr) ;
String heartbeatSQL = element.getElementsByTagName("heartbeat").item(0).getTextContent();
// sql,oracle
NodeList connectionInitSqlList = element.getElementsByTagName("connectionInitSql");
String initConSQL = null;
if (connectionInitSqlList.getLength() > 0) {
initConSQL = connectionInitSqlList.item(0).getTextContent();
}
//writeHost
NodeList writeNodes = element.getElementsByTagName("writeHost");
DBHostConfig[] writeDbConfs = new DBHostConfig[writeNodes.getLength()];
Map<Integer, DBHostConfig[]> readHostsMap = new HashMap<Integer, DBHostConfig[]>(2);
Set<String> writeHostNameSet = new HashSet<String>(writeNodes.getLength());
for (int w = 0; w < writeDbConfs.length; w++) {
Element writeNode = (Element) writeNodes.item(w);
writeDbConfs[w] = createDBHostConf(name, writeNode, dbType, dbDriver, maxCon, minCon,filters,logTime);
if(writeHostNameSet.contains(writeDbConfs[w].getHostName())) {
throw new ConfigException("writeHost " + writeDbConfs[w].getHostName() + " duplicated!");
} else {
writeHostNameSet.add(writeDbConfs[w].getHostName());
}
NodeList readNodes = writeNode.getElementsByTagName("readHost");
//readHost
if (readNodes.getLength() != 0) {
DBHostConfig[] readDbConfs = new DBHostConfig[readNodes.getLength()];
Set<String> readHostNameSet = new HashSet<String>(readNodes.getLength());
for (int r = 0; r < readDbConfs.length; r++) {
Element readNode = (Element) readNodes.item(r);
readDbConfs[r] = createDBHostConf(name, readNode, dbType, dbDriver, maxCon, minCon,filters, logTime);
if(readHostNameSet.contains(readDbConfs[r].getHostName())) {
throw new ConfigException("readHost " + readDbConfs[r].getHostName() + " duplicated!");
} else {
readHostNameSet.add(readDbConfs[r].getHostName());
}
}
readHostsMap.put(w, readDbConfs);
}
}
DataHostConfig hostConf = new DataHostConfig(name, dbType, dbDriver,
writeDbConfs, readHostsMap, switchType, slaveThreshold, tempReadHostAvailable);
hostConf.setMaxCon(maxCon);
hostConf.setMinCon(minCon);
hostConf.setBalance(balance);
hostConf.setWriteType(writeType);
hostConf.setHearbeatSQL(heartbeatSQL);
hostConf.setConnectionInitSql(initConSQL);
hostConf.setFilters(filters);
hostConf.setLogTime(logTime);
hostConf.setSlaveIDs(slaveIDs);
dataHosts.put(hostConf.getName(), hostConf);
}
}
} |
package io.usethesource.vallang.util;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.function.BiFunction;
import io.usethesource.capsule.Map;
import io.usethesource.capsule.util.EqualityComparator;
import io.usethesource.vallang.IValue;
public class EqualityUtils {
/**
* Temporary function in order to support different equality checks.
*/
public static EqualityComparator<Object> getDefaultEqualityComparator() {
return Object::equals;
}
/**
* Temporary function in order to support equivalence. Note, this
* implementation is only works for {@link IValue} arguments. If arguments
* are of a different type, an unchecked exception will be thrown.
*/
public static EqualityComparator<Object> getEquivalenceComparator() {
return (a, b) -> EqualityComparator.equals((IValue) a, (IValue) b, IValue::isEqual);
}
public static final EqualityComparator<Map.Immutable<String, IValue>> KEYWORD_PARAMETER_COMPARATOR = EqualityUtils::compareKwParams;
private static boolean compareKwParams(Map.Immutable<String, IValue> a, Map.Immutable<String, IValue> b) {
if (a.size() != b.size()) {
return false;
}
Iterator<Entry<String, IValue>> aIt = a.entryIterator();
Iterator<Entry<String, IValue>> bIt = a.entryIterator();
EqualityComparator<Object> comp = getEquivalenceComparator();
while (aIt.hasNext() && bIt.hasNext()) {
Entry<String, IValue> aNext = aIt.next();
Entry<String, IValue> bNext = bIt.next();
if (!aNext.getKey().equals(bNext.getKey())) {
return false;
}
if (!comp.equals(aNext.getValue(), bNext.getValue())) {
return false;
}
}
return true;
}
public static final BiFunction<java.util.List<Object>, Object, Boolean> func = (a, b) -> a.stream().map(e -> e == b) == null;
} |
package com.mangofactory.swagger.models.property;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
public class BeanPropertyDefinitions {
private BeanPropertyDefinitions() {
throw new UnsupportedOperationException();
}
public static Function<BeanPropertyDefinition, String> beanPropertyByInternalName() {
return new Function<BeanPropertyDefinition, String>() {
@Override
public String apply(BeanPropertyDefinition input) {
return input.getInternalName();
}
};
}
public static Optional<BeanPropertyDefinition> jacksonPropertyWithSameInternalName(BeanDescription beanDescription,
BeanPropertyDefinition propertyDefinition) {
return FluentIterable.from(beanDescription.findProperties())
.firstMatch(withSameInternalName(propertyDefinition));
}
private static Predicate<BeanPropertyDefinition> withSameInternalName(
final BeanPropertyDefinition propertyDefinition) {
return new Predicate<BeanPropertyDefinition>() {
@Override
public boolean apply(BeanPropertyDefinition input) {
return input.getInternalName().equals(propertyDefinition.getInternalName());
}
};
}
} |
package isomorphly.reflect.scanners;
import isomorphly.IsomorphlyEngine;
public class PackageScanner {
private String[] packageNames;
private IsomorphlyEngine engine;
public PackageScanner(IsomorphlyEngine engine, String[] packageNames) {
this.engine = engine;
this.packageNames = packageNames;
}
public String[] getPackagesNames() {
return this.packageNames;
}
public IsomorphlyEngine getEngine() {
return this.engine;
}
} |
package jfxtras.samples.controls;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.scene.Node;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import jfxtras.labs.scene.control.CornerMenu;
import jfxtras.samples.JFXtrasSampleBase;
import jfxtras.scene.control.ListSpinner;
import jfxtras.scene.layout.GridPane;
import org.controlsfx.dialog.Dialogs;
public class CornerMenuSample1 extends JFXtrasSampleBase
{
public CornerMenuSample1() {
}
final private MenuItem facebookMenuItem = registerAction(new MenuItem("Facebook", new ImageView(new Image(this.getClass().getResourceAsStream("social_facebook_button_blue.png")))));
final private MenuItem googleMenuItem = registerAction(new MenuItem("Google", new ImageView(new Image(this.getClass().getResourceAsStream("social_google_button_blue.png")))));
final private MenuItem skypeMenuItem = registerAction(new MenuItem("Skype", new ImageView(new Image(this.getClass().getResourceAsStream("social_skype_button_blue.png")))));
final private MenuItem twitterMenuItem = registerAction(new MenuItem("Twitter", new ImageView(new Image(this.getClass().getResourceAsStream("social_twitter_button_blue.png")))));
final private MenuItem windowsMenuItem = registerAction(new MenuItem("Windows", new ImageView(new Image(this.getClass().getResourceAsStream("social_windows_button.png")))));
private MenuItem registerAction(MenuItem menuItem) {
menuItem.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
Dialogs.create().masthead("Click").message( "You clicked the " + menuItem.getText() + " icon").showInformation();
}
});
return menuItem;
}
/**
*
* @return
*/
@Override
public String getSampleName() {
return this.getClass().getSimpleName();
}
/**
*
* @return
*/
@Override
public String getSampleDescription() {
return "Basic CornerMenu usage; CornerMenu uses CircularPane to render a menu that can be placed in the corner of a screen.";
}
/**
*
* @param stage
* @return
*/
@Override
public Node getPanel(Stage stage) {
createCircularPane();
return pane;
}
private Pane pane = new Pane();
@Override
public Node getControlPanel() {
// the result
GridPane lGridPane = new GridPane();
lGridPane.setVgap(2.0);
lGridPane.setHgap(2.0);
// setup the grid so all the labels will not grow, but the rest will
ColumnConstraints lColumnConstraintsAlwaysGrow = new ColumnConstraints();
lColumnConstraintsAlwaysGrow.setHgrow(Priority.ALWAYS);
ColumnConstraints lColumnConstraintsNeverGrow = new ColumnConstraints();
lColumnConstraintsNeverGrow.setHgrow(Priority.NEVER);
lGridPane.getColumnConstraints().addAll(lColumnConstraintsNeverGrow, lColumnConstraintsAlwaysGrow);
int lRowIdx = 0;
// Location
{
lGridPane.add(new Label("Location"), new GridPane.C().row(lRowIdx).col(0).halignment(HPos.RIGHT));
lOrientationChoiceBox.getSelectionModel().select(CornerMenu.Orientation.TOP_LEFT);
lGridPane.add(lOrientationChoiceBox, new GridPane.C().row(lRowIdx).col(1));
lOrientationChoiceBox.valueProperty().addListener( (observable) -> {
createCircularPane();
});
}
lRowIdx++;
// done
return lGridPane;
}
private ChoiceBox<CornerMenu.Orientation> lOrientationChoiceBox = new ChoiceBox<CornerMenu.Orientation>(FXCollections.observableArrayList(CornerMenu.Orientation.values()));;
private void createCircularPane() {
pane.getChildren().clear();
cornerMenu = new CornerMenu();
cornerMenu.setOrientation(lOrientationChoiceBox.getValue());
if (CornerMenu.Orientation.TOP_LEFT.equals(lOrientationChoiceBox.getValue())) {
}
else if (CornerMenu.Orientation.TOP_RIGHT.equals(lOrientationChoiceBox.getValue())) {
cornerMenu.layoutXProperty().bind( pane.widthProperty().subtract(cornerMenu.widthProperty()));
}
else if (CornerMenu.Orientation.BOTTOM_RIGHT.equals(lOrientationChoiceBox.getValue())) {
cornerMenu.layoutXProperty().bind( pane.widthProperty().subtract(cornerMenu.widthProperty()));
cornerMenu.layoutYProperty().bind( pane.heightProperty().subtract(cornerMenu.heightProperty()));
}
else if (CornerMenu.Orientation.BOTTOM_LEFT.equals(lOrientationChoiceBox.getValue())) {
cornerMenu.layoutYProperty().bind( pane.heightProperty().subtract(cornerMenu.heightProperty()));
}
cornerMenu.getItems().addAll(facebookMenuItem, googleMenuItem, skypeMenuItem, twitterMenuItem, windowsMenuItem);
pane.getChildren().add(cornerMenu);
}
private CornerMenu cornerMenu;
/**
*
* @return
*/
@Override
public String getJavaDocURL() {
return "http://jfxtras.org/doc/8.0/jfxtras-controls/" + ListSpinner.class.getName().replace(".", "/") + ".html";
}
public static void main(String[] args) {
launch(args);
}
} |
package net.bootsfaces.component.ajax;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.MethodExpression;
import javax.faces.FacesException;
import javax.faces.component.ActionSource;
import javax.faces.component.ActionSource2;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UIForm;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.AjaxBehavior;
import javax.faces.component.behavior.ClientBehavior;
import javax.faces.component.behavior.ClientBehaviorHolder;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.FacesEvent;
import javax.faces.event.PhaseId;
import net.bootsfaces.component.commandButton.CommandButton;
import net.bootsfaces.component.navCommandLink.NavCommandLink;
import net.bootsfaces.component.navLink.NavLink;
import net.bootsfaces.component.tabView.TabView;
import net.bootsfaces.expressions.ExpressionResolver;
import net.bootsfaces.render.CoreRenderer;
public class AJAXRenderer extends CoreRenderer {
private static final Logger LOGGER = Logger.getLogger("net.bootsfaces.component.ajax.AJAXRenderer");
// local constants
public static final String BSF_EVENT_PREFIX = "BsFEvent=";
public static final String AJAX_EVENT_PREFIX = "ajax:";
public void decode(FacesContext context, UIComponent component) {
String id = component.getClientId(context);
decode(context, component, id);
}
public void decode(FacesContext context, UIComponent component, String componentId) {
if (componentIsDisabledOrReadonly(component)) {
return;
}
String source = (String) context.getExternalContext().getRequestParameterMap().get("javax.faces.source");
if (component instanceof TabView && source != null) {
for (UIComponent tab : component.getChildren()) {
String tabId = tab.getClientId().replace(":", "_") + "_tab";
if (source.equals(tabId)) {
component = tab;
componentId = tabId;
break;
}
}
}
if (source == null) {
// check for non-ajax call
if (context.getExternalContext().getRequestParameterMap().containsKey(componentId)) {
source = componentId;
}
}
if (source != null && (source.equals(componentId) || (source.equals("input_"+componentId))
|| (("input_"+source).equals(componentId)) || source.equals(componentId+"Inner"))) {
String event = context.getExternalContext().getRequestParameterMap().get("javax.faces.partial.event");
String realEvent = (String) context.getExternalContext().getRequestParameterMap().get("params");
if (null != realEvent && realEvent.startsWith(BSF_EVENT_PREFIX)) {
realEvent = realEvent.substring(BSF_EVENT_PREFIX.length());
if (!realEvent.equals(event)) {
// System.out.println("Difference between event and
// realEvent:" + event + " vs. " + realEvent
// + " Component: " + component.getClass().getSimpleName());
event = realEvent;
}
}
String nameOfGetter = "getOn" + event;
try {
Method[] methods = component.getClass().getMethods();
for (Method m : methods) {
if (m.getParameterTypes().length == 0) {
if (m.getReturnType() == String.class) {
if (m.getName().equalsIgnoreCase(nameOfGetter)) {
String jsCallback = (String) m.invoke(component);
if (jsCallback != null && jsCallback.contains(AJAX_EVENT_PREFIX)) {
if (component instanceof CommandButton && "action".equals(event)) {
component.queueEvent(new ActionEvent(component));
} else {
FacesEvent ajaxEvent = new BootsFacesAJAXEvent(
new AJAXBroadcastComponent(component), event, jsCallback);
ajaxEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
if (component instanceof ActionSource) {
if (((ActionSource) component).isImmediate())
ajaxEvent.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
} else if (component instanceof IAJAXComponent) {
if (((IAJAXComponent) component).isImmediate())
ajaxEvent.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
}
component.queueEvent(ajaxEvent);
}
}
break;
}
}
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Couldn't invoke method " + nameOfGetter);
}
if (null != event) {
UIComponentBase bb = (UIComponentBase) component;
Map<String, List<ClientBehavior>> clientBehaviors = bb.getClientBehaviors();
for (Entry<String, List<ClientBehavior>> entry : clientBehaviors.entrySet()) {
if (event.equals(entry.getKey())) {
List<ClientBehavior> value = entry.getValue();
for (ClientBehavior bh : value) {
if (bh instanceof AjaxBehavior) {
// String delay = ((AjaxBehavior)
// bh).getDelay();
bh.decode(context, component);
}
}
}
}
}
boolean addEventToQueue = false;
if (component instanceof ActionSource) {
ActionSource b = (ActionSource) component;
ActionListener[] actionListeners = b.getActionListeners();
if (null != actionListeners && actionListeners.length > 0) {
addEventToQueue = true;
}
}
if (component instanceof ActionSource2) {
MethodExpression actionExpression = ((ActionSource2) component).getActionExpression();
if (null != actionExpression) {
addEventToQueue = true;
}
}
if (addEventToQueue) {
ActionEvent ae = new ActionEvent(component);
if (component instanceof ActionSource) {
if (((ActionSource) component).isImmediate()) {
ae.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
} else {
ae.setPhaseId(PhaseId.INVOKE_APPLICATION);
}
}
component.queueEvent(ae );
}
}
}
/**
* Public API for every input component (effectively everything except the
* command button).
*
* @param context
* @param component
* @param rw
* @param suppressAJAX replaces the AJAX request by a BsF.submitForm(), but only if there are parameters. Used by b:navCommandRenderer to implement
* an action or an actionListener instead of rendering a simple link.
* @throws IOException
*/
public static void generateBootsFacesAJAXAndJavaScript(FacesContext context, ClientBehaviorHolder component,
ResponseWriter rw, boolean suppressAJAX) throws IOException {
generateBootsFacesAJAXAndJavaScript(context, component, rw, null, null, false, suppressAJAX);
}
public static void generateBootsFacesAJAXAndJavaScript(FacesContext context, ClientBehaviorHolder component,
ResponseWriter rw, String specialEvent, String specialEventHandler, boolean isJQueryCallback, boolean suppressAJAX)
throws IOException {
boolean generatedAJAXCall = false;
Collection<String> eventNames = component.getEventNames();
Map<String, String> jQueryEvents = ((IAJAXComponent) component).getJQueryEvents();
if (null != eventNames) {
for (String keyClientBehavior : eventNames) {
if (null != jQueryEvents)
if (jQueryEvents.containsKey(keyClientBehavior))
continue;
generatedAJAXCall |= generateAJAXCallForASingleEvent(context, component, rw, null, specialEvent,
specialEventHandler, isJQueryCallback, keyClientBehavior, null, null);
}
}
if (!generatedAJAXCall) {
// should we generate AJAX nonetheless?
boolean ajax = ((IAJAXComponent) component).isAjax();
ajax |= null != ((IAJAXComponent) component).getUpdate();
if (ajax) {
// before generating an AJAX default handler, check if there's an jQuery handler that's generated later
if (null != jQueryEvents) {
Set<String> events = jQueryEvents.keySet();
for (String event : events) {
String nameOfGetter = "getOn" + event;
try {
Method[] methods = component.getClass().getMethods();
for (Method m : methods) {
if (m.getParameterTypes().length == 0) {
if (m.getReturnType() == String.class) {
if (m.getName().equalsIgnoreCase(nameOfGetter)) {
String jsCallback = (String) m.invoke(component);
if (jsCallback != null && jsCallback.contains(AJAX_EVENT_PREFIX)) {
ajax=false;
}
break;
}
}
}
}
} catch (Exception e) {
}
}
}
if (ajax) {
StringBuilder s = generateAJAXCallForClientBehavior(context, (IAJAXComponent) component,
(ClientBehavior) null);
String script = s.toString() + ";";
String defaultEvent = ((IAJAXComponent) component).getDefaultEventName();
if (component instanceof CommandButton)
if (script.length() > 0 && "click".equals(defaultEvent))
script += ";return false;";
rw.writeAttribute("on" + defaultEvent, script, null);
}
} else if (component instanceof CommandButton) {
encodeFormSubmit((UIComponent)component, rw, false);
}
else {
// b:navCommandLink doesn't submit the form, so we need to use
// AJAX
boolean generateNonAJAXCommand = false;
if (component instanceof ActionSource) {
ActionSource b = (ActionSource) component;
ActionListener[] actionListeners = b.getActionListeners();
if (null != actionListeners && actionListeners.length > 0) {
generateNonAJAXCommand = true;
}
}
if (component instanceof ActionSource2) {
MethodExpression actionExpression = ((ActionSource2) component).getActionExpression();
if (null != actionExpression) {
generateNonAJAXCommand = true;
}
}
if (generateNonAJAXCommand && component instanceof IAJAXComponent) {
// rw.writeAttribute("id", getClientId() + "_a", null);
generateOnClickHandler(context, rw, (IAJAXComponent) component, suppressAJAX);
}
}
// TODO: what about composite components?
}
}
private static void encodeFormSubmit(UIComponent component, ResponseWriter rw, boolean evenWithoutParameters) throws IOException {
String parameterList="";
List<UIComponent> children = ((UIComponent)component).getChildren();
for (UIComponent parameter: children) {
if (parameter instanceof UIParameter) {
String value=String.valueOf(((UIParameter) parameter).getValue());
String name = ((UIParameter) parameter).getName();
if (null!=value) {
parameterList += ",'" + name + "':'" + value + "'";
}
}
}
if (evenWithoutParameters || parameterList.length()>0) {
UIForm currentForm = getSurroundingForm((UIComponent)component, false);
parameterList = "'" + currentForm.getClientId() + "',{'" +component.getClientId() + "':'" + component.getClientId() + "'" + parameterList+ "}";
rw.writeAttribute("onclick", encodeClick((UIComponent) component) + "BsF.submitForm(" + parameterList + ");return false;", null);
}
}
private static void generateOnClickHandler(FacesContext context, ResponseWriter rw, IAJAXComponent component, boolean suppressAJAX)
throws IOException {
StringBuilder cJS = new StringBuilder(150); // optimize int
if (suppressAJAX) {
encodeFormSubmit((UIComponent)component, rw, true);
} else {
cJS.append(encodeClick((UIComponent)component)).append("return BsF.ajax.cb(this, event);");
}
rw.writeAttribute("onclick", cJS.toString(), null);
}
public static boolean generateAJAXCallForASingleEvent(FacesContext context, ClientBehaviorHolder component,
ResponseWriter rw, StringBuffer code, String specialEvent, String specialEventHandler, boolean isJQueryCallback,
String keyClientBehavior, StringBuilder generatedJSCode, String optionalParameterList) throws IOException {
boolean generatedAJAXCall = false;
String jsCallback = "";
String nameOfGetter = "getOn" + keyClientBehavior;
try {
Method[] methods = component.getClass().getMethods();
for (Method m : methods) {
if (m.getParameterTypes().length == 0) {
if (m.getReturnType() == String.class) {
if (m.getName().equalsIgnoreCase(nameOfGetter)) {
jsCallback = (String) m.invoke(component);
if (specialEventHandler != null && keyClientBehavior.equals(specialEvent)) {
if (null == jsCallback || jsCallback.length() == 0)
jsCallback = specialEventHandler;
else
jsCallback = jsCallback + ";javascript:" + specialEventHandler;
}
jsCallback = convertAJAXToJavascript(context, jsCallback, component, keyClientBehavior, optionalParameterList);
if (null != code) {
code.append(jsCallback);
}
if ("dragstart".equals(keyClientBehavior)) {
if (null != rw) {
rw.writeAttribute("draggable", "true", "draggable");
}
}
break;
}
}
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Couldn't invoke method " + nameOfGetter);
}
// TODO behaviors don't render correctly?
// SR 19.09.2015: looks a bit odd, indeed. The method generateAJAXCall()
// generates an onclick handler -
// regardless of which event we currently deal with
String script = "";
Map<String, List<ClientBehavior>> clientBehaviors = component.getClientBehaviors();
List<ClientBehavior> behaviors = clientBehaviors.get(keyClientBehavior);
if (null != behaviors) {
for (ClientBehavior cb : behaviors) {
if (cb instanceof AjaxBehavior) {
StringBuilder s = generateAJAXCallForClientBehavior(context, (IAJAXComponent) component,
(AjaxBehavior) cb);
script += s.toString() + ";";
} else if (cb.getClass().getSimpleName().equals("AjaxBehavior")) {
AjaxBehavior ab = new AjaxBehavior();
Object disabled = readBeanAttribute(cb, "isDisabled");
ab.setDisabled((Boolean) disabled);
ab.setOnerror((String) readBeanAttribute(cb, "getOnerror"));
ab.setRender((Collection<String>) readBeanAttributeAsCollection(cb, "getUpdate"));
ab.setExecute((Collection<String>) readBeanAttributeAsCollection(cb, "getProcess"));
ab.setOnevent(keyClientBehavior);
StringBuilder s = generateAJAXCallForClientBehavior(context, (IAJAXComponent) component, ab);
script += s.toString() + ";";
}
}
}
// TODO end
if (jsCallback.contains("BsF.ajax.") || script.contains("BsF.ajax.")) {
generatedAJAXCall = true;
}
if (!isJQueryCallback) {
if (jsCallback.length() > 0 || script.length() > 0) {
if (component instanceof CommandButton)
if (generatedAJAXCall && "click".equals(keyClientBehavior))
script += ";return false;";
if (script.startsWith(jsCallback)) {
// this happens when you combine onclick and f:ajax.
// Both render the onclick attribute, but
// in general it's hard to detect this situation because
// different components have different default actions for
// f:ajax. So let's simply use this hack.
jsCallback="";
}
if (null != rw) {
rw.writeAttribute("on" + keyClientBehavior, jsCallback + script, null);
}
if (null != code) {
code.append(jsCallback + script);
}
}
}
if (null != generatedJSCode) {
generatedJSCode.setLength(0);
if (jsCallback.length() > 0)
generatedJSCode.append(jsCallback);
if (script.length() > 0)
generatedJSCode.append(script);
}
return generatedAJAXCall;
}
private static Object readBeanAttribute(Object bean, String getter) {
try {
Method method = bean.getClass().getMethod(getter);
Object result = method.invoke(bean);
return result;
} catch (Exception e) {
throw new FacesException("An error occured when reading the property " + getter + " from the bean "
+ bean.getClass().getName(), e);
}
}
private static Collection<String> readBeanAttributeAsCollection(Object bean, String getter) {
Collection<String> result = null;
try {
Method method = bean.getClass().getMethod(getter);
Object value = method.invoke(bean);
if (null != value) {
String[] partials = ((String) value).split(" ");
result = new ArrayList<String>();
for (String p : partials) {
result.add(p);
}
}
return result;
} catch (Exception e) {
throw new FacesException("An error occured when reading the property " + getter + " from the bean "
+ bean.getClass().getName(), e);
}
}
private static String convertAJAXToJavascript(FacesContext context, String jsCallback,
ClientBehaviorHolder component, String event, String optionalParameterList) {
if (jsCallback == null)
jsCallback = "";
else {
if (jsCallback.contains(AJAX_EVENT_PREFIX)) {
int pos = jsCallback.indexOf(AJAX_EVENT_PREFIX);
String rest = "";
int end = jsCallback.indexOf(";javascript:", pos);
if (end >= 0) {
rest = jsCallback.substring(end + ";javascript:".length());
jsCallback = jsCallback.substring(0, end);
}
StringBuilder ajax = generateAJAXCall(context, (IAJAXComponent) component, event, optionalParameterList);
jsCallback = jsCallback.substring(0, pos) + ";" + ajax + rest;
}
if (!jsCallback.endsWith(";"))
jsCallback += ";";
}
return jsCallback;
}
public static StringBuilder generateAJAXCall(FacesContext context, IAJAXComponent component, String event, String optionalParameterList) {
String complete = component.getOncomplete();
String onError = null;
String onSuccess = null;
if (component instanceof IAJAXComponent2) {
onError = ((IAJAXComponent2) component).getOnerror();
onSuccess = ((IAJAXComponent2) component).getOnsuccess();
}
StringBuilder cJS = new StringBuilder(150);
String update = component.getUpdate();
if (null == update) {
update = "@none";
}
update = ExpressionResolver.getComponentIDs(context, (UIComponent) component, update);
String process = component.getProcess();
if (null == process) {
process = "@all";
}
if ("@all".equals(process) || "@none".equals(process)) {
// these expressions are evaluated on the client side
} else {
process = ExpressionResolver.getComponentIDs(context, (UIComponent) component, process);
}
cJS.append("BsF.ajax.callAjax(this, event").append(",'" + update + "'").append(",'").append(process)
.append("'");
if (complete != null) {
cJS.append(",function(){" + complete + "}");
} else
cJS.append(", null");
if (onError != null) {
cJS.append(",function(){" + onError + "}");
} else
cJS.append(", null");
if (onSuccess != null) {
cJS.append(",function(){" + onSuccess + "}");
} else
cJS.append(", null");
if ((event != null) && (event.length() > 0)) {
cJS.append(", '" + event + "'");
} else
cJS.append(", null");
String parameterList="";
List<UIComponent> children = ((UIComponent)component).getChildren();
for (UIComponent parameter: children) {
if (parameter instanceof UIParameter) {
String value=String.valueOf(((UIParameter) parameter).getValue());
String name = ((UIParameter) parameter).getName();
if (null!=value) {
parameterList += ",'" + name + "':'" + value + "'";
}
}
}
if (null != optionalParameterList) {
parameterList += "," + optionalParameterList;
}
if (parameterList.length()>0) {
String json=",{" + parameterList.substring(1) + "}";
cJS.append(json);
}
cJS.append(");");
return cJS;
}
private static StringBuilder generateAJAXCallForClientBehavior(FacesContext context, IAJAXComponent component,
ClientBehavior ajaxBehavior) {
StringBuilder cJS = new StringBuilder(150);
// find default values
String update = component.getUpdate();
String oncomplete = component.getOncomplete();
String process = component.getProcess();
String onevent = "";
String onError = null;
String onSuccess = null;
if (component instanceof IAJAXComponent2) {
onError = ((IAJAXComponent2) component).getOnerror();
onSuccess = ((IAJAXComponent2) component).getOnsuccess();
}
if (ajaxBehavior != null) {
// the default values can be overridden by the AJAX behavior
if (ajaxBehavior instanceof AjaxBehavior) {
boolean disabled = ((AjaxBehavior) ajaxBehavior).isDisabled();
if (!disabled) {
// String onerror = ((AjaxBehavior)
// ajaxBehavior).getOnerror(); // todo
onevent = ((AjaxBehavior) ajaxBehavior).getOnevent();
if (onevent == null)
onevent = "";
Collection<String> execute = ((AjaxBehavior) ajaxBehavior).getExecute();
if (null != execute && (!execute.isEmpty())) {
for (String u : execute) {
if (null == process)
process = u;
else
process += " " + u;
}
} else {
process = "@this";
}
Collection<String> render = ((AjaxBehavior) ajaxBehavior).getRender();
if (null != render && (!render.isEmpty())) {
update = "";
for (String u : render) {
update += u + " ";
}
}
oncomplete = component.getOncomplete();
}
}
}
if ("@all".equals(process) || "@none".equals(process) ) {
// these expressions are evaluated on the client side
} else {
process = ExpressionResolver.getComponentIDs(context, (UIComponent) component, process);
}
if (update==null) {
update="";
} else {
update = ExpressionResolver.getComponentIDs(context, (UIComponent) component, update);
}
cJS.append(encodeClick((UIComponent)component)).append("BsF.ajax.callAjax(this, event")
.append(update == null ? ",''" : (",'" + update + "'"))
.append(process == null ? ",'@this'" : (",'" + process.trim() + "'"));
if (oncomplete != null) {
cJS.append(",function(){" + oncomplete + "}");
} else
cJS.append(",null");
if (onError != null) {
cJS.append(",function(){" + onError + "}");
} else
cJS.append(",null");
if (onSuccess != null) {
cJS.append(",function(){" + onSuccess + "}");
} else
cJS.append(",null");
if ((onevent != null) && (onevent.length() > 0)) {
cJS.append(", '" + onevent + "'");
} else {
cJS.append(",null");
}
String parameterList="";
List<UIComponent> children = ((UIComponent)component).getChildren();
for (UIComponent parameter: children) {
if (parameter instanceof UIParameter) {
String value=String.valueOf(((UIParameter) parameter).getValue());
String name = ((UIParameter) parameter).getName();
if (null!=value) {
parameterList += ",'" + name + "':'" + value + "'";
}
}
}
if (parameterList.length()>0) {
String json=",{" + parameterList.substring(1) + "}";
cJS.append(json);
}
cJS.append(");");
return cJS;
}
private static String encodeClick(UIComponent component) {
String js;
String oc=null;
if (component instanceof IAJAXComponent) {
oc = (String) ((IAJAXComponent)component).getOnclick();
}
if (component instanceof NavLink) {
oc = (String) ((NavLink)component).getOnclick();
}
if (component instanceof NavCommandLink) {
oc = (String) ((NavCommandLink)component).getOnclick();
}
if (oc != null) {
js = oc.endsWith(";") ? oc : oc + ";";
} else {
js = "";
}
return js;
}
/**
* Registers a callback with jQuery.
*
* @param context
* @param component
* @param rw
* @param jQueryExpressionOfTargetElement
* @param additionalEventHandlers
* @throws IOException
*/
public void generateBootsFacesAJAXAndJavaScriptForJQuery(FacesContext context, UIComponent component,
ResponseWriter rw, String jQueryExpressionOfTargetElement, Map<String, String> additionalEventHandlers) throws IOException {
generateBootsFacesAJAXAndJavaScriptForJQuery(context, component, rw, jQueryExpressionOfTargetElement, additionalEventHandlers, false);
}
/**
* Registers a callback with jQuery.
*
* @param context
* @param component
* @param rw
* @param jQueryExpressionOfTargetElement
* @param additionalEventHandlers
* @param attachOnReady
* @throws IOException
*/
public void generateBootsFacesAJAXAndJavaScriptForJQuery(FacesContext context, UIComponent component,
ResponseWriter rw, String jQueryExpressionOfTargetElement, Map<String, String> additionalEventHandlers, boolean attachOnReady) throws IOException {
if (jQueryExpressionOfTargetElement.contains(":")) {
if (!jQueryExpressionOfTargetElement.contains("\\\\:")) { // avoid escaping twice
jQueryExpressionOfTargetElement=jQueryExpressionOfTargetElement.replace(":", "\\\\:");
}
}
IAJAXComponent ajaxComponent = (IAJAXComponent) component;
Set<String> events = ajaxComponent.getJQueryEvents().keySet();
for (String event : events) {
StringBuilder code = new StringBuilder();
String additionalEventHandler = null;
if (null != additionalEventHandlers)
additionalEventHandler = additionalEventHandlers.get(event);
String parameterList = null;
if (null != ajaxComponent.getJQueryEventParameterListsForAjax()) {
if (null != ajaxComponent.getJQueryEventParameterListsForAjax().get(event))
parameterList = ajaxComponent.getJQueryEventParameterListsForAjax().get(event);
}
generateAJAXCallForASingleEvent(context, (ClientBehaviorHolder) component, rw, null, event,
additionalEventHandler, true, event, code, parameterList);
if (code.length() > 0) {
rw.startElement("script", component);
parameterList = "event";
if (null != ajaxComponent.getJQueryEventParameterLists()) {
if (null != ajaxComponent.getJQueryEventParameterLists().get(event))
parameterList = ajaxComponent.getJQueryEventParameterLists().get(event);
}
String js = "$('" + jQueryExpressionOfTargetElement + "').on('" + ajaxComponent.getJQueryEvents().get(event)
+ "', function(" + parameterList + "){" + code.toString() + "});";
if (attachOnReady) js = "$(function() { " + js + " })";
rw.writeText(js, null);
rw.endElement("script");
}
}
}
public String generateBootsFacesAJAXAndJavaScriptForAnMobileEvent(FacesContext context,
ClientBehaviorHolder component, ResponseWriter rw, String clientId, String event) throws IOException {
StringBuilder code = new StringBuilder();
String additionalEventHandler = null;
generateAJAXCallForASingleEvent(context, component, rw, null, event, additionalEventHandler, true, event, code, null);
return code.toString();
}
} |
package net.earthcomputer.easyeditors.api;
import java.util.regex.Pattern;
/**
* A class containing a number of {@link Pattern}s useful to Easy Editors.
*
* <b>This class is a member of the Easy Editors API</b>
*
* @author Earthcomputer
*
*/
public class Patterns {
public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");
public static final Pattern playerName = Pattern.compile("\\w{1,32}");
public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");
public static final Pattern partialUUID = Pattern
.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");
public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w\\.=,!-]*)\\])?");
public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");
public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");
} |
package net.sf.mzmine.project.impl;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import net.sf.mzmine.datamodel.DataPoint;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.datamodel.RawDataFileWriter;
import net.sf.mzmine.datamodel.Scan;
import net.sf.mzmine.datamodel.impl.SimpleDataPoint;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;
/**
* RawDataFile implementation. It provides storage of data points for scans and
* mass lists using the storeDataPoints() and readDataPoints() methods. The data
* points are stored in a temporary file (dataPointsFile) and the structure of
* the file is stored in two TreeMaps. The dataPointsOffsets maps storage ID to
* the offset in the dataPointsFile. The dataPointsLength maps the storage ID to
* the number of data points stored under this ID. When stored data points are
* deleted using removeStoredDataPoints(), the dataPointsFile is not modified,
* the storage ID is just deleted from the two TreeMaps. When the project is
* saved, the contents of the dataPointsFile are consolidated - only data points
* referenced by the TreeMaps are saved (see the RawDataFileSaveHandler class).
*/
public class RawDataFileImpl implements RawDataFile, RawDataFileWriter {
private final Logger logger = Logger.getLogger(this.getClass().getName());
// Name of this raw data file - may be changed by the user
private String dataFileName;
private final Hashtable<Integer, Range<Double>> dataMZRange, dataRTRange;
private final Hashtable<Integer, Double> dataMaxBasePeakIntensity,
dataMaxTIC;
private final Hashtable<Integer, int[]> scanNumbersCache;
private ByteBuffer buffer = ByteBuffer.allocate(20000);
private final TreeMap<Integer, Long> dataPointsOffsets;
private final TreeMap<Integer, Integer> dataPointsLengths;
// Temporary file for scan data storage
private File dataPointsFileName;
private RandomAccessFile dataPointsFile;
/**
* Scans
*/
private final Hashtable<Integer, StorableScan> scans;
public RawDataFileImpl(String dataFileName) throws IOException {
this.dataFileName = dataFileName;
// Prepare the hashtables for scan numbers and data limits.
scanNumbersCache = new Hashtable<Integer, int[]>();
dataMZRange = new Hashtable<Integer, Range<Double>>();
dataRTRange = new Hashtable<Integer, Range<Double>>();
dataMaxBasePeakIntensity = new Hashtable<Integer, Double>();
dataMaxTIC = new Hashtable<Integer, Double>();
scans = new Hashtable<Integer, StorableScan>();
dataPointsOffsets = new TreeMap<Integer, Long>();
dataPointsLengths = new TreeMap<Integer, Integer>();
}
@Override
public RawDataFile clone() throws CloneNotSupportedException {
return (RawDataFile) super.clone();
}
/**
* Create a new temporary data points file
*/
public static File createNewDataPointsFile() throws IOException {
return File.createTempFile("mzmine", ".scans");
}
/**
* Returns the (already opened) data points file. Warning: may return null
* in case no scans have been added yet to this RawDataFileImpl instance
*/
public RandomAccessFile getDataPointsFile() {
return dataPointsFile;
}
/**
* Opens the given file as a data points file for this RawDataFileImpl
* instance. If the file is not empty, the TreeMaps supplied as parameters
* have to describe the mapping of storage IDs to data points in the file.
*/
public synchronized void openDataPointsFile(File dataPointsFileName)
throws IOException {
if (this.dataPointsFile != null) {
throw new IOException(
"Cannot open another data points file, because one is already open");
}
this.dataPointsFileName = dataPointsFileName;
this.dataPointsFile = new RandomAccessFile(dataPointsFileName, "rw");
// Locks the temporary file so it is not removed when another instance
// of MZmine is starting. Lock will be automatically released when this
// instance of MZmine exits. Locking may fail on network-mounted filesystems.
try {
FileChannel fileChannel = dataPointsFile.getChannel();
fileChannel.lock();
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to lock the file " + dataPointsFileName, e);
}
// Unfortunately, deleteOnExit() doesn't work on Windows, see JDK
// bug #4171239. We will try to remove the temporary files in a
// shutdown hook registered in the main.ShutDownHook class
dataPointsFileName.deleteOnExit();
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getNumOfScans()
*/
public int getNumOfScans() {
return scans.size();
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getScan(int)
*/
public @Nonnull Scan getScan(int scanNumber) {
return scans.get(scanNumber);
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getScanNumbers(int)
*/
public @Nonnull int[] getScanNumbers(int msLevel) {
if (scanNumbersCache.containsKey(msLevel))
return scanNumbersCache.get(msLevel);
Range<Double> all = Range.all();
int scanNumbers[] = getScanNumbers(msLevel, all);
scanNumbersCache.put(msLevel, scanNumbers);
return scanNumbers;
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getScanNumbers(int, double,
* double)
*/
public @Nonnull int[] getScanNumbers(int msLevel,
@Nonnull Range<Double> rtRange) {
assert rtRange != null;
ArrayList<Integer> eligibleScanNumbers = new ArrayList<Integer>();
Enumeration<StorableScan> scansEnum = scans.elements();
while (scansEnum.hasMoreElements()) {
Scan scan = scansEnum.nextElement();
if ((scan.getMSLevel() == msLevel)
&& (rtRange.contains(scan.getRetentionTime())))
eligibleScanNumbers.add(scan.getScanNumber());
}
int[] numbersArray = Ints.toArray(eligibleScanNumbers);
Arrays.sort(numbersArray);
return numbersArray;
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getScanNumbers()
*/
public @Nonnull int[] getScanNumbers() {
if (scanNumbersCache.containsKey(0))
return scanNumbersCache.get(0);
Set<Integer> allScanNumbers = scans.keySet();
int[] numbersArray = Ints.toArray(allScanNumbers);
Arrays.sort(numbersArray);
scanNumbersCache.put(0, numbersArray);
return numbersArray;
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getMSLevels()
*/
public @Nonnull int[] getMSLevels() {
Set<Integer> msLevelsSet = new HashSet<Integer>();
Enumeration<StorableScan> scansEnum = scans.elements();
while (scansEnum.hasMoreElements()) {
Scan scan = scansEnum.nextElement();
msLevelsSet.add(scan.getMSLevel());
}
int[] msLevels = Ints.toArray(msLevelsSet);
Arrays.sort(msLevels);
return msLevels;
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getDataMaxBasePeakIntensity()
*/
public double getDataMaxBasePeakIntensity(int msLevel) {
// check if we have this value already cached
Double maxBasePeak = dataMaxBasePeakIntensity.get(msLevel);
if (maxBasePeak != null)
return maxBasePeak;
// find the value
Enumeration<StorableScan> scansEnum = scans.elements();
while (scansEnum.hasMoreElements()) {
Scan scan = scansEnum.nextElement();
// ignore scans of other ms levels
if (scan.getMSLevel() != msLevel)
continue;
DataPoint scanBasePeak = scan.getHighestDataPoint();
if (scanBasePeak == null)
continue;
if ((maxBasePeak == null)
|| (scanBasePeak.getIntensity() > maxBasePeak))
maxBasePeak = scanBasePeak.getIntensity();
}
// return -1 if no scan at this MS level
if (maxBasePeak == null)
maxBasePeak = -1d;
// cache the value
dataMaxBasePeakIntensity.put(msLevel, maxBasePeak);
return maxBasePeak;
}
/**
* @see net.sf.mzmine.datamodel.RawDataFile#getDataMaxTotalIonCurrent()
*/
public double getDataMaxTotalIonCurrent(int msLevel) {
// check if we have this value already cached
Double maxTIC = dataMaxTIC.get(msLevel);
if (maxTIC != null)
return maxTIC.doubleValue();
// find the value
Enumeration<StorableScan> scansEnum = scans.elements();
while (scansEnum.hasMoreElements()) {
Scan scan = scansEnum.nextElement();
// ignore scans of other ms levels
if (scan.getMSLevel() != msLevel)
continue;
if ((maxTIC == null) || (scan.getTIC() > maxTIC))
maxTIC = scan.getTIC();
}
// return -1 if no scan at this MS level
if (maxTIC == null)
maxTIC = -1d;
// cache the value
dataMaxTIC.put(msLevel, maxTIC);
return maxTIC;
}
public synchronized int storeDataPoints(DataPoint dataPoints[])
throws IOException {
if (dataPointsFile == null) {
File newFile = RawDataFileImpl.createNewDataPointsFile();
openDataPointsFile(newFile);
}
final long currentOffset = dataPointsFile.length();
final int currentID;
if (!dataPointsOffsets.isEmpty())
currentID = dataPointsOffsets.lastKey() + 1;
else
currentID = 1;
final int numOfDataPoints = dataPoints.length;
// Convert the dataPoints into a byte array. Each float takes 4 bytes,
// so we get the current float offset by dividing the size of the file
// by 4
final int numOfBytes = numOfDataPoints * 2 * 4;
if (buffer.capacity() < numOfBytes) {
buffer = ByteBuffer.allocate(numOfBytes * 2);
} else {
buffer.clear();
}
FloatBuffer floatBuffer = buffer.asFloatBuffer();
for (DataPoint dp : dataPoints) {
floatBuffer.put((float) dp.getMZ());
floatBuffer.put((float) dp.getIntensity());
}
dataPointsFile.seek(currentOffset);
dataPointsFile.write(buffer.array(), 0, numOfBytes);
dataPointsOffsets.put(currentID, currentOffset);
dataPointsLengths.put(currentID, numOfDataPoints);
return currentID;
}
public synchronized DataPoint[] readDataPoints(int ID) throws IOException {
final Long currentOffset = dataPointsOffsets.get(ID);
final Integer numOfDataPoints = dataPointsLengths.get(ID);
if ((currentOffset == null) || (numOfDataPoints == null)) {
throw new IllegalArgumentException("Unknown storage ID " + ID);
}
final int numOfBytes = numOfDataPoints * 2 * 4;
if (buffer.capacity() < numOfBytes) {
buffer = ByteBuffer.allocate(numOfBytes * 2);
} else {
buffer.clear();
}
dataPointsFile.seek(currentOffset);
dataPointsFile.read(buffer.array(), 0, numOfBytes);
FloatBuffer floatBuffer = buffer.asFloatBuffer();
DataPoint dataPoints[] = new DataPoint[numOfDataPoints];
for (int i = 0; i < numOfDataPoints; i++) {
float mz = floatBuffer.get();
float intensity = floatBuffer.get();
dataPoints[i] = new SimpleDataPoint(mz, intensity);
}
return dataPoints;
}
public synchronized void removeStoredDataPoints(int ID) throws IOException {
dataPointsOffsets.remove(ID);
dataPointsLengths.remove(ID);
}
public synchronized void addScan(Scan newScan) throws IOException {
// When we are loading the project, scan data file is already prepare
// and we just need store the reference
if (newScan instanceof StorableScan) {
scans.put(newScan.getScanNumber(), (StorableScan) newScan);
return;
}
DataPoint dataPoints[] = newScan.getDataPoints();
final int storageID = storeDataPoints(dataPoints);
StorableScan storedScan = new StorableScan(newScan, this,
dataPoints.length, storageID);
scans.put(newScan.getScanNumber(), storedScan);
}
/**
* @see net.sf.mzmine.datamodel.RawDataFileWriter#finishWriting()
*/
public synchronized RawDataFile finishWriting() throws IOException {
for (StorableScan scan : scans.values()) {
scan.updateValues();
}
logger.finest("Writing of scans to file " + dataPointsFileName
+ " finished");
return this;
}
public @Nonnull Range<Double> getDataMZRange() {
return getDataMZRange(0);
}
public @Nonnull Range<Double> getDataMZRange(int msLevel) {
// check if we have this value already cached
Range<Double> mzRange = dataMZRange.get(msLevel);
if (mzRange != null)
return mzRange;
// find the value
for (Scan scan : scans.values()) {
// ignore scans of other ms levels
if ((msLevel != 0) && (scan.getMSLevel() != msLevel))
continue;
if (mzRange == null)
mzRange = scan.getDataPointMZRange();
else
mzRange = mzRange.span(scan.getDataPointMZRange());
}
// cache the value, if we found any
if (mzRange != null)
dataMZRange.put(msLevel, mzRange);
else
mzRange = Range.singleton(0.0);
return mzRange;
}
public @Nonnull Range<Double> getDataRTRange() {
return getDataRTRange(0);
}
public @Nonnull Range<Double> getDataRTRange(int msLevel) {
// check if we have this value already cached
Range<Double> rtRange = dataRTRange.get(msLevel);
if (rtRange != null)
return rtRange;
// find the value
for (Scan scan : scans.values()) {
// ignore scans of other ms levels
if ((msLevel != 0) && (scan.getMSLevel() != msLevel))
continue;
if (rtRange == null)
rtRange = Range.singleton(scan.getRetentionTime());
else
rtRange = rtRange
.span(Range.singleton(scan.getRetentionTime()));
}
// cache the value
if (rtRange != null)
dataRTRange.put(msLevel, rtRange);
else
rtRange = Range.singleton(0.0);
return rtRange;
}
public void setRTRange(int msLevel, Range<Double> rtRange) {
dataRTRange.put(msLevel, rtRange);
}
public void setMZRange(int msLevel, Range<Double> mzRange) {
dataMZRange.put(msLevel, mzRange);
}
public int getNumOfScans(int msLevel) {
return getScanNumbers(msLevel).length;
}
public synchronized TreeMap<Integer, Long> getDataPointsOffsets() {
return dataPointsOffsets;
}
public synchronized TreeMap<Integer, Integer> getDataPointsLengths() {
return dataPointsLengths;
}
public synchronized void close() {
try {
if(dataPointsFileName != null) {
dataPointsFile.close();
dataPointsFileName.delete();
}
} catch (IOException e) {
logger.warning("Could not close file " + dataPointsFileName + ": "
+ e.toString());
}
}
public @Nonnull String getName() {
return dataFileName;
}
public void setName(@Nonnull String name) {
this.dataFileName = name;
}
public String toString() {
return dataFileName;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.wur.plantbreeding.gff2RDF;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.wur.plantbreeding.gff2RDF.Arabidopsis.At_Gene;
import nl.wur.plantbreeding.gff2RDF.Arabidopsis.At_GeneProtein;
import nl.wur.plantbreeding.gff2RDF.Arabidopsis.At_Marker;
import org.apache.commons.lang.StringEscapeUtils;
/**
* This class handles the conversion from the object used in this programm
* to the RDF model.
* @author Pierre-Yves Chibon -- py@chibon.fr
*/
public class ObjectToModel {
/**
* This is the based URI which will be used in the construction of the
* model.
*/
private final String uri = new App().getUri();
/** Logger used for outputing log information. */
private final Logger log = Logger.getLogger(
ObjectToModel.class.getName());
/**
* This method add the given Arabidopsis thaliana gene information to the
* provided Jena model and return this model.
* @param geneobj an Arabidopsis thaliana gene with information
* @param model a Jena Model
* @return a Jena Model with the gene information
*/
public final Model addToModel(final At_Gene geneobj, final Model model) {
// Set the different URI that will be used
String geneuri = uri + "GENE
String scaffolduri = uri + "SCAFFOLD
String positionuri = uri + "POSITION
String gouri = "http://purl.org/obo/owl/GO
// Create the scaffold node, add type and name
Resource scaffold = model.createResource(scaffolduri
+ geneobj.getChromosome());
scaffold.addProperty(RDF.type, scaffolduri);
if (geneobj.getChromosome() != null
&& !geneobj.getChromosome().isEmpty()) {
scaffold.addProperty(model.createProperty(scaffolduri
+ "ScaffoldName"), geneobj.getChromosome());
}
// Create the gene node and add the type and basic information
Resource gene = model.createResource(geneuri + geneobj.getLocus());
gene.addProperty(RDF.type, geneuri);
gene.addProperty(model.createProperty(geneuri + "FeatureName"),
geneobj.getLocus());
if (geneobj.getFunction() != null && !geneobj.getFunction().isEmpty()) {
gene.addProperty(model.createProperty(geneuri + "FeatureType"),
geneobj.getFunction());
}
// Create the position node, add type and start, stop and chr
// information
if (geneobj.getChromosome() != null
&& !geneobj.getChromosome().isEmpty()) {
Resource position = model.createResource();
position.addProperty(RDF.type, positionuri);
position.addProperty(model.createProperty(positionuri + "Start"),
Integer.toString(geneobj.getStart()));
position.addProperty(model.createProperty(positionuri + "Stop"),
Integer.toString(geneobj.getStop()));
position.addProperty(model.createProperty(positionuri + "Scaffold"),
geneobj.getChromosome());
gene.addProperty(model.createProperty(geneuri + "Position"),
position);
}
// Iterate over the GO term list and add them to the model
for (String go : geneobj.getGoterms()) {
String goi = go.replace(":", "_");
Resource goterm = model.createResource(gouri + goi);
goterm.addProperty(RDF.type, gouri);
goterm.addProperty(model.createProperty(gouri + "GoID"), go);
gene.addProperty(model.createProperty(geneuri + "Go"), goterm);
}
return model;
}
/**
* This function add the given Arabidopsis thaliana gene/protein relation
* information to the model.
* @param agp an At_GeneProtein containing the relation between one gene
* and one protein.
* @param model a Jena Model to add the information into.
* @return the Jena Model with the information added
*/
public final Model addToModel(final At_GeneProtein agp, final Model model) {
// Set the different URI that will be used
String geneuri = uri + "GENE
String proteinuri = "http://purl.uniprot.org/uniprot/";
// Create the gene node and add the type
Resource gene = model.createResource(geneuri + agp.getLocus());
gene.addProperty(RDF.type, geneuri);
// Create the protein node
final Resource protein = model.createResource(proteinuri
+ agp.getProtein());
// Link the gene node to the protein node
gene.addProperty(model.createProperty(geneuri + "Protein"), protein);
return model;
}
/**
* Add a Arabidopsis thaliana marker to the model.
* This marker can be either located on a genetic map (it has a Position)
* or on a physical map (it has no Position but a Start and Stop).
* @param marker a At_Marker to add to the model.
* @param model the Jena model to which the At_Marker will be added.
* @return the given Jena Model containing the original information and the
* information about the marker.
*/
public final Model addToModel(final At_Marker marker, final Model model) {
// Set the different URI that will be used
String markeruri = uri + "MARKER
String positionuri = uri + "POSITION
String mappositionuri = uri + "MAPPOSITION
// Create the gene node and add the type
Resource markerres = model.createResource(markeruri
+ marker.getName());
markerres.addProperty(model.createProperty(markeruri
+ "MarkerName"), marker.getName());
markerres.addProperty(RDF.type, markeruri);
// Create the position node
if (marker.getChromosome() != null
&& !marker.getChromosome().isEmpty()) {
if (marker.isGenetic()) {
// Genetic location of the marker
markerres.addProperty(model.createProperty(markeruri
+ "mapPosition"), marker.getPosition());
markerres.addProperty(model.createProperty(markeruri
+ "Chromosome"), marker.getChromosome());
} else {
// Physical location of the marker
Resource position = model.createResource();
position.addProperty(RDF.type, positionuri);
position.addProperty(model.createProperty(positionuri
+ "Start"), Integer.toString(marker.getStart()));
position.addProperty(model.createProperty(positionuri + "Stop"),
Integer.toString(marker.getStop()));
position.addProperty(model.createProperty(positionuri
+ "Scaffold"), "Chr" + marker.getChromosome());
markerres.addProperty(model.createProperty(markeruri
+ "Position"), position);
}
}
return model;
}
/**
* Add the given description to a given gene in the given Jena Model.
* @param geneid the geneid of the gene (used in the URI).
* @param description the description to be added to the gene.
* @param model the model in which this gene and its description go
* @return the Jena Model with the added information
*/
public final Model addGeneDescriptionToModel(final String geneid,
String description, final Model model) {
description = description.replaceAll("&
description = StringEscapeUtils.unescapeHtml(description);
description = description.replaceAll("&", "");
String geneuri = uri + "GENE
Resource gene = model.createResource(geneuri + geneid);
gene.addProperty(RDF.type, geneuri);
gene.addProperty(model.createProperty(geneuri + "Description"),
description);
return model;
}
} |
package org.biouno.unochoice.model;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.biouno.unochoice.util.Utils;
import org.jenkinsci.plugins.scriptler.ScriptlerManagement;
import org.jenkinsci.plugins.scriptler.config.Script;
import org.jenkinsci.plugins.scriptler.util.ScriptHelper;
import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.Util;
import hudson.model.ManagementLink;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* A scriptler script.
*
* @author Bruno P. Kinoshita
* @since 0.1
*/
public class ScriptlerScript extends AbstractScript {
/*
* Serial UID.
*/
private static final long serialVersionUID = -6600327523009436354L;
private final String scriptlerScriptId;
// Map is not serializable, but LinkedHashMap is. Ignore static analysis errors
private final Map<String, String> parameters;
@DataBoundConstructor
public ScriptlerScript(String scriptlerScriptId, List<ScriptlerScriptParameter> parameters) {
super();
this.scriptlerScriptId = scriptlerScriptId;
this.parameters = new LinkedHashMap<String, String>();
if (parameters != null) {
for (ScriptlerScriptParameter parameter : parameters) {
this.parameters.put(parameter.getName(), parameter.getValue());
}
}
}
/**
* @return the scriptlerScriptId
*/
public String getScriptlerScriptId() {
return scriptlerScriptId;
}
/**
* @return the parameters
*/
public Map<String, String> getParameters() {
return parameters;
}
@Override
public Object eval() {
return eval(null);
}
/*
* (non-Javadoc)
* @see org.biouno.unochoice.model.Script#eval(java.util.Map)
*/
@Override
public Object eval(Map<String, String> parameters) {
final Map<String, String> envVars = Utils.getSystemEnv();
Map<String, String> evaledParameters = new LinkedHashMap<String, String>(envVars);
// if we have any parameter that came from UI, let's eval and use them
if (parameters != null && !parameters.isEmpty()) {
// fill our map with the given parameters
evaledParameters.putAll(parameters);
// and now try to expand env vars
for (String key : this.getParameters().keySet()) {
String value = this.getParameters().get(key);
value = Util.replaceMacro((String) value, parameters);
evaledParameters.put(key, value);
}
} else {
evaledParameters.putAll(this.getParameters());
}
return this.toGroovyScript().eval(evaledParameters);
}
/**
* Converts this scriptler script to a GroovyScript.
*
* @return a GroovyScript
*/
public GroovyScript toGroovyScript() {
final Script scriptler = ScriptHelper.getScript(getScriptlerScriptId(), true);
if (scriptler == null) {
throw new RuntimeException("Missing required scriptler!");
}
return new GroovyScript(new SecureGroovyScript(scriptler.script, false, null), null);
}
@Extension(optional = true)
public static class DescriptorImpl extends ScriptDescriptor {
static {
// make sure this class fails to load during extension discovery if scriptler isn't present
ScriptlerManagement.getScriptlerHomeDirectory();
}
/*
* (non-Javadoc)
*
* @see hudson.model.Descriptor#getDisplayName()
*/
@Override
public String getDisplayName() {
return "Scriptler Script";
}
@Override
public AbstractScript newInstance(StaplerRequest req, JSONObject jsonObject) throws FormException {
ScriptlerScript script = null;
String scriptScriptId = jsonObject.getString("scriptlerScriptId");
if (scriptScriptId != null && !scriptScriptId.trim().equals("")) {
List<ScriptlerScriptParameter> parameters = new ArrayList<ScriptlerScriptParameter>();
final JSONObject defineParams = jsonObject.getJSONObject("defineParams");
if (defineParams != null && !defineParams.isNullObject()) {
JSONObject argsObj = defineParams.optJSONObject("parameters");
if (argsObj == null) {
JSONArray argsArrayObj = defineParams.optJSONArray("parameters");
if (argsArrayObj != null) {
for (int i = 0; i < argsArrayObj.size(); i++) {
JSONObject obj = argsArrayObj.getJSONObject(i);
String name = obj.getString("name");
String value = obj.getString("value");
if (name != null && !name.trim().equals("") && value != null) {
ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value);
parameters.add(param);
}
}
}
} else {
String name = argsObj.getString("name");
String value = argsObj.getString("value");
if (name != null && !name.trim().equals("") && value != null) {
ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value);
parameters.add(param);
}
}
}
script = new ScriptlerScript(scriptScriptId, parameters);
}
return script;
}
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private ManagementLink getScriptler() {
return Jenkins.getInstanceOrNull().getExtensionList(ScriptlerManagement.class).get(0);
}
/**
* gets the argument description to be displayed on the screen when selecting a config in the dropdown
*
* @param scriptlerScriptId
* the config id to get the arguments description for
* @return the description
*/
@JavaScriptMethod
public JSONArray getParameters(String scriptlerScriptId) {
final ManagementLink scriptler = this.getScriptler();
if (scriptler != null) {
ScriptlerManagement scriptlerManagement = (ScriptlerManagement) scriptler;
final Script script = scriptlerManagement.getConfiguration().getScriptById(scriptlerScriptId);
if (script != null && script.getParameters() != null) {
return JSONArray.fromObject(script.getParameters());
}
}
return null;
}
}
} |
package org.deepsymmetry.beatlink.data;
import io.kaitai.struct.RandomAccessFileKaitaiStream;
import org.deepsymmetry.beatlink.*;
import org.deepsymmetry.cratedigger.Database;
import org.deepsymmetry.cratedigger.FileFetcher;
import org.deepsymmetry.cratedigger.pdb.RekordboxAnlz;
import org.deepsymmetry.cratedigger.pdb.RekordboxPdb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class CrateDigger {
private final Logger logger = LoggerFactory.getLogger(CrateDigger.class);
/**
* How many times we will try to download a file from a player before giving up.
*/
private final AtomicInteger retryLimit = new AtomicInteger(3);
/**
* Check how many times we will try to download a file from a player before giving up.
*
* @return the maximum number of attempts we will make when a file download fails
*/
public int getRetryLimit() {
return retryLimit.get();
}
/**
* Set how many times we will try to download a file from a player before giving up.
*
* @param limit the maximum number of attempts we will make when a file download fails
*/
public void setRetryLimit(int limit) {
if (limit < 1 || limit > 10) {
throw new IllegalArgumentException("limit must be between 1 and 10");
}
retryLimit.set(limit);
}
/**
* Keep track of whether we are running.
*/
private final AtomicBoolean running = new AtomicBoolean(false);
/**
* Check whether we are currently running.
*
* @return true if track metadata is being fetched using NFS for all active players
*/
@SuppressWarnings("WeakerAccess")
public boolean isRunning() {
return running.get();
}
/**
* Allows us to automatically shut down when the {@link MetadataFinder}, which we depend on, does, and start
* back up once it resumes.
*/
@SuppressWarnings("FieldCanBeLocal")
private final LifecycleListener lifecycleListener = new LifecycleListener() {
@Override
public void started(final LifecycleParticipant sender) {
new Thread(new Runnable() {
@Override
public void run() {
try {
logger.info("CrateDigger starting because {} has.", sender);
start();
} catch (Throwable t) {
logger.error("Problem starting the CrateDigger in response to a lifecycle event.", t);
}
}
}).start();
}
@Override
public void stopped(final LifecycleParticipant sender) {
if (isRunning()) {
logger.info("CrateDigger stopping because {} has.", sender);
stop();
}
}
};
/**
* Clear the {@link org.deepsymmetry.cratedigger.FileFetcher} cache when media is unmounted, so it does not try
* to use stale filesystem handles. Also clear up our own caches for the vanished media, and close the files
* associated with the parsed database structures.
*/
private final MountListener mountListener = new MountListener() {
@Override
public void mediaMounted(SlotReference slot) {
// Nothing for us to do here yet, we need to wait until the media details are available.
}
@Override
public void mediaUnmounted(SlotReference slot) {
DeviceAnnouncement player = DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player);
if (player != null) {
FileFetcher.getInstance().removePlayer(player.getAddress());
final Database database = databases.remove(slot);
if (database != null) {
deliverDatabaseUpdate(slot, database, false);
try {
database.close();
} catch (IOException e) {
logger.error("Problem closing parsed rekordbox database export.", e);
}
//noinspection ResultOfMethodCallIgnored
database.sourceFile.delete();
}
final String prefix = slotPrefix(slot);
File[] files = downloadDirectory.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().startsWith(prefix)) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
}
} else {
logger.info("Ignoring unmount from player that we can't find, must have left network.");
}
}
};
/**
* Clear the {@link org.deepsymmetry.cratedigger.FileFetcher} cache when players disappear, so it does not try
* to use stale filesystem handles. Our own caches will be cleaned up by {@link #mountListener}.
*/
@SuppressWarnings("FieldCanBeLocal")
private final DeviceAnnouncementListener deviceListener = new DeviceAnnouncementAdapter() {
@Override
public void deviceLost(DeviceAnnouncement announcement) {
FileFetcher.getInstance().removePlayer(announcement.getAddress());
}
};
/**
* Keep track of the slots we are currently trying to fetch local databases for, so we only do it once even if
* multiple media details responses arrive while we are working on the first.
*/
private final Set<SlotReference> activeRequests = Collections.newSetFromMap(new ConcurrentHashMap<SlotReference, Boolean>());
/**
* Holds the local databases we have fetched for mounted media, so we can use them to respond to metadata requests.
*/
private final Map<SlotReference, Database> databases = new ConcurrentHashMap<SlotReference, Database>();
private String mountPath(CdjStatus.TrackSourceSlot slot) {
switch (slot) {
case SD_SLOT: return "/B/";
case USB_SLOT: return "/C/";
}
throw new IllegalArgumentException("Don't know how to NFS mount filesystem for slot " + slot);
}
/**
* Helper method to call the {@link FileFetcher} with the right arguments to get a file for a particular slot. Also
* arranges for the file to be deleted when we are shutting down in case we fail to clean it up ourselves.
*
* @param slot the slot from which a file is desired
* @param path the path to the file within the slot's mounted filesystem
* @param destination where to write the file contents
*
* @throws IOException if there is a problem fetching the file
*/
private void fetchFile(SlotReference slot, String path, File destination) throws IOException {
destination.deleteOnExit();
final DeviceAnnouncement player = DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player);
if (player == null) {
throw new IOException("Cannot fetch file from player that is not found on the network; slot: " + slot);
}
int triesLeft = getRetryLimit();
while (triesLeft > 0) {
try {
FileFetcher.getInstance().fetch(player.getAddress(), mountPath(slot.slot), path, destination);
return;
} catch (IOException e) {
triesLeft
if (triesLeft > 0) {
logger.warn("Attempt to fetch file from player failed, tries left: " + triesLeft, e);
} else {
throw e;
}
}
}
}
/**
* Format the filename prefix that will be used to store files downloaded from a particular player slot.
* This allows them all to be cleaned up when that slot is unmounted or the player goes away.
*
* @param slotReference the slot from which files are being downloaded
*
* @return the prefix with which the names of all files downloaded from that slot will start
*/
private String slotPrefix(SlotReference slotReference) {
return "player-" + slotReference.player + "-slot-" + slotReference.slot.protocolValue + "-";
}
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
@SuppressWarnings("SpellCheckingInspection") String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
/**
* Whenever we learn media details about a newly-mounted media slot, if it is rekordbox media, start the process
* of fetching and parsing the database so we can offer metadata for that slot.
*/
private final MediaDetailsListener mediaDetailsListener = new MediaDetailsListener() {
@Override
public void detailsAvailable(final MediaDetails details) {
if (isRunning() && details.mediaType == CdjStatus.TrackType.REKORDBOX &&
details.slotReference.slot != CdjStatus.TrackSourceSlot.COLLECTION && // We always use dbserver to talk to rekordbox
!databases.containsKey(details.slotReference) &&
activeRequests.add(details.slotReference)) {
new Thread(new Runnable() {
@Override
public void run() {
File file = null;
try {
file = new File(downloadDirectory, slotPrefix(details.slotReference) + "export.pdb");
logger.info("Fetching rekordbox export.pdb from player " + details.slotReference.player +
", slot " + details.slotReference.slot);
long started = System.nanoTime();
fetchFile(details.slotReference, "PIONEER/rekordbox/export.pdb", file);
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
logger.info("Finished fetching export.pdb from player " + details.slotReference.player +
", slot " + details.slotReference.slot + "; received " +
humanReadableByteCount(file.length(), true) + " in " + duration + "ms, " +
humanReadableByteCount(file.length() * 1000 / duration, true) + "/s.");
started = System.nanoTime();
Database database = new Database(file);
duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
logger.info("Parsing database took " + duration + "ms, " +
(database.trackIndex.size() * 1000 / duration) + " tracks/s");
databases.put(details.slotReference, database);
deliverDatabaseUpdate(details.slotReference, database, true);
} catch (Throwable t) {
logger.error("Problem fetching rekordbox database for media " + details +
", will not offer metadata for it.", t);
if (file != null) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
} finally {
activeRequests.remove(details.slotReference);
}
}
}).start();
}
}
};
/**
* Find the database we have downloaded and parsed that can provide information about the supplied data
* reference, if any.
*
* @param reference identifies the location from which data is desired
*
* @return the appropriate rekordbox extract to start from in finding that data, if we have one
*/
@SuppressWarnings("WeakerAccess")
public Database findDatabase(DataReference reference) {
return databases.get(reference.getSlotReference());
}
/**
* Find the database we have downloaded and parsed that can provide information about the supplied slot
* reference, if any.
*
* @param slot identifies the slot from which data is desired
*
* @return the appropriate rekordbox extract to start from in finding that data, if we have one
*/
public Database findDatabase(SlotReference slot) {
return databases.get(slot);
}
/**
* Find the analysis file for the specified track, downloading it from the player if we have not already done so.
* Be sure to call {@code _io().close()} when you are done using the returned struct.
*
* @param track the track whose analysis file is desired
* @param database the parsed database export from which the analysis path can be determined
*
* @return the parsed file containing the track analysis
*/
private RekordboxAnlz findTrackAnalysis(DataReference track, Database database) {
File file = null;
try {
RekordboxPdb.TrackRow trackRow = database.trackIndex.get((long) track.rekordboxId);
if (trackRow != null) {
file = new File(downloadDirectory, slotPrefix(track.getSlotReference()) +
"track-" + track.rekordboxId + "-anlz.dat");
final String filePath = file.getCanonicalPath();
try {
synchronized (Util.allocateNamedLock(filePath)) {
if (file.canRead()) { // We have already downloaded it.
return new RekordboxAnlz(new RandomAccessFileKaitaiStream(filePath));
}
file.deleteOnExit(); // Prepare to download it.
fetchFile(track.getSlotReference(), Database.getText(trackRow.analyzePath()), file);
return new RekordboxAnlz(new RandomAccessFileKaitaiStream(filePath));
}
} finally {
Util.freeNamedLock(filePath);
}
} else {
logger.warn("Unable to find track " + track + " in database " + database);
}
} catch (Exception e) {
logger.error("Problem fetching analysis file for track " + track + " from database " + database, e);
if (file != null) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
return null;
}
/**
* Find the extended analysis file for the specified track, downloading it from the player if we have not already
* done so. Be sure to call {@code _io().close()} when you are done using the returned struct.
*
* @param track the track whose extended analysis file is desired
* @param database the parsed database export from which the analysis path can be determined
*
* @return the parsed file containing the track analysis
*/
private RekordboxAnlz findExtendedAnalysis(DataReference track, Database database) {
File file = null;
try {
RekordboxPdb.TrackRow trackRow = database.trackIndex.get((long) track.rekordboxId);
if (trackRow != null) {
file = new File(downloadDirectory, slotPrefix(track.getSlotReference()) +
"track-" + track.rekordboxId + "-anlz.ext");
final String filePath = file.getCanonicalPath();
try {
synchronized (Util.allocateNamedLock(filePath)) {
if (file.canRead()) { // We have already downloaded it.
return new RekordboxAnlz(new RandomAccessFileKaitaiStream(filePath));
}
file.deleteOnExit(); // Prepare to download it.
final String analyzePath = Database.getText(trackRow.analyzePath());
final String extendedPath = analyzePath.replaceAll("\\.DAT$", ".EXT");
fetchFile(track.getSlotReference(), extendedPath, file);
return new RekordboxAnlz(new RandomAccessFileKaitaiStream(filePath));
}
} finally {
Util.freeNamedLock(filePath);
}
} else {
logger.warn("Unable to find track " + track + " in database " + database);
}
} catch (Exception e) {
logger.error("Problem fetching extended analysis file for track " + track + " from database " + database, e);
if (file != null) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
return null;
}
/**
* This is the mechanism by which we offer metadata to the {@link MetadataProvider} while we are running.
*/
private final MetadataProvider metadataProvider = new MetadataProvider() {
@Override
public List<MediaDetails> supportedMedia() {
return null; // We can potentially answer any query.
}
@Override
public TrackMetadata getTrackMetadata(MediaDetails sourceMedia, DataReference track) {
Database database = findDatabase(track);
if (database != null) {
try {
return new TrackMetadata(track, database, getCueList(sourceMedia, track));
} catch (Exception e) {
logger.error("Problem fetching metadata for track " + track + " from database " + database, e);
}
}
return null;
}
@Override
public AlbumArt getAlbumArt(MediaDetails sourceMedia, DataReference art) {
File file = null;
Database database = findDatabase(art);
if (database != null) {
try {
RekordboxPdb.ArtworkRow artworkRow = database.artworkIndex.get((long) art.rekordboxId);
if (artworkRow != null) {
file = new File(downloadDirectory, slotPrefix(art.getSlotReference()) +
"art-" + art.rekordboxId + ".jpg");
if (file.canRead()) {
return new AlbumArt(art, file);
}
file.deleteOnExit(); // Prepare to download it.
fetchFile(art.getSlotReference(), Database.getText(artworkRow.path()), file);
return new AlbumArt(art, file);
} else {
logger.warn("Unable to find artwork " + art + " in database " + database);
}
} catch (Exception e) {
logger.warn("Problem fetching artwork " + art + " from database " + database, e);
if (file != null) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
}
return null;
}
@Override
public BeatGrid getBeatGrid(MediaDetails sourceMedia, DataReference track) {
Database database = findDatabase(track);
if (database != null) {
try {
RekordboxAnlz file = findTrackAnalysis(track, database);
if (file != null) {
try {
return new BeatGrid(track, file);
} finally {
file._io().close();
}
}
} catch (Exception e) {
logger.error("Problem fetching beat grid for track " + track + " from database " + database, e);
}
}
return null;
}
@Override
public CueList getCueList(MediaDetails sourceMedia, DataReference track) {
Database database = findDatabase(track);
if (database != null) {
try {
RekordboxAnlz file = findTrackAnalysis(track, database);
if (file != null) {
try {
return new CueList(file);
} finally {
file._io().close();
}
}
} catch (Exception e) {
logger.error("Problem fetching cue list for track " + track + " from database " + database, e);
}
}
return null;
}
@Override
public WaveformPreview getWaveformPreview(MediaDetails sourceMedia, DataReference track) {
Database database = findDatabase(track);
if (database != null) {
try {
RekordboxAnlz file = findExtendedAnalysis(track, database); // Look for color preview first
if (file != null) {
try {
return new WaveformPreview(track, file);
} finally {
file._io().close();
}
}
} catch (IllegalStateException e) {
logger.info("No color preview waveform found, checking for blue version.");
} catch (Exception e) {
logger.error("Problem fetching color waveform preview for track " + track + " from database " + database, e);
}
try {
RekordboxAnlz file = findTrackAnalysis(track, database);
if (file != null) {
try {
return new WaveformPreview(track, file);
} finally {
file._io().close();
}
}
} catch (Exception e) {
logger.error("Problem fetching waveform preview for track " + track + " from database " + database, e);
}
}
return null;
}
@Override
public WaveformDetail getWaveformDetail(MediaDetails sourceMedia, DataReference track) {
Database database = findDatabase(track);
if (database != null) {
try {
RekordboxAnlz file = findExtendedAnalysis(track, database);
if (file != null) {
try {
return new WaveformDetail(track, file);
} finally {
file._io().close();
}
}
} catch (Exception e) {
logger.error("Problem fetching waveform preview for track " + track + " from database " + database, e);
}
}
return null;
}
};
/**
* Start finding track metadata for all active players using the NFS server on the players to pull the exported
* database and track analysis files. Starts the {@link MetadataFinder} if it is not already
* running, because we build on its features. This will transitively start many of the other Beat Link subsystems,
* and stopping any of them will stop us as well.
*
* @throws Exception if there is a problem starting the required components
*/
@SuppressWarnings("WeakerAccess")
public synchronized void start() throws Exception {
if (!isRunning()) {
MetadataFinder.getInstance().start();
running.set(true);
// Try fetching the databases of anything that was already mounted before we started.
for (MediaDetails details : MetadataFinder.getInstance().getMountedMediaDetails()) {
mediaDetailsListener.detailsAvailable(details);
}
MetadataFinder.getInstance().addMetadataProvider(metadataProvider);
}
}
/**
* Stop finding track metadata for all active players.
*/
@SuppressWarnings("WeakerAccess")
public synchronized void stop() {
if (isRunning()) {
running.set(false);
MetadataFinder.getInstance().removeMetadataProvider(metadataProvider);
for (Database database : databases.values()) {
//noinspection ResultOfMethodCallIgnored
database.sourceFile.delete();
}
databases.clear();
}
}
/**
* Holds the singleton instance of this class.
*/
private static final CrateDigger instance = new CrateDigger();
/**
* Get the singleton instance of this class.
*
* @return the only instance of this class which exists.
*/
public static CrateDigger getInstance() {
return instance;
}
/**
* The folder into which database exports and track analysis files will be downloaded.
*/
@SuppressWarnings("WeakerAccess")
public final File downloadDirectory;
/**
* The number of variations on the file name we will attempt when creating our temporary directory.
*/
private static final int TEMP_DIR_ATTEMPTS = 1000;
/**
* Create the directory into which we can download (and reuse) database exports and track analysis files.
*
* @return the created temporary directory.
*/
private File createDownloadDirectory() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseName = "bl-" + System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create download directory within " + TEMP_DIR_ATTEMPTS + " attempts.");
}
/**
* Keeps track of the registered database listeners.
*/
private final Set<DatabaseListener> dbListeners =
Collections.newSetFromMap(new ConcurrentHashMap<DatabaseListener, Boolean>());
public void addDatabaseListener(DatabaseListener listener) {
if (listener != null) {
dbListeners.add(listener);
}
}
/**
* Removes the specified database listener so that it no longer receives updates when there
* are changes to the available set of rekordbox databases. If {@code listener} is {@code null} or not present
* in the set of registered listeners, no exception is thrown and no action is performed.
*
* @param listener the cache update listener to remove
*/
public void removeDatabaseListener(DatabaseListener listener) {
if (listener != null) {
dbListeners.remove(listener);
}
}
@SuppressWarnings("WeakerAccess")
public Set<DatabaseListener> getDatabaseListeners() {
// Make a copy so callers get an immutable snapshot of the current state.
return Collections.unmodifiableSet(new HashSet<DatabaseListener>(dbListeners));
}
/**
* Send a database announcement to all registered listeners.
*
* @param slot the media slot whose database availability has changed
* @param database the database whose relevance has changed
* @param available if {@code} true, the database is newly available, otherwise it is no longer relevant
*/
private void deliverDatabaseUpdate(SlotReference slot, Database database, boolean available) {
for (final DatabaseListener listener : getDatabaseListeners()) {
try {
if (available) {
listener.databaseMounted(slot, database);
} else {
listener.databaseUnmounted(slot, database);
}
} catch (Throwable t) {
logger.warn("Problem delivering rekordbox database availability update to listener", t);
}
}
}
/**
* Prevent direct instantiation, create a temporary directory for our file downloads,
* and register the listeners that hook us into the streams of information we need.
*/
private CrateDigger() {
MetadataFinder.getInstance().addLifecycleListener(lifecycleListener);
MetadataFinder.getInstance().addMountListener(mountListener);
DeviceFinder.getInstance().addDeviceAnnouncementListener(deviceListener);
VirtualCdj.getInstance().addMediaDetailsListener(mediaDetailsListener);
downloadDirectory = createDownloadDirectory();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("MetadataFinder[").append("running: ").append(isRunning());
if (isRunning()) {
sb.append(", databases mounted: ").append(databases.size());
sb.append(", download directory: ").append(downloadDirectory.getAbsolutePath());
}
return sb.append("]").toString();
}
} |
package org.esupportail.smsu.services;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
public class UrlGenerator {
private final Logger logger = new LoggerImpl(getClass());
private String serverURL;
private String contextPath;
public String baseURL(HttpServletRequest request) {
try {
return get_baseURL(request, serverURL, contextPath);
} catch (IOException e) {
logger.error(e);
return null;
}
}
public String goTo(HttpServletRequest request, String then) {
return baseURL(request) + "/#" + then;
}
static public String get_baseURL(HttpServletRequest request, String serverURL, String contextPath) throws IOException {
if (StringUtils.isBlank(contextPath)) {
contextPath = request.getContextPath();
}
contextPath = contextPath.replaceFirst("/$", "");
return serverURL + contextPath;
}
// since java-cas-client breaks its serverName when the port is not explicit,
// we end up here with urls with explicit ports even when unneeded.
// alas angularjs $sceDelegateProvider.resourceUrlWhitelist does not like this it seems,
// so a nice cleanup here will help
// (also cleanup trailing slash that would break web.xml <url-pattern> in case of double "/")
private String cleanupServerUrl(String serverURL) {
serverURL = serverURL.replaceFirst("/$", "");
if (serverURL.startsWith("http:
return serverURL.replaceFirst(":80/?$", "");
else if (serverURL.startsWith("https:
return serverURL.replaceFirst(":443/?$", "");
else
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = cleanupServerUrl(serverURL);
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
} |
package org.helianto.security.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import org.helianto.core.def.ActivityState;
import org.helianto.user.domain.UserGroup;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Domain class to represent user authority.
*
* Grants roles to user groups.
*
* @author mauriciofernandesdecastro
*/
@javax.persistence.Entity
@Table(name="core_authority",
uniqueConstraints = {
@UniqueConstraint(columnNames={"userGroupId", "serviceCode"})
}
)
public class UserAuthority implements Serializable {
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Version
private int version;
@JsonIgnore
@ManyToOne
@JoinColumn(name="userGroupId", nullable=true)
private UserGroup userGroup;
@Transient
private Integer userGroupId = 0;
@Transient
private String userGroupName = "";
@Column(length=20)
private String serviceCode;
@Column(length=128)
private String serviceExtension;
@Column(length=20)
@Enumerated(EnumType.STRING)
private ActivityState authorityState = ActivityState.ACTIVE;
@Transient
private Integer selfIdentityId = 0;
/**
* Constructor.
*/
public UserAuthority() {
super();
}
/**
* Constructor.
*
* @param userGroup
* @param serviceCode
*/
public UserAuthority(UserGroup userGroup, String serviceCode) {
this();
setUserGroup(userGroup);
setServiceCode(serviceCode);
}
/**
* Constructor.
*
* @param userGroup
* @param serviceCode
* @param extensions
*/
public UserAuthority(UserGroup userGroup, String serviceCode, String extensions) {
this(userGroup, serviceCode);
setServiceExtension(extensions);
}
/**
* Constructor.
*
* @param id
* @param userGroupId
* @param serviceCode
* @param serviceExtension
*/
public UserAuthority(
Integer id
, Integer userGroupId
, String serviceCode
, String serviceExtension) {
this();
this.id = id;
this.userGroupId = userGroupId;
this.serviceCode = serviceCode;
this.serviceExtension = serviceExtension;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/**
* User group where authorities are applied.
*/
public UserGroup getUserGroup() {
return userGroup;
}
public void setUserGroup(UserGroup userGroup) {
this.userGroup = userGroup;
}
/**
* <<Transient>> user group id.
*/
public Integer getUserGroupId() {
if (getUserGroup()!=null) {
return getUserGroup().getId();
}
return userGroupId;
}
public void setUserGroupId(Integer userGroupId) {
this.userGroupId = userGroupId;
}
/**
* <<Transient>> user group name.
*/
public String getUserGroupName() {
if (getUserGroup()!=null) {
return getUserGroup().getUserName();
}
return userGroupName;
}
public void setUserGroupName(String userGroupName) {
this.userGroupName = userGroupName;
}
/**
* Service code.
*/
public String getServiceCode() {
return serviceCode;
}
public void setServiceCode(String serviceCode) {
this.serviceCode = serviceCode;
}
public String getServiceExtension() {
return serviceExtension;
}
public void setServiceExtension(String serviceExtension) {
this.serviceExtension = serviceExtension;
}
public ActivityState getAuthorityState() {
return authorityState;
}
public void setAuthorityState(ActivityState authorityState) {
this.authorityState = authorityState;
}
/**
* <<Transient>> self identity id.
*
* <p>Convenient transient field to provide the logged user with privileges
* assigned to herself.</p>
*/
public Integer getSelfIdentityId() {
return selfIdentityId;
}
public void setSelfIdentityId(Integer selfIdentityId) {
this.selfIdentityId = selfIdentityId;
}
/**
* Expands user authorities to user roles, including "ROLE_SELF_ID_x", where
* x is the authorized user identity primary key.
*
* @param userRole
* @param identityId
*/
public static List<String> getRoleNames(List<UserAuthority> adapterList, Integer identityId) {
List<String> roleNames = new ArrayList<>();
for (UserAuthority userAuthorityReadAdapter: adapterList) {
roleNames.addAll(getUserAuthoritiesAsString(
userAuthorityReadAdapter.getServiceCode()
, userAuthorityReadAdapter.getServiceExtension()
, identityId));
}
return roleNames;
}
/**
* Converts user roles to authorities, including "ROLE_SELF_ID_x", where
* x is the authorized user identity primary key.
*
* @param serviceName
* @param serviceExtensions
* @param identityId
*/
public static Set<String> getUserAuthoritiesAsString(String serviceName, String serviceExtensions, int identityId) {
Set<String> roleNames = new LinkedHashSet<String>();
if (identityId>0) {
roleNames.add(formatRole("SELF", new StringBuilder("ID_").append(identityId).toString()));
}
roleNames.add(formatRole(serviceName, null));
String[] extensions = serviceExtensions.split(",");
for (String extension: extensions) {
roleNames.add(formatRole(serviceName, extension));
}
return roleNames;
}
/**
* Convenient conversion for authorities.
*/
public Set<String> getUserAuthoritiesAsString() {
return getUserAuthoritiesAsString(getServiceCode(), getServiceExtension(), getSelfIdentityId());
}
/**
* Internal role formatter.
*
* @param serviceName
* @param extension
*/
public static String formatRole(String serviceName, String extension) {
StringBuilder sb = new StringBuilder("ROLE_").append(serviceName.toUpperCase());
if (extension!=null && extension.length()>0) {
sb.append("_").append(extension.trim());
}
return sb.toString();
}
/**
* Merger.
*
* @param command
*/
public UserAuthority merge(UserAuthority command) {
setServiceCode(command.getServiceCode());
setServiceExtension(command.getServiceExtension());
setAuthorityState(command.getAuthorityState());
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((serviceCode == null) ? 0 : serviceCode.hashCode());
result = prime * result
+ ((userGroup == null) ? 0 : userGroup.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAuthority other = (UserAuthority) obj;
if (serviceCode == null) {
if (other.serviceCode != null)
return false;
} else if (!serviceCode.equals(other.serviceCode))
return false;
if (userGroup == null) {
if (other.userGroup != null)
return false;
} else if (!userGroup.equals(other.userGroup))
return false;
return true;
}
} |
package org.jgroups.protocols.kubernetes;
import org.jgroups.Address;
import org.jgroups.PhysicalAddress;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.Property;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.kubernetes.stream.CertificateStreamProvider;
import org.jgroups.protocols.kubernetes.stream.InsecureStreamProvider;
import org.jgroups.protocols.kubernetes.stream.StreamProvider;
import org.jgroups.protocols.TCPPING;
import org.jgroups.protocols.TP;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Responses;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.jgroups.protocols.kubernetes.Utils.readFileToString;
@MBean(description="Kubernetes based discovery protocol")
public class KUBE_PING extends TCPPING {
protected static final short KUBERNETES_PING_ID=2017;
static {
ClassConfigurator.addProtocol(KUBERNETES_PING_ID, KUBE_PING.class);
}
@Property(description="Max time (in millis) to wait for a connection to the Kubernetes server. If exceeded, " +
"an exception will be thrown", systemProperty="KUBERNETES_CONNECT_TIMEOUT")
protected int connectTimeout=5000;
@Property(description="Max time (in millis) to wait for a response from the Kubernetes server",
systemProperty="KUBERNETES_READ_TIMEOUT")
protected int readTimeout=30000;
@Property(description="Max number of attempts to send discovery requests", systemProperty="KUBERNETES_OPERATION_ATTEMPTS")
protected int operationAttempts=3;
@Property(description="Time (in millis) between operation attempts", systemProperty="KUBERNETES_OPERATION_SLEEP")
protected long operationSleep=1000;
@Property(description="http (default) or https. Used to send the initial discovery request to the Kubernetes server",
systemProperty="KUBERNETES_MASTER_PROTOCOL")
protected String masterProtocol="https";
@Property(description="The URL of the Kubernetes server", systemProperty="KUBERNETES_SERVICE_HOST")
protected String masterHost;
@Property(description="The port on which the Kubernetes server is listening", systemProperty="KUBERNETES_SERVICE_PORT")
protected int masterPort;
@Property(description="The version of the protocol to the Kubernetes server", systemProperty="KUBERNETES_API_VERSION")
protected String apiVersion="v1";
@Property(description="namespace", systemProperty="OPENSHIFT_KUBE_PING_NAMESPACE")
protected String namespace; // DO NOT HARDCODE A DEFAULT (i.e.: "default") - SEE isClusteringEnabled() and init() METHODS BELOW!
@Property(description="The labels to use in the discovery request to the Kubernetes server",
systemProperty="KUBERNETES_LABELS")
protected String labels;
@Property(description="Certificate to access the Kubernetes server", systemProperty="KUBERNETES_CLIENT_CERTIFICATE_FILE")
protected String clientCertFile;
@Property(description="Client key file (store)", systemProperty="KUBERNETES_CLIENT_KEY_FILE")
protected String clientKeyFile;
@Property(description="The password to access the client key store", systemProperty="KUBERNETES_CLIENT_KEY_PASSWORD")
protected String clientKeyPassword;
@Property(description="The algorithm used by the client", systemProperty="KUBERNETES_CLIENT_KEY_ALGO")
protected String clientKeyAlgo="RSA";
@Property(description="Client CA certificate", systemProperty="KUBERNETES_CA_CERTIFICATE_FILE")
protected String caCertFile;
@Property(description="Token file", systemProperty="SA_TOKEN_FILE")
protected String saTokenFile="/var/run/secrets/kubernetes.io/serviceaccount/token";
protected Client client;
protected int tp_bind_port;
public void setMasterHost(String masterMost) {
this.masterHost=masterMost;
}
public void setMasterPort(int masterPort) {
this.masterPort=masterPort;
}
public void setNamespace(String namespace) {
this.namespace=namespace;
}
protected boolean isClusteringEnabled() {
return namespace != null;
}
public void init() throws Exception {
super.init();
TP transport=getTransport();
tp_bind_port=transport.getBindPort();
if(tp_bind_port <= 0)
throw new IllegalArgumentException(String.format("%s only works with %s.bind_port > 0",
KUBE_PING.class.getSimpleName(), transport.getClass().getSimpleName()));
if(namespace == null) {
log.warn("namespace not set; clustering disabled");
return; // no further initialization necessary
}
log.info("namespace %s set; clustering enabled", namespace);
Map<String,String> headers=new HashMap<>();
StreamProvider streamProvider;
if(clientCertFile != null) {
if(masterProtocol == null)
masterProtocol="http";
streamProvider=new CertificateStreamProvider(clientCertFile, clientKeyFile, clientKeyPassword, clientKeyAlgo, caCertFile);
}
else {
String saToken=readFileToString(saTokenFile);
if(saToken != null) {
// curl -k -H "Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)" \
headers.put("Authorization", "Bearer " + saToken);
}
streamProvider=new InsecureStreamProvider();
}
String url=String.format("%s://%s:%s/api/%s", masterProtocol, masterHost, masterPort, apiVersion);
client=new Client(url, headers, connectTimeout, readTimeout, operationAttempts, operationSleep, streamProvider, log);
log.debug("KubePING configuration: " + toString());
populateInitialHosts();
}
@Override public void destroy() {
client=null;
super.destroy();
}
public void findMembers(List<Address> members, boolean initial_discovery, Responses responses) {
if(!initial_discovery)
populateInitialHosts();
super.findMembers(members, initial_discovery, responses);
}
protected void populateInitialHosts() {
List<InetAddress> hosts=readAll();
if(hosts == null || hosts.isEmpty()) {
log.warn("initial_hosts could not be populated with information from Kubernetes");
return;
}
List<PhysicalAddress> tcpping_hosts=getInitialHosts();
for(InetAddress host: hosts) {
for(int i=0; i <= getPortRange(); i++) {
IpAddress addr=new IpAddress(host, tp_bind_port+i);
if(!tcpping_hosts.contains(addr)) {
tcpping_hosts.add(addr);
log.debug("added %s to initial_hosts", addr);
}
}
}
}
protected List<InetAddress> readAll() {
if(isClusteringEnabled()) {
return doReadAll(cluster_name);
}
else {
return Collections.emptyList();
}
}
protected List<InetAddress> readAllTest() {
if(isClusteringEnabled())
try {
return Collections.singletonList(InetAddress.getByName("127.0.0.1"));
}
catch(UnknownHostException e) {
log.error("failed reading IP address", e);
}
return Collections.emptyList();
}
protected List<InetAddress> doReadAll(String clusterName) {
try {
if(client != null)
return client.getPods(namespace, labels);
}
catch(Exception e) {
log.warn("Problem getting Pod json from Kubernetes %s for cluster [%s], namespace [%s], labels [%s]; encountered [%s: %s]",
client.info(), clusterName, namespace, labels, e.getClass().getName(), e.getMessage());
}
return Collections.emptyList();
}
@Override
public String toString() {
return String.format("KubePing{namespace='%s', labels='%s'}", namespace, labels);
}
} |
package org.jtrfp.trcl.ctl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.beanutils.BeanUtils;
import org.jtrfp.trcl.core.Feature;
import org.jtrfp.trcl.core.FeatureFactory;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.gui.ControllerInputDevicePanel.ControllerConfiguration;
import org.springframework.stereotype.Component;
@Component
public class ControllerMapperFactory implements FeatureFactory<Features> {
public class ControllerMapper implements Feature<Features>{
private final Collection<InputDevice> inputDevices = new ArrayList<InputDevice>();
private final Set<MappingListener<ControllerSource,ControllerMapping>> mappingListeners = new HashSet<MappingListener<ControllerSource,ControllerMapping>>();
private final Map<ControllerSource,ControllerMapping> map = new HashMap<ControllerSource,ControllerMapping>();
private final Map<String,ControllerConfiguration> recommendedDefaultConfigurations = new HashMap<String,ControllerConfiguration>();
public void registerInputDevice(InputDevice dev){
inputDevices.add(dev);
}
public void registerInputDevices(Collection<InputDevice> dev){
inputDevices.addAll(dev);
}
public Collection<InputDevice> getInputDevices(){
return inputDevices;
}//end getInputDevices()
/**
* Multiple sources may feed the same input, though their behavior is undefined if they are of different types
* i.e. button vs trigger vs axis
* @param controllerSource
* @param controllerInput
* @since Nov 12, 2015
*/
public void mapControllerSourceToInput(ControllerSource controllerSource, ControllerInput controllerInput, double scale, double offset){
final ControllerMapping mapping = new ControllerMapping(controllerSource,controllerInput,scale,offset);
map.put(controllerSource, mapping);
controllerSource.addPropertyChangeListener(mapping);
fireMappedEvent(controllerSource, mapping);
}//end mapControllerSourceToInput
public boolean unmapControllerSource(ControllerSource controllerSource){
final ControllerMapping controllerMapping = map.get(controllerSource);
if(controllerMapping==null)
return false; //Was never here to begin with
map.remove(controllerSource);
controllerSource.removePropertyChangeListener(controllerMapping);
return true;
}
private void fireMappedEvent(ControllerSource cs, ControllerMapping mapping){
for(MappingListener<ControllerSource,ControllerMapping> l:mappingListeners)
l.mapped(cs, mapping);
}// end fireMappedEvent(...)
public boolean addMappingListener(MappingListener<ControllerSource,ControllerMapping> l, boolean populate) {
boolean result = mappingListeners.add(l);
if(populate){
for(Entry<ControllerSource,ControllerMapping> entry:map.entrySet()){
l.mapped(entry.getKey(), entry.getValue());
}//end for(entries)
}//end if(populate)
return result;
}//end addMappingListener(...)
public boolean removeMappingListener(MappingListener<ControllerSource,ControllerMapping> l){
boolean result = mappingListeners.remove(l);
return result;
}//end removeMappingListener(...)
public ControllerConfiguration getRecommendedDefaultConfiguration(
InputDevice inputDevice) {
ControllerConfiguration result = recommendedDefaultConfigurations.get(inputDevice.getName());
if(result==null)
result = recommendedDefaultConfigurations.get("fallback "+inputDevice.getClass().getName());
if(result!=null){
try{result = (ControllerConfiguration)BeanUtils.cloneBean(result);}
catch(Exception e){e.printStackTrace();}
}//end if(!null)
return result;
}//end getRecommendedDefaultConfiguration()
@Override
public void apply(Features target) {
// TODO Auto-generated method stub
}
@Override
public void destruct(Features target) {
// TODO Auto-generated method stub
}
public void registerDefaultConfiguration(
ControllerConfiguration config) {
recommendedDefaultConfigurations.put(config.getIntendedController(), config);
}
}//end ControllerMapper
@Override
public Feature<Features> newInstance(Features target) {
return new ControllerMapper();
}
@Override
public Class<Features> getTargetClass() {
return Features.class;
}
@Override
public Class<? extends Feature> getFeatureClass() {
return ControllerMapper.class;
}
}//end ControllerMapperFactory |
package org.languagetool.oxygen;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Access to a LanguageTool instance via HTTP.
*/
class LanguageToolClient {
private final String url;
LanguageToolClient(String url) {
this.url = url;
}
List<RuleMatch> checkText(TextWithMapping text, String langCode) {
HttpURLConnection connection = null;
try {
String urlParameters =
"language=" + langCode.replace('_', '-') +
"&text=" + URLEncoder.encode(text.getText(), "utf-8");
URL languageToolUrl = new URL(url);
connection = openConnection(languageToolUrl);
writeParameters(urlParameters, connection);
InputStream inputStream = connection.getInputStream();
String xml = streamToString(inputStream, "utf-8");
return parseXml(xml, text);
} catch (MappingException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(
"Could not check text using LanguageTool server at URL '" + url + "':\n" +
e.getMessage() + "\n" +
"Please make sure the LanguageTool server is running at this URL or\n" +
"change the location at Options -> Preferences... -> Plugins.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private HttpURLConnection openConnection(URL languageToolUrl) throws IOException {
HttpURLConnection connection = (HttpURLConnection) languageToolUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches(false);
return connection;
}
private void writeParameters(String urlParameters, HttpURLConnection connection) throws IOException {
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
try {
wr.write(urlParameters.getBytes("UTF-8"));
} finally {
wr.flush();
wr.close();
}
}
private static String streamToString(InputStream is, String charsetName) throws IOException {
InputStreamReader isr = new InputStreamReader(is, charsetName);
try {
return readerToString(isr);
} finally {
isr.close();
}
}
private static String readerToString(Reader reader) throws IOException {
StringBuilder sb = new StringBuilder();
int readBytes = 0;
char[] chars = new char[4000];
while (readBytes >= 0) {
readBytes = reader.read(chars, 0, 4000);
if (readBytes <= 0) {
break;
}
sb.append(new String(chars, 0, readBytes));
}
return sb.toString();
}
private List<RuleMatch> parseXml(String xml, TextWithMapping text) throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
Document document = XmlTools.getDocument(xml);
NodeList nodeSet = (NodeList) xPath.evaluate("//error", document, XPathConstants.NODESET);
List<RuleMatch> matches = new ArrayList<RuleMatch>();
for (int i = 0; i < nodeSet.getLength(); i++) {
Node errorNode = nodeSet.item(i);
RuleMatch ruleMatch = getRuleMatch(text, errorNode);
matches.add(ruleMatch);
}
return matches;
}
private RuleMatch getRuleMatch(TextWithMapping text, Node errorNode) {
NamedNodeMap attributes = errorNode.getAttributes();
String message = attributes.getNamedItem("msg").getNodeValue();
Node replacementAttribute = attributes.getNamedItem("replacements");
List<String> replacements = replacementAttribute != null ?
Arrays.asList(replacementAttribute.getNodeValue().split("#")) : Collections.<String>emptyList();
String offsetStr = attributes.getNamedItem("offset").getNodeValue();
String lengthStr = attributes.getNamedItem("errorlength").getNodeValue();
Node issueType = attributes.getNamedItem("locqualityissuetype");
int offset = Integer.parseInt(offsetStr);
int length = Integer.parseInt(lengthStr);
RuleMatch ruleMatch = new RuleMatch(message, offset, offset + length, replacements, issueType != null ? issueType.getNodeValue() : null);
try {
ruleMatch.setOxygenOffsetStart(text.getOxygenPositionFor(offset) + 1);
ruleMatch.setOxygenOffsetEnd(text.getOxygenPositionFor(offset + length - 1) + 1);
} catch (Exception e) {
throw new MappingException("Could not map start or end offset of rule match '" +
ruleMatch.getMessage() + "': " + offset + "-" + (offset + length - 1), e);
}
return ruleMatch;
}
} |
package org.neo4j.gis.spatial;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.neo4j.gis.spatial.query.SearchIntersect;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.linearref.LinearLocation;
import com.vividsolutions.jts.linearref.LocationIndexedLine;
/**
* This class is a temporary location for collecting a number of spatial
* utilities before we have decided on a more complete analysis structure. Do
* not rely on this API remaining constant.
*
* @author craig
*/
public class SpatialTopologyUtils {
/**
* Inner class associating points and resulting geometry records to
* facilitate the result set returned.
*
* @author craig
*/
public static class PointResult implements
Map.Entry<Point, SpatialDatabaseRecord>, Comparable<PointResult> {
private Point point;
private SpatialDatabaseRecord record;
private double distance;
private PointResult(Point point, SpatialDatabaseRecord record,
double distance) {
this.point = point;
this.record = record;
this.distance = distance;
}
public Point getKey() {
return point;
}
public SpatialDatabaseRecord getValue() {
return record;
}
public double getDistance() {
return distance;
}
public SpatialDatabaseRecord setValue(SpatialDatabaseRecord value) {
return this.record = value;
}
public int compareTo(PointResult other) {
if (this.distance == other.distance) {
return 0;
} else if (this.distance < other.distance) {
return -1;
} else {
return 1;
}
}
public String toString() {
return "Point[" + point + "] distance[" + distance + "] record["
+ record + "]";
}
}
public static ArrayList<PointResult> findClosestEdges(Point point,
Layer layer) {
return findClosestEdges(point, layer, 0.0);
}
public static ArrayList<PointResult> findClosestEdges(Point point,
Layer layer, double distance) {
ReferencedEnvelope env = new ReferencedEnvelope(layer.getIndex()
.getLayerBoundingBox(), layer.getCoordinateReferenceSystem());
if (distance <= 0.0)
distance = env.getSpan(0) / 100.0;
Envelope search = new Envelope(point.getCoordinate());
search.expandBy(distance);
GeometryFactory factory = layer.getGeometryFactory();
return findClosestEdges(point, layer, factory.toGeometry(search));
}
public static ArrayList<PointResult> findClosestEdges(Point point,
Layer layer, Geometry filter) {
ArrayList<PointResult> results = new ArrayList<PointResult>();
Search searchQuery = new SearchIntersect(filter);
layer.getIndex().executeSearch(searchQuery);
for (SpatialDatabaseRecord record : searchQuery.getResults()) {
Geometry geom = record.getGeometry();
if (geom instanceof LineString) {
LocationIndexedLine line = new LocationIndexedLine(geom);
LinearLocation here = line.project(point.getCoordinate());
Coordinate snap = line.extractPoint(here);
double distance = snap.distance(point.getCoordinate());
results.add(new PointResult(layer.getGeometryFactory()
.createPoint(snap), record, distance));
}
}
Collections.sort(results);
return results;
}
/**
* Adjust the size and position of a ReferencedEnvelope using fractions of
* the current size. For example:
*
* <pre>
* bounds = adjustBounds(bounds, 0.3, new double[] { -0.1, 0.1 });
* </pre>
*
* This will zoom in to show 30% of the height and width, and will also
* move the visible window 10% to the left and 10% up.
*
* @param bounds
* current envelope
* @param zoomFactor
* fraction of size to zoom in by
* @param offsetFactor
* fraction of size to offset visible window by
* @return adjusted envelope
*/
public static ReferencedEnvelope adjustBounds(ReferencedEnvelope bounds,
double zoomFactor, double[] offsetFactor) {
if(offsetFactor==null || offsetFactor.length < bounds.getDimension()) {
offsetFactor = new double[bounds.getDimension()];
}
ReferencedEnvelope scaled = new ReferencedEnvelope(bounds);
if (Math.abs(zoomFactor - 1.0) > 0.01) {
double[] min = scaled.getLowerCorner().getCoordinate();
double[] max = scaled.getUpperCorner().getCoordinate();
for (int i = 0; i < scaled.getDimension(); i++) {
double span = scaled.getSpan(i);
double delta = (span - span * zoomFactor) / 2.0;
double shift = span * offsetFactor[i];
System.out.println("Have offset["+i+"]: "+shift);
min[i] += shift + delta;
max[i] += shift - delta;
}
scaled = new ReferencedEnvelope(min[0], max[0], min[1], max[1],
scaled.getCoordinateReferenceSystem());
}
return scaled;
}
public static Envelope adjustBounds(Envelope bounds, double zoomFactor, double[] offset) {
if(offset==null || offset.length < 2) {
offset = new double[]{0,0};
}
Envelope scaled = new Envelope(bounds);
if (Math.abs(zoomFactor - 1.0) > 0.01) {
double[] min = new double[] { scaled.getMinX(), scaled.getMinY() };
double[] max = new double[] { scaled.getMaxX(), scaled.getMaxY() };
for (int i = 0; i < 2; i++) {
double shift = offset[i];
System.out.println("Have offset["+i+"]: "+shift);
double span = (i == 0) ? scaled.getWidth() : scaled.getHeight();
double delta = (span - span * zoomFactor) / 2.0;
min[i] += shift + delta;
max[i] += shift - delta;
}
scaled = new Envelope(min[0], max[0], min[1], max[1]);
}
return scaled;
}
} |
package org.opencds.cqf.servlet;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.hl7.fhir.dstu3.model.*;
import org.hl7.fhir.exceptions.FHIRException;
import org.opencds.cqf.cds.*;
import org.opencds.cqf.helpers.Dstu2ToStu3;
import org.opencds.cqf.providers.FHIRPlanDefinitionResourceProvider;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
@WebServlet(name = "cds-services")
public class CdsServicesServlet extends BaseServlet {
// default is DSTU2
private boolean isStu3 = false;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// validate that we are dealing with JSON
if (!request.getContentType().equals("application/json")) {
throw new ServletException(String.format("Invalid content type %s. Please use application/json.", request.getContentType()));
}
CdsHooksRequest cdsHooksRequest = new CdsHooksRequest(request.getReader());
cdsHooksRequest.setService(request.getPathInfo().replace("/", ""));
if (cdsHooksRequest.getFhirServerEndpoint() != null) {
isStu3 = isStu3(cdsHooksRequest.getFhirServerEndpoint());
}
CdsRequestProcessor processor = null;
// necessary resource providers
LibraryResourceProvider libraryResourceProvider = (LibraryResourceProvider) getProvider("Library");
FHIRPlanDefinitionResourceProvider planDefinitionResourceProvider = (FHIRPlanDefinitionResourceProvider) getProvider("PlanDefinition");
// Custom cds services - requires customized terminology/data providers
if (request.getRequestURL().toString().endsWith("cdc-opioid-guidance")) {
resolveMedicationPrescribePrefetch(cdsHooksRequest);
try {
processor = new OpioidGuidanceProcessor(cdsHooksRequest, libraryResourceProvider, planDefinitionResourceProvider, isStu3);
} catch (FHIRException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
else if (request.getRequestURL().toString().endsWith("diabetes-management")) {
try {
resolveDiabetesManagementPrefetch(cdsHooksRequest);
processor = new DiabetesManagementProcessor(cdsHooksRequest, libraryResourceProvider, planDefinitionResourceProvider, isStu3);
} catch (FHIRException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
else {
// User-defined cds services
// These are limited - no user-defined data/terminology providers
switch (cdsHooksRequest.getHook()) {
case "medication-prescribe":
resolveMedicationPrescribePrefetch(cdsHooksRequest);
try {
processor = new MedicationPrescribeProcessor(cdsHooksRequest, libraryResourceProvider, planDefinitionResourceProvider, isStu3);
} catch (FHIRException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
break;
case "order-review":
// resolveOrderReviewPrefetch(cdsHooksRequest);
// TODO - currently only works for ProcedureRequest orders
processor = new OrderReviewProcessor(cdsHooksRequest, libraryResourceProvider, planDefinitionResourceProvider, isStu3);
break;
case "patient-view":
processor = new PatientViewProcessor(cdsHooksRequest, libraryResourceProvider, planDefinitionResourceProvider, isStu3);
break;
}
}
if (processor == null) {
throw new RuntimeException("Invalid cds service");
}
response.getWriter().println(toJsonResponse(processor.process()));
}
// This is a little bit of a hacky way to determine the FHIR version - but it works =)
private boolean isStu3(String baseUrl) throws IOException {
URL url = new URL(baseUrl + "/metadata");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
StringBuilder response = new StringBuilder();
try(Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")))
{
for (int i; (i = in.read()) >= 0;) {
response.append((char) i);
}
}
return !response.toString().contains("Conformance");
}
// If the EHR did not provide the prefetch resources, fetch them
// Assuming EHR is using DSTU2 resources here...
// This is a big drag on performance.
private void resolveMedicationPrescribePrefetch(CdsHooksRequest cdsHooksRequest) {
if (cdsHooksRequest.getPrefetch().size() == 0) {
if (isStu3) {
String searchUrl = String.format("MedicationRequest?patient=%s&status=active", cdsHooksRequest.getPatientId());
Bundle postfetch = FhirContext.forDstu3()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(postfetch, "medication");
}
else {
String searchUrl = String.format("MedicationOrder?patient=%s&status=active", cdsHooksRequest.getPatientId());
ca.uhn.fhir.model.dstu2.resource.Bundle postfetch = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(postfetch, "medication");
}
}
}
private Bundle getPrefetchElement(String searchUrl, String fhirServerEndpoint) throws FHIRException {
Bundle postfetch;
if (isStu3) {
postfetch = FhirContext.forDstu3()
.newRestfulGenericClient(fhirServerEndpoint)
.search()
.byUrl(searchUrl)
.returnBundle(Bundle.class)
.execute();
}
else {
postfetch = Dstu2ToStu3.convertBundle(FhirContext.forDstu2()
.newRestfulGenericClient(fhirServerEndpoint)
.search()
.byUrl(searchUrl)
.returnBundle(org.hl7.fhir.instance.model.Bundle.class)
.execute());
}
return postfetch;
}
public void resolveDiabetesManagementPrefetch(CdsHooksRequest cdsHooksRequest) throws FHIRException {
if (cdsHooksRequest.getPrefetch().size() == 0) {
String searchUrl = String.format("Condition?patient=%s&code=250.00,E11.9,313436004,73211009", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "DiabetesConditions");
searchUrl = String.format("Observation?patient=%s&code=2160-0", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "CreatinineLabs");
searchUrl = String.format("Observation?patient=%s&code=59261-8", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "HbA1CLabs");
searchUrl = String.format("Observation?patient=%s&code=13457-7", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "LDLLabs");
searchUrl = String.format("Observation?patient=%s&code=20008", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "MicroalbCrLabs");
searchUrl = String.format("Observation?patient=%s&code=20009", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "FootExams");
searchUrl = String.format("Observation?patient=%s&code=20010", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "EyeExams");
searchUrl = String.format("MedicationStatement?patient=%s&code=999996", cdsHooksRequest.getPatientId());
cdsHooksRequest.setPrefetch(getPrefetchElement(searchUrl, cdsHooksRequest.getFhirServerEndpoint()), "ACEorARBMedications");
}
}
// This is especially inefficient as the search must be done for each Request resource (and then converted to stu3):
// MedicationOrder -> MedicationRequest, DiagnosticOrder or DeviceUseRequest -> ProcedureRequest, SupplyRequest
public void resolveOrderReviewPrefetch(CdsHooksRequest cdsHooksRequest) {
// TODO - clean this up
if (cdsHooksRequest.getPrefetch().size() == 0) {
String searchUrl = String.format("MedicationOrder?patient=%s&encounter=%s", cdsHooksRequest.getPatientId(), cdsHooksRequest.getEncounterId());
ca.uhn.fhir.model.dstu2.resource.Bundle postfetch = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(postfetch, "medication");
searchUrl = String.format("DiagnosticOrder?patient=%s&encounter=%s", cdsHooksRequest.getPatientId(), cdsHooksRequest.getEncounterId());
ca.uhn.fhir.model.dstu2.resource.Bundle diagnosticOrders = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(diagnosticOrders, "diagnosticOrders");
searchUrl = String.format("DeviceUseRequest?patient=%s&encounter=%s", cdsHooksRequest.getPatientId(), cdsHooksRequest.getEncounterId());
ca.uhn.fhir.model.dstu2.resource.Bundle deviceUseRequests = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(deviceUseRequests, "deviceUseRequests");
searchUrl = String.format("ProcedureRequest?patient=%s&encounter=%s", cdsHooksRequest.getPatientId(), cdsHooksRequest.getEncounterId());
ca.uhn.fhir.model.dstu2.resource.Bundle procedureRequests = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(procedureRequests, "procedureRequests");
searchUrl = String.format("SupplyRequest?patient=%s&encounter=%s", cdsHooksRequest.getPatientId(), cdsHooksRequest.getEncounterId());
ca.uhn.fhir.model.dstu2.resource.Bundle supplyRequests = FhirContext.forDstu2()
.newRestfulGenericClient(cdsHooksRequest.getFhirServerEndpoint())
.search()
.byUrl(searchUrl)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
cdsHooksRequest.setPrefetch(supplyRequests, "supplyRequests");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!request.getRequestURL().toString().endsWith("cds-services")) {
throw new ServletException("This servlet is not configured to handle GET requests.");
}
CdsHooksHelper.DisplayDiscovery(response);
}
private String toJsonResponse(List<CdsCard> cards) {
JsonObject ret = new JsonObject();
JsonArray cardArray = new JsonArray();
for (CdsCard card : cards) {
cardArray.add(card.toJson());
}
ret.add("cards", cardArray);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(ret);
}
} |
package org.threadly.test.concurrent;
import java.util.concurrent.locks.LockSupport;
/**
* {@link TestCondition} in unit test, designed to check a condition
* for something that is happening in a different thread. Allowing a
* test to efficiently block till the testable action has finished.
*
* @author jent - Mike Jensen
*/
public abstract class TestCondition {
private static final int NANOS_IN_MILLISECOND = 1000000;
private static final int DEFAULT_POLL_INTERVAL = 20;
private static final int DEFAULT_TIMEOUT = 1000 * 10;
private static final int SPIN_THRESHOLD = 10;
/**
* Getter for the conditions current state.
*
* @return condition state, true if ready
*/
public abstract boolean get();
/**
* Blocks till condition is true, useful for asynchronism operations,
* waiting for them to complete in other threads during unit tests.
*
* This uses a default timeout of 10 seconds, and a poll interval of 20ms
*/
public void blockTillTrue() {
blockTillTrue(DEFAULT_TIMEOUT, DEFAULT_POLL_INTERVAL);
}
/**
* Blocks till condition is true, useful for asynchronism operations,
* waiting for them to complete in other threads during unit tests.
*
* This uses the default poll interval of 20ms
*
* @param timeout time to wait for value to become true
*/
public void blockTillTrue(int timeout) {
blockTillTrue(timeout, DEFAULT_POLL_INTERVAL);
}
/**
* Blocks till condition is true, useful for asynchronism operations,
* waiting for them to complete in other threads during unit tests.
*
* @param timeout time to wait for value to become true
* @param pollInterval time to sleep between checks
*/
public void blockTillTrue(int timeout, int pollInterval) {
long startTime = System.currentTimeMillis();
boolean lastResult;
while (! (lastResult = get()) &&
System.currentTimeMillis() - startTime < timeout) {
if (pollInterval > SPIN_THRESHOLD) {
LockSupport.parkNanos(NANOS_IN_MILLISECOND * pollInterval);
}
}
if (! lastResult) {
throw new TimeoutException("Still false after " +
(System.currentTimeMillis() - startTime) + "ms");
}
}
/**
* Thrown if condition is still false after a given timeout.
*
* @author jent - Mike Jensen
*/
public static class TimeoutException extends RuntimeException {
private static final long serialVersionUID = 7445447193772617274L;
/**
* Constructor for new TimeoutException.
*/
public TimeoutException() {
super();
}
/**
* Constructor for new TimeoutException.
*
* @param msg Exception message
*/
public TimeoutException(String msg) {
super(msg);
}
}
} |
package org.webbitserver.handler;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;
import org.webbitserver.helpers.ClassloaderResourceHelper;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import static java.util.concurrent.Executors.newFixedThreadPool;
public class StaticFileHandler extends AbstractResourceHandler {
protected final File dir;
protected final long maxAge;
public StaticFileHandler(File dir, Executor ioThread, TemplateEngine templateEngine) {
super(ioThread, templateEngine);
this.dir = dir;
this.maxAge = 0;
}
public StaticFileHandler(File dir, Executor ioThread) {
this(dir, ioThread, new StaticFile());
}
public StaticFileHandler(String dir, Executor ioThread, TemplateEngine templateEngine) {
this(new File(dir), ioThread, templateEngine);
}
public StaticFileHandler(String dir, Executor ioThread) {
this(dir, ioThread, new StaticFile());
}
public StaticFileHandler(File dir, TemplateEngine templateEngine) {
this(dir, newFixedThreadPool(4), templateEngine);
}
public StaticFileHandler(File dir) {
this(dir, new StaticFile());
}
public StaticFileHandler(String dir, TemplateEngine templateEngine) {
this(new File(dir), templateEngine);
}
public StaticFileHandler(String dir) {
this(new File(dir));
}
//cache control-aware
public StaticFileHandler(File dir, Executor ioThread, TemplateEngine templateEngine, long maxAge) {
super(ioThread, templateEngine);
this.dir = dir;
this.maxAge = maxAge;
}
public StaticFileHandler(File dir, Executor ioThread, long maxAge) {
this(dir, ioThread, new StaticFile(), maxAge);
}
public StaticFileHandler(String dir, long maxAge) {
this(new File(dir), maxAge);
}
public StaticFileHandler(File dir, long maxAge) {
this(dir, newFixedThreadPool(4), new StaticFile(), maxAge);
}
@Override
protected FileWorker createIOWorker(HttpRequest request,
HttpResponse response,
HttpControl control) {
return new FileWorker(request, response, control, maxAge);
}
protected class FileWorker extends IOWorker {
private File file;
private final HttpResponse response;
private final HttpRequest request;
private final long maxAge;
private String mimeType(String uri) {
String ext = uri.lastIndexOf(".") != -1 ? uri.substring(uri.lastIndexOf(".")) : null;
String currentMimeType = mimeTypes.get(ext);
if (currentMimeType == null) currentMimeType = "text/plain";
return currentMimeType;
}
private String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
private String toHeader(Date date) {
SimpleDateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return httpDateFormat.format(date);
}
private Date fromHeader(String date) {
SimpleDateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
return httpDateFormat.parse(date);
} catch (Exception ex) {
return new Date();
}
}
protected FileWorker(HttpRequest request, HttpResponse response, HttpControl control, long maxAge) {
super(request.uri(), request, response, control);
this.maxAge = maxAge;
this.response = response;
this.request = request;
}
@Override
protected boolean exists() throws IOException {
file = resolveFile(path);
return file != null && file.exists();
}
@Override
protected boolean isDirectory() throws IOException {
return file.isDirectory();
}
@Override
protected byte[] fileBytes() throws IOException {
byte[] raw = file.isFile() ? read(file) : null;
//add cache control headers if needed
if (raw != null) {
Date lastModified = new Date(file.lastModified());
// String hashtext = MD5(Long.toString(lastModified.getTime()));
// if (hashtext != null) response.header("ETag", "\"" + hashtext + "\"");
if(path.contains(".cache."))
{
if(request.header("If-Modified-Since") != null
&& fromHeader(request.header("If-Modified-Since")).getTime() / 1000 == lastModified.getTime() / 1000)
response.status(304);
else
{
response.header("Cache-control", "public, must-revalidate, max-age=" + 31536000 /* Seconds in a year. */);
response.header("Last-Modified", toHeader(lastModified));
response.header("Expires", new Date(System.currentTimeMillis() + 31536000000L /* Millis in a year. */));
}
}
else if(
path.contains(".nocache.")
|| path.endsWith(".htm")
|| path.endsWith(".html"))
{
response.header("Cache-control", "no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0");
response.header("Last-Modified", new Date());
response.header("Expires", new Date(0));
response.header("Pragma", "no-cache");
}
else
{
response.header("Last-Modified", toHeader(lastModified));
//is there an incoming If-Modified-Since?
if(request.header("If-Modified-Since") != null
&& fromHeader(request.header("If-Modified-Since")).getTime() / 1000 == lastModified.getTime() / 1000)
response.status(304);
//is setting cache control necessary?
if (maxAge != 0) {
response.header("Expires", toHeader( new Date(new Date().getTime() + maxAge * 1000)));
response.header("Cache-Control", "max-age=" + maxAge+", public");
}
}
}
return raw;
}
@Override
protected byte[] welcomeBytes() throws IOException {
File welcome = new File(file, welcomeFileName);
return welcome.isFile() ? read(welcome) : null;
}
@Override
protected byte[] directoryListingBytes() throws IOException {
if (!isDirectory()) {
return null;
}
Iterable<FileEntry> files = ClassloaderResourceHelper.fileEntriesFor(file.listFiles());
return directoryListingFormatter.formatFileListAsHtml(files);
}
private byte[] read(File file) throws IOException {
return read((int) file.length(), new FileInputStream(file));
}
protected File resolveFile(String path) throws IOException {
// Find file, relative to root
File result = new File(dir, path).getCanonicalFile();
// For security, check file really does exist under root.
String fullPath = result.getPath();
if (!fullPath.startsWith(dir.getCanonicalPath() + File.separator) && !fullPath.equals(dir.getCanonicalPath())) {
return null;
}
return result;
}
}
} |
package org.yinwang.pysonar.visitor;
import org.jetbrains.annotations.NotNull;
import org.yinwang.pysonar.*;
import org.yinwang.pysonar.ast.*;
import org.yinwang.pysonar.types.*;
import java.util.*;
public class TypeInferencer implements Visitor1<Type, State> {
@NotNull
@Override
public Type visit(Alias node, State s) {
return Type.UNKNOWN;
}
@NotNull
@Override
public Type visit(Assert node, State s) {
if (node.test != null) {
visit(node.test, s);
}
if (node.msg != null) {
visit(node.msg, s);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Assign node, State s) {
Type valueType = visit(node.value, s);
Binder.bind(s, node.target, valueType);
return Type.CONT;
}
@NotNull
@Override
public Type visit(Attribute node, State s) {
Type targetType = visit(node.target, s);
if (targetType instanceof UnionType) {
Set<Type> types = ((UnionType) targetType).types;
Type retType = Type.UNKNOWN;
for (Type tt : types) {
retType = UnionType.union(retType, node.getAttrType(tt));
}
return retType;
} else {
return node.getAttrType(targetType);
}
}
@NotNull
@Override
public Type visit(Await node, State s) {
if (node.value == null) {
return Type.NONE;
} else {
return visit(node.value, s);
}
}
@NotNull
@Override
public Type visit(BinOp node, State s) {
Type ltype = visit(node.left, s);
Type rtype = visit(node.right, s);
if (Op.isBoolean(node.op)) {
return Type.BOOL;
} else {
return UnionType.union(ltype, rtype);
}
}
@NotNull
@Override
public Type visit(Block node, State s) {
// first pass: mark global names
for (Node n : node.seq) {
if (n instanceof Global) {
for (Name name : ((Global) n).names) {
s.addGlobalName(name.id);
Set<Binding> nb = s.lookup(name.id);
if (nb != null) {
Analyzer.self.putRef(name, nb);
}
}
}
}
boolean returned = false;
Type retType = Type.UNKNOWN;
for (Node n : node.seq) {
Type t = visit(n, s);
if (!returned) {
retType = UnionType.union(retType, t);
if (!UnionType.contains(t, Type.CONT)) {
returned = true;
retType = UnionType.remove(retType, Type.CONT);
}
}
}
return retType;
}
@NotNull
@Override
public Type visit(Break node, State s) {
return Type.NONE;
}
@NotNull
@Override
public Type visit(Bytes node, State s) {
return Type.STR;
}
@NotNull
@Override
public Type visit(Call node, State s) {
Type fun = visit(node.func, s);
List<Type> pos = visit(node.args, s);
Map<String, Type> hash = new HashMap<>();
if (node.keywords != null) {
for (Keyword kw : node.keywords) {
hash.put(kw.arg, visit(kw.value, s));
}
}
Type kw = node.kwargs == null ? null : visit(node.kwargs, s);
Type star = node.starargs == null ? null : visit(node.starargs, s);
if (fun instanceof UnionType) {
Set<Type> types = ((UnionType) fun).types;
Type retType = Type.UNKNOWN;
for (Type ft : types) {
Type t = node.resolveCall(ft, pos, hash, kw, star);
retType = UnionType.union(retType, t);
}
return retType;
} else {
return node.resolveCall(fun, pos, hash, kw, star);
}
}
@NotNull
@Override
public Type visit(ClassDef node, State s) {
ClassType classType = new ClassType(node.name.id, s);
List<Type> baseTypes = new ArrayList<>();
for (Node base : node.bases) {
Type baseType = visit(base, s);
if (baseType instanceof ClassType) {
classType.addSuper(baseType);
} else if (baseType instanceof UnionType) {
for (Type parent : ((UnionType) baseType).types) {
classType.addSuper(parent);
}
} else {
Analyzer.self.putProblem(base, base + " is not a class");
}
baseTypes.add(baseType);
}
// XXX: Not sure if we should add "bases", "name" and "dict" here. They
// must be added _somewhere_ but I'm just not sure if it should be HERE.
node.addSpecialAttribute(classType.table, "__bases__", new TupleType(baseTypes));
node.addSpecialAttribute(classType.table, "__name__", Type.STR);
node.addSpecialAttribute(classType.table, "__dict__",
new DictType(Type.STR, Type.UNKNOWN));
node.addSpecialAttribute(classType.table, "__module__", Type.STR);
node.addSpecialAttribute(classType.table, "__doc__", Type.STR);
// Bind ClassType to name here before resolving the body because the
// methods need node type as self.
Binder.bind(s, node.name, classType, Binding.Kind.CLASS);
if (node.body != null) {
visit(node.body, classType.table);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Comprehension node, State s) {
Binder.bindIter(s, node.target, node.iter, Binding.Kind.SCOPE);
visit(node.ifs, s);
return visit(node.target, s);
}
@NotNull
@Override
public Type visit(Continue node, State s) {
return Type.CONT;
}
@NotNull
@Override
public Type visit(Delete node, State s) {
for (Node n : node.targets) {
visit(n, s);
if (n instanceof Name) {
s.remove(((Name) n).id);
}
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Dict node, State s) {
Type keyType = resolveUnion(node.keys, s);
Type valType = resolveUnion(node.values, s);
return new DictType(keyType, valType);
}
@NotNull
@Override
public Type visit(DictComp node, State s) {
visit(node.generators, s);
Type keyType = visit(node.key, s);
Type valueType = visit(node.value, s);
return new DictType(keyType, valueType);
}
@NotNull
@Override
public Type visit(Dummy node, State s) {
return Type.UNKNOWN;
}
@NotNull
@Override
public Type visit(Ellipsis node, State s) {
return Type.NONE;
}
@NotNull
@Override
public Type visit(Exec node, State s) {
if (node.body != null) {
visit(node.body, s);
}
if (node.globals != null) {
visit(node.globals, s);
}
if (node.locals != null) {
visit(node.locals, s);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Expr node, State s) {
if (node.value != null) {
visit(node.value, s);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(ExtSlice node, State s) {
for (Node d : node.dims) {
visit(d, s);
}
return new ListType();
}
@NotNull
@Override
public Type visit(For node, State s) {
Binder.bindIter(s, node.target, node.iter, Binding.Kind.SCOPE);
Type ret;
if (node.body == null) {
ret = Type.UNKNOWN;
} else {
ret = visit(node.body, s);
}
if (node.orelse != null) {
ret = UnionType.union(ret, visit(node.orelse, s));
}
return ret;
}
@NotNull
@Override
public Type visit(FunctionDef node, State s) {
State env = s.getForwarding();
FunType fun = new FunType(node, env);
fun.table.setParent(s);
fun.table.setPath(s.extendPath(node.name.id));
fun.setDefaultTypes(visit(node.defaults, s));
Analyzer.self.addUncalled(fun);
Binding.Kind funkind;
if (node.isLamba) {
return fun;
} else {
if (s.stateType == State.StateType.CLASS) {
if ("__init__".equals(node.name.id)) {
funkind = Binding.Kind.CONSTRUCTOR;
} else {
funkind = Binding.Kind.METHOD;
}
} else {
funkind = Binding.Kind.FUNCTION;
}
Type outType = s.type;
if (outType instanceof ClassType) {
fun.setCls((ClassType) outType);
}
Binder.bind(s, node.name, fun, funkind);
return Type.CONT;
}
}
@NotNull
@Override
public Type visit(GeneratorExp node, State s) {
visit(node.generators, s);
return new ListType(visit(node.elt, s));
}
@NotNull
@Override
public Type visit(Global node, State s) {
return Type.CONT;
}
@NotNull
@Override
public Type visit(Handler node, State s) {
Type typeval = Type.UNKNOWN;
if (node.exceptions != null) {
typeval = resolveUnion(node.exceptions, s);
}
if (node.binder != null) {
Binder.bind(s, node.binder, typeval);
}
if (node.body != null) {
return visit(node.body, s);
} else {
return Type.UNKNOWN;
}
}
@NotNull
@Override
public Type visit(If node, State s) {
Type type1, type2;
State s1 = s.copy();
State s2 = s.copy();
// ignore condition for now
visit(node.test, s);
if (node.body != null) {
type1 = visit(node.body, s1);
} else {
type1 = Type.CONT;
}
if (node.orelse != null) {
type2 = visit(node.orelse, s2);
} else {
type2 = Type.CONT;
}
boolean cont1 = UnionType.contains(type1, Type.CONT);
boolean cont2 = UnionType.contains(type2, Type.CONT);
// decide which branch affects the downstream state
if (cont1 && cont2) {
s1.merge(s2);
s.overwrite(s1);
} else if (cont1) {
s.overwrite(s1);
} else if (cont2) {
s.overwrite(s2);
}
return UnionType.union(type1, type2);
}
@NotNull
@Override
public Type visit(IfExp node, State s) {
Type type1, type2;
visit(node.test, s);
if (node.body != null) {
type1 = visit(node.body, s);
} else {
type1 = Type.CONT;
}
if (node.orelse != null) {
type2 = visit(node.orelse, s);
} else {
type2 = Type.CONT;
}
return UnionType.union(type1, type2);
}
@NotNull
@Override
public Type visit(Import node, State s) {
for (Alias a : node.names) {
Type mod = Analyzer.self.loadModule(a.name, s);
if (mod == null) {
Analyzer.self.putProblem(node, "Cannot load module");
} else if (a.asname != null) {
s.insert(a.asname.id, a.asname, mod, Binding.Kind.VARIABLE);
}
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(ImportFrom node, State s) {
if (node.module == null) {
return Type.CONT;
}
Type mod = Analyzer.self.loadModule(node.module, s);
if (mod == null) {
Analyzer.self.putProblem(node, "Cannot load module");
} else if (node.isImportStar()) {
node.importStar(s, mod);
} else {
for (Alias a : node.names) {
Name first = a.name.get(0);
Set<Binding> bs = mod.table.lookup(first.id);
if (bs != null) {
if (a.asname != null) {
s.update(a.asname.id, bs);
Analyzer.self.putRef(a.asname, bs);
} else {
s.update(first.id, bs);
Analyzer.self.putRef(first, bs);
}
} else {
List<Name> ext = new ArrayList<>(node.module);
ext.add(first);
Type mod2 = Analyzer.self.loadModule(ext, s);
if (mod2 != null) {
if (a.asname != null) {
s.insert(a.asname.id, a.asname, mod2, Binding.Kind.VARIABLE);
} else {
s.insert(first.id, first, mod2, Binding.Kind.VARIABLE);
}
}
}
}
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Index node, State s) {
return visit(node.value, s);
}
@NotNull
@Override
public Type visit(Keyword node, State s) {
return visit(node.value, s);
}
@NotNull
@Override
public Type visit(ListComp node, State s) {
visit(node.generators, s);
return new ListType(visit(node.elt, s));
}
@NotNull
@Override
public Type visit(Module node, State s) {
ModuleType mt = new ModuleType(node.name, node.file, Analyzer.self.globaltable);
s.insert($.moduleQname(node.file), node, mt, Binding.Kind.MODULE);
if (node.body != null) {
visit(node.body, mt.table);
}
return mt;
}
@NotNull
@Override
public Type visit(Name node, State s) {
Set<Binding> b = s.lookup(node.id);
if (b != null) {
Analyzer.self.putRef(node, b);
Analyzer.self.resolved.add(node);
Analyzer.self.unresolved.remove(node);
return State.makeUnion(b);
} else if (node.id.equals("True") || node.id.equals("False")) {
return Type.BOOL;
} else {
Analyzer.self.putProblem(node, "unbound variable " + node.id);
Analyzer.self.unresolved.add(node);
Type t = Type.UNKNOWN;
t.table.setPath(s.extendPath(node.id));
return t;
}
}
@NotNull
@Override
public Type visit(Pass node, State s) {
return Type.CONT;
}
@NotNull
@Override
public Type visit(Print node, State s) {
if (node.dest != null) {
visit(node.dest, s);
}
if (node.values != null) {
visit(node.values, s);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(PyComplex node, State s) {
return Type.COMPLEX;
}
@NotNull
@Override
public Type visit(PyFloat node, State s) {
return Type.FLOAT;
}
@NotNull
@Override
public Type visit(PyInt node, State s) {
return Type.INT;
}
@NotNull
@Override
public Type visit(PyList node, State s) {
if (node.elts.size() == 0) {
return new ListType(); // list<unknown>
}
ListType listType = new ListType();
for (Node elt : node.elts) {
listType.add(visit(elt, s));
if (elt instanceof Str) {
listType.addValue(((Str) elt).value);
}
}
return listType;
}
@NotNull
@Override
public Type visit(PySet node, State s) {
if (node.elts.size() == 0) {
return new ListType();
}
ListType listType = null;
for (Node elt : node.elts) {
if (listType == null) {
listType = new ListType(visit(elt, s));
} else {
listType.add(visit(elt, s));
}
}
return listType;
}
@NotNull
@Override
public Type visit(Raise node, State s) {
if (node.exceptionType != null) {
visit(node.exceptionType, s);
}
if (node.inst != null) {
visit(node.inst, s);
}
if (node.traceback != null) {
visit(node.traceback, s);
}
return Type.CONT;
}
@NotNull
@Override
public Type visit(Repr node, State s) {
if (node.value != null) {
visit(node.value, s);
}
return Type.STR;
}
@NotNull
@Override
public Type visit(Return node, State s) {
if (node.value == null) {
return Type.NONE;
} else {
return visit(node.value, s);
}
}
@NotNull
@Override
public Type visit(SetComp node, State s) {
visit(node.generators, s);
return new ListType(visit(node.elt, s));
}
@NotNull
@Override
public Type visit(Slice node, State s) {
if (node.lower != null) {
visit(node.lower, s);
}
if (node.step != null) {
visit(node.step, s);
}
if (node.upper != null) {
visit(node.upper, s);
}
return new ListType();
}
@NotNull
@Override
public Type visit(Starred node, State s) {
return visit(node.value, s);
}
@NotNull
@Override
public Type visit(Str node, State s) {
return Type.STR;
}
@NotNull
@Override
public Type visit(Subscript node, State s) {
Type vt = visit(node.value, s);
Type st = node.slice == null ? null : visit(node.slice, s);
if (vt instanceof UnionType) {
Type retType = Type.UNKNOWN;
for (Type t : ((UnionType) vt).types) {
retType = UnionType.union(retType, node.getSubscript(t, st, s));
}
return retType;
} else {
return node.getSubscript(vt, st, s);
}
}
@NotNull
@Override
public Type visit(Try node, State s) {
Type tp1 = Type.UNKNOWN;
Type tp2 = Type.UNKNOWN;
Type tph = Type.UNKNOWN;
Type tpFinal = Type.UNKNOWN;
if (node.handlers != null) {
for (Handler h : node.handlers) {
tph = UnionType.union(tph, visit(h, s));
}
}
if (node.body != null) {
tp1 = visit(node.body, s);
}
if (node.orelse != null) {
tp2 = visit(node.orelse, s);
}
if (node.finalbody != null) {
tpFinal = visit(node.finalbody, s);
}
return new UnionType(tp1, tp2, tph, tpFinal);
}
@NotNull
@Override
public Type visit(Tuple node, State s) {
TupleType t = new TupleType();
for (Node e : node.elts) {
t.add(visit(e, s));
}
return t;
}
@NotNull
@Override
public Type visit(UnaryOp node, State s) {
return visit(node.operand, s);
}
@NotNull
@Override
public Type visit(Unsupported node, State s) {
return Type.NONE;
}
@NotNull
@Override
public Type visit(Url node, State s) {
return Type.STR;
}
@NotNull
@Override
public Type visit(While node, State s) {
visit(node.test, s);
Type t = Type.UNKNOWN;
if (node.body != null) {
t = visit(node.body, s);
}
if (node.orelse != null) {
t = UnionType.union(t, visit(node.orelse, s));
}
return t;
}
@NotNull
@Override
public Type visit(With node, State s) {
for (Withitem item : node.items) {
Type val = visit(item.context_expr, s);
if (item.optional_vars != null) {
Binder.bind(s, item.optional_vars, val);
}
}
return visit(node.body, s);
}
@NotNull
@Override
public Type visit(Withitem node, State s) {
return Type.UNKNOWN;
}
@NotNull
@Override
public Type visit(Yield node, State s) {
if (node.value != null) {
return new ListType(visit(node.value, s));
} else {
return Type.NONE;
}
}
@NotNull
@Override
public Type visit(YieldFrom node, State s) {
if (node.value != null) {
return new ListType(visit(node.value, s));
} else {
return Type.NONE;
}
}
@NotNull
private Type resolveUnion(@NotNull Collection<? extends Node> nodes, State s) {
Type result = Type.UNKNOWN;
for (Node node : nodes) {
Type nodeType = visit(node, s);
result = UnionType.union(result, nodeType);
}
return result;
}
} |
package ro.msg.learning.shop.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ro.msg.learning.shop.entities.*;
import ro.msg.learning.shop.exceptions.ProductNotFoundException;
import ro.msg.learning.shop.exceptions.QuantityExceedsStockException;
import ro.msg.learning.shop.models.OrderInput;
import ro.msg.learning.shop.repositories.*;
import ro.msg.learning.shop.services.strategies.QuantityStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author Zbiera Alexandru-Robert <Robert.Zbiera@msg.group>
*/
@Service
public class OrderCreator {
private final OrderRepository orderRepository;
private final ProductRepository productRepository;
private final CustomerRepository customerRepository;
private final EmployeeRepository employeeRepository;
private final AddressRepository addressRepository;
private final QuantityStrategy quantityStrategy;
private final LocationRepository locationRepository;
@Autowired
public OrderCreator(OrderRepository orderRepository, ProductRepository productRepository, CustomerRepository customerRepository, EmployeeRepository employeeRepository, AddressRepository addressRepository, QuantityStrategy quantityStrategy, LocationRepository locationRepository) {
this.orderRepository = orderRepository;
this.productRepository = productRepository;
this.customerRepository = customerRepository;
this.employeeRepository = employeeRepository;
this.addressRepository = addressRepository;
this.quantityStrategy = quantityStrategy;
this.locationRepository = locationRepository;
}
private void validateOrder(OrderInput orderInput) {
for (Long key : orderInput.getProductMap().keySet()) {
long tempLong = productRepository.getQuantityForProduct(key);
if (productRepository.findOne(key) == null) {
throw new ProductNotFoundException();
} else if (tempLong < orderInput.getProductMap().get(key)) {
throw new QuantityExceedsStockException(key, orderInput.getProductMap().get(key), tempLong);
}
}
}
private ArrayList<OrderDetails> getOrderDetails(List<ProductsLocations> productsLocations) {
ArrayList<OrderDetails> orderDetailsList = new ArrayList<>();
for (ProductsLocations productsLocation : productsLocations) {
orderDetailsList.add(new OrderDetails(productsLocation.getQuantity(), 0.0, productsLocation.getProduct(), productsLocation.getLocation()));
}
return orderDetailsList;
}
private Address getAddress(OrderInput orderInput) {
Address address = addressRepository.findByCountryAndCityAndStreet(orderInput.getAddress().getCountry(), orderInput.getAddress().getCity(), orderInput.getAddress().getStreet());
if (address == null) {
address = addressRepository.save(orderInput.getAddress());
}
return address;
}
private Customer getCustomer() {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
Optional<Customer> customerOptional = customerRepository.findOptionalByUserUsername(username);
if (customerOptional.isPresent()) {
return customerOptional.get();
} else {
Optional<Employee> employeeOptional = employeeRepository.findOptionalByUserUsername(username);
if (employeeOptional.isPresent()) {
Customer customer = new Customer();
customer.setLastName(employeeOptional.get().getLastName());
customer.setFirstName(employeeOptional.get().getFirstName());
customer.setUser(employeeOptional.get().getUser());
customer.setAddress(employeeOptional.get().getAddress());
customer = customerRepository.save(customer);
return customer;
} else {
throw new UsernameNotFoundException("could not find the user '" + username + "'");
}
}
}
@Transactional
@PreAuthorize("hasAnyAuthority('CUSTOMER','ADMIN')")
public Order createOrder(OrderInput orderInput) {
validateOrder(orderInput);
List<ProductsLocations> locations = quantityStrategy.
getLocations(orderInput.getProductMap(), productRepository.
findAllProductsLocationsInSet(orderInput.getProductMap().keySet()));
List<Location> tempLocations = locationRepository.findAllByIdIn(locations.stream().map(ProductsLocations::getLocationId).collect(Collectors.toSet()));
locations.forEach(x -> x.setLocation(
tempLocations.stream()
.filter(y -> x.getLocationId().equals(y.getId()))
.findFirst()
.orElse(null)));
List<Product> tempProducts = productRepository.findAllByIdIn(locations.stream().map(ProductsLocations::getProductId).collect(Collectors.toSet()));
locations.forEach(x -> x.setProduct(tempProducts.stream().filter(y -> x.getProductId().equals(y.getId())).findFirst().orElse(null)));
locations.forEach(x -> productRepository.changeTheQuantity(x.getLocationId(), x.getProductId(), x.getQuantity()));
Order order = new Order();
for (OrderDetails orderDetail : getOrderDetails(locations)) {
order.addOrderDetail(orderDetail);
}
order.setOrderDate(orderInput.getDate());
order.setAddress(getAddress(orderInput));
order.setCustomer(getCustomer());
order.setEmployee(employeeRepository.getOne(orderRepository.employeeIdWithLeastOrders()));
return orderRepository.save(order);
}
} |
package seedu.taskmanager.commons.util;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import seedu.taskmanager.commons.exceptions.IllegalValueException;
public class CurrentDate {
public static final String MESSAGE_DAY_CONSTRAINTS = "Task date should be either a day (e.g. thursday) or a date with the format: DD/MM/YY (e.g. 03/03/17)";
public static final String CURRENTDATE_VALIDATION_REGEX_TODAY1 = "Today";
public static final String CURRENTDATE_VALIDATION_REGEX_TODAY2 = "today";
public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW1 = "Tomorrow";
public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW2 = "tomorrow";
public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW3 = "Tom";
public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW4 = "tom";
public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY1 = "Monday";
public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY2 = "monday";
public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY3 = "Mon";
public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY4 = "mon";
public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY1 = "Tuesday";
public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY2 = "tuesday";
public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY3 = "Tues";
public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY4 = "tues";
public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1 = "Wednesday";
public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2 = "wednesday";
public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3 = "Wed";
public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4 = "wed";
public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY1 = "Thursday";
public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY2 = "thursday";
public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY3 = "Thurs";
public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY4 = "thurs";
public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY1 = "Friday";
public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY2 = "friday";
public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY3 = "Fri";
public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY4 = "fri";
public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY1 = "Saturday";
public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY2 = "saturday";
public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY3 = "Sat";
public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY4 = "sat";
public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY1 = "Sunday";
public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY2 = "sunday";
public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY3 = "Sun";
public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY4 = "sun";
public static int currentDay;
public static String currentDate = "";
public CurrentDate() {
currentDay = getCurrentDay();
currentDate = getCurrentDate();
}
/**
* Checks to see if user has input a valid day, this function includes
* different spellings of the same day
*/
public static boolean isValidDay(String test) {
return test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY4)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TODAY1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TODAY2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW1)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW2)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW3)
|| test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW4);
}
/**
* @return Day number relative to the day itself (e.g. Sunday == 1 &
* Wednesday == 4)
*/
public static int getNewDay(String day) {
int newDay = 0;
if (day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY4)) {
return newDay = 1;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY4)) {
return newDay = 2;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY4)) {
return newDay = 3;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4)) {
return newDay = 4;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY4)) {
return newDay = 5;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY4)) {
return newDay = 6;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY2)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY3)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY4)) {
return newDay = 7;
} else {
if (day.matches(CURRENTDATE_VALIDATION_REGEX_TODAY1)
|| day.matches(CURRENTDATE_VALIDATION_REGEX_TODAY2)) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return dayOfWeek;
} else {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek + 1 == 8) {
return dayOfWeek = 1;
} else {
return dayOfWeek + 1;
}
}
}
}
}
}
}
}
}
}
/**
* @return Current Day with respect to the date on the computer
*/
public static int getCurrentDay() {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
int day = calendar.get(Calendar.DATE);
return day;
}
/**
* @return Current Date with respect to the date on the computer
*/
public static String getCurrentDate() {
String newdate = "";
String stringDay = "";
String stringMonth = "";
String stringYear = "";
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
// getTime() returns the current date in default time zone
int day = calendar.get(Calendar.DATE);
// Note: +1 the month for current month
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
if (day < 10) {
stringDay = "0" + Integer.toString(day);
} else
stringDay = Integer.toString(day);
if (month < 10) {
stringMonth = "0" + Integer.toString(month);
} else
stringMonth = Integer.toString(month);
stringYear = Integer.toString(year).substring(Math.max(Integer.toString(year).length() - 2, 0));
newdate = stringDay + "/" + stringMonth + "/" + stringYear;
return newdate;
}
public static String getNewDate(String givenDay) throws IllegalValueException {
if (!isValidDay(givenDay)) {
throw new IllegalValueException(MESSAGE_DAY_CONSTRAINTS);
}
int inputDay = getNewDay(givenDay);
String updatedDate = "";
String stringDay = "";
String stringMonth = "";
String stringYear = "";
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
// getTime() returns the current date in default time zone
Date date = calendar.getTime();
int day = calendar.get(Calendar.DATE);
// Note: +1 the month for current month
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
int diffInDays = dayOfWeek - inputDay;
if (diffInDays == 0)
return getCurrentDate();
if (diffInDays > 0)
day += (7 - diffInDays);
if (diffInDays < 0)
day -= diffInDays;
LocalDate testdate = LocalDate.of(year, month, day);
int testdays = testdate.lengthOfMonth();
if (day > testdays) {
month += 1;
day -= testdays;
}
if (month > 12) {
month = 1;
year += 1;
}
if (day < 10) {
stringDay = "0" + Integer.toString(day);
} else
stringDay = Integer.toString(day);
if (month < 10) {
stringMonth = "0" + Integer.toString(month);
} else
stringMonth = Integer.toString(month);
stringYear = Integer.toString(year).substring(Math.max(Integer.toString(year).length() - 2, 0));
return updatedDate = stringDay + "/" + stringMonth + "/" + stringYear;
}
} |
package seedu.unburden.logic.commands;
import seedu.unburden.model.ListOfTask;
/**
* Clears the address book.
*/
public class ClearCommand extends Command {
public static final String COMMAND_WORD = "clear";
public static final String MESSAGE_SUCCESS = "Unburden has been cleared!";
public ClearCommand() {}
@Override
public CommandResult execute() {
assert model != null;
model.resetData(ListOfTask.getEmptyAddressBook());
return new CommandResult(MESSAGE_SUCCESS);
}
} |
package uk.co.samicemalone.libtv.matcher;
import java.nio.file.Path;
import java.util.regex.Pattern;
import uk.co.samicemalone.libtv.exception.MatchElementNotFoundException;
import uk.co.samicemalone.libtv.exception.MatchException;
import uk.co.samicemalone.libtv.exception.MatchNotFoundException;
import uk.co.samicemalone.libtv.matcher.tv.NoDelimiterMatcher;
import uk.co.samicemalone.libtv.matcher.tv.PartMatcher;
import uk.co.samicemalone.libtv.matcher.tv.SEDelimitedMatcher;
import uk.co.samicemalone.libtv.matcher.tv.WordDelimitedMatcher;
import uk.co.samicemalone.libtv.matcher.tv.XDelimitedMatcher;
import uk.co.samicemalone.libtv.model.EpisodeMatch;
import uk.co.samicemalone.libtv.model.TVMatcherOptions;
/**
* TVMatcher matches an episode file path to an EpisodeMatch with the ability
* to specify which TV show elements are required.
* By default, episode matching is deferred to the implementations of {@link Matcher} in
* {@link uk.co.samicemalone.libtv.matcher.tv}.
* Matching can be deferred to a {@link TVMatcherOptions} instance
* @author Sam Malone
*/
public class TVMatcher {
/**
* Matcher used to match an episode file path to an EpisodeMatch according
* the TVMatcherOptions.
*/
public static interface Matcher {
/**
* Get TV matcher options
* @see TVMatcherOptions
* @return TV matcher options
*/
public TVMatcherOptions getOptions();
/**
* Match a file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* @param path absolute episode path
* @param filteredFileName filtered file name. see {@link #stripCommonTags(java.lang.String)}
* @return EpisodeMatch if found, otherwise null
*/
public EpisodeMatch match(Path path, String filteredFileName);
}
/**
* MatchElement represents data to be matched: SHOW, SEASON or ALL
*/
public static enum MatchElement {
SHOW, SEASON, ALL
}
private final TVMatcherOptions options;
/**
* Strip common tags from an episode filename that may interfere with
* matching. Tags removed:
* Qualities: e.g. 720p, 1080i, 480p
* Codecs: e.g. ac3, dd5.1, aac2.0, dd 7.1, h.264, x264
* @param fileName fileName to strip of tags
* @return stripped filename
*/
public static String stripCommonTags(String fileName) {
String regex = "(?:720|480|1080)[ip]|([hx][_\\-. +]*264)|dd[_\\-. +]?[257][_\\-. +]*[01]|ac3|aac[_\\-. +]*(?:[257][_\\-. +]*[01])*";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
return p.matcher(fileName).replaceAll("");
}
/**
* Create a new instance of TVMatcher with the default matcher options to
* match the tv show, season and episode(s) from the file name.
*/
public TVMatcher() {
options = new TVMatcherOptions();
}
/**
* Create a new instance of TVMatcher using the specified TVMatcherOptions
* @param options TV matcher options
*/
public TVMatcher(TVMatcherOptions options) {
this.options = options;
}
/**
* Match a file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* @param path path to match
* @return EpisodeMatch if found, otherwise null.
*/
public EpisodeMatch match(Path path) {
return match(path,
new SEDelimitedMatcher(options),
new XDelimitedMatcher(options),
new WordDelimitedMatcher(options),
new NoDelimiterMatcher(options),
new PartMatcher(options)
);
}
/**
* Match a file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* Throws a MatchNotFoundException if an episode match was not found
* @param path path to match
* @return EpisodeMatch
* @throws uk.co.samicemalone.libtv.exception.MatchNotFoundException
* if an episode match was not found
*/
public EpisodeMatch matchOrThrow(Path path) throws MatchNotFoundException {
EpisodeMatch e = match(path);
if(e == null) {
throw new MatchNotFoundException("Match not found: " + path);
}
return e;
}
/**
* Match a file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* Throws a MatchElementNotFoundException if an episode match was found
* but the required match component wasn't e.g. no season.
* @param path path to match
* @param requiredMatch require the match to have the given MatchElement
* @return EpisodeMatch
* @throws uk.co.samicemalone.libtv.exception.MatchElementNotFoundException
* if an episode match was found but the required match component was not.
* @throws uk.co.samicemalone.libtv.exception.MatchNotFoundException
* if an episode match was not found
*/
public EpisodeMatch matchOrThrow(Path path, MatchElement requiredMatch) throws MatchException {
EpisodeMatch e = matchElementOrThrow(path, requiredMatch);
if(e == null) {
throw new MatchNotFoundException("Match not found: " + path);
}
return e;
}
/**
* Match file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* If an episode match was found but the required match component wasn't,
* e.g. no season, then null will be returned
* @param path path to match
* @param requiredMatch require the match to have the given MatchElement
* @return EpisodeMatch if found and has the required elements, otherwise null.
*/
public EpisodeMatch matchElement(Path path, MatchElement requiredMatch) {
EpisodeMatch e = match(path);
if(e == null) {
return null;
}
if(e.getShow() == null && (requiredMatch == MatchElement.SHOW || requiredMatch == MatchElement.ALL)) {
return null;
}
if(e.getSeason() == EpisodeMatch.NO_SEASON && (requiredMatch == MatchElement.SHOW || requiredMatch == MatchElement.ALL)) {
return null;
}
return e;
}
/**
* Match file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* Throws a MatchElementNotFoundException if an episode match was found
* but the required match component wasn't e.g. no season.
* @param path path to match
* @param requiredMatch require the match to have the given MatchElement
* @return EpisodeMatch if found, otherwise null.
* @throws uk.co.samicemalone.libtv.exception.MatchElementNotFoundException
* if an episode match was found but the required match component was not.
*/
public EpisodeMatch matchElementOrThrow(Path path, MatchElement requiredMatch) throws MatchElementNotFoundException {
EpisodeMatch e = match(path);
if(e == null) {
return null;
}
switch(requiredMatch) {
case SHOW:
assertHasShow(e, path);
break;
case SEASON:
assertHasSeason(e, path);
break;
case ALL:
assertHasShow(e, path);
assertHasSeason(e, path);
}
return e;
}
private void assertHasShow(EpisodeMatch m, Path path) throws MatchElementNotFoundException {
if(m.getShow() == null) {
throw new MatchElementNotFoundException("Show not found: " + path);
}
}
private void assertHasSeason(EpisodeMatch m, Path path) throws MatchElementNotFoundException {
if(m.getSeason() == EpisodeMatch.NO_SEASON) {
throw new MatchElementNotFoundException("Season not found: " + path);
}
}
/**
* Match a file path to an episode to determine the episode number(s).
* The show and season will be matched if found.
* Each Matcher is checked in array order and returns as soon as a match is found
* @param path path to match
* @param matchers Matchers to check in the order given
* @return EpisodeMatch if found, otherwise null.
*/
private EpisodeMatch match(Path path, Matcher... matchers) {
String filteredName = stripCommonTags(path.getFileName().toString());
for(Matcher matcher : matchers) {
EpisodeMatch m = matcher.match(path, filteredName);
if(m != null) {
m.setEpisodeFile(path.toFile());
return m;
}
}
return null;
}
} |
package wasdev.sample.servlet;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
public class GeneralRequestFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletResponse resp = (HttpServletResponse) response;
if (request.isSecure()) {
resp.setHeader("Strict-Transport-Security", "max-age=31622400; includeSubDomains; preload");
resp.setHeader("X-Frame-Options", "SAMEORIGIN");
resp.setHeader("X-XSS-Protection", "1; mode=block");
resp.setHeader("X-Content-Type-Options", "nosniff");
resp.setHeader("Content-Security-Policy", " default-src https:; style-src 'unsafe-inline' 'self'; img-src 'self' http://lorempizza.com/100/500");
resp.setHeader("Referrer-Policy", "no-referrer");
}
chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void destroy() { }
}
class AddParamsToHeader extends HttpServletRequestWrapper {
public AddParamsToHeader(HttpServletRequest request) { super(request); }
public String getHeader(String name) {
String header = super.getHeader(name);
return header != null ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
}
public Enumeration<String> getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
return Collections.enumeration(names);
}
} |
package xyz.jacobclark.controllers;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.jacobclark.Board;
import xyz.jacobclark.exceptions.PositionOccupiedException;
import xyz.jacobclark.exceptions.PositionOutOfBoundsException;
import xyz.jacobclark.models.Move;
import xyz.jacobclark.models.Piece;
import xyz.jacobclark.rules.impl.GomokuRules;
import java.util.List;
@RestController
public class BoardController {
Board board = new Board(new GomokuRules());
@MessageMapping("/board")
public List<Piece> placePiece(Move move) throws PositionOutOfBoundsException, PositionOccupiedException {
board.placePiece(move.getPlayer(), move.getColumn(), move.getRow());
return board.getPieces();
}
@CrossOrigin(origins = "*")
@GetMapping("/board")
public List<Piece> getPieces() {
return board.getPieces();
}
} |
package org.voltcore.messaging;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.Connection;
import org.voltcore.network.QueueMonitor;
import org.voltcore.network.VoltProtocolHandler;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.DeferredSerialization;
import org.voltcore.utils.EstTime;
import org.voltdb.VoltDB;
public class ForeignHost {
private static final VoltLogger hostLog = new VoltLogger("HOST");
private Connection m_connection;
final FHInputHandler m_handler;
private final HostMessenger m_hostMessenger;
private final Integer m_hostId;
final InetSocketAddress m_listeningAddress;
private boolean m_closing;
boolean m_isUp;
// hold onto the socket so we can kill it
private final Socket m_socket;
private final SocketChannel m_sc;
// Set the default here for TestMessaging, which currently has no VoltDB instance
private long m_deadHostTimeout;
private final AtomicLong m_lastMessageMillis = new AtomicLong(Long.MAX_VALUE);
/** ForeignHost's implementation of InputHandler */
public class FHInputHandler extends VoltProtocolHandler {
@Override
public int getMaxRead() {
return Integer.MAX_VALUE;
}
@Override
public void handleMessage(ByteBuffer message, Connection c) throws IOException {
handleRead(message, c);
}
@Override
public void stopping(Connection c)
{
m_isUp = false;
if (!m_closing)
{
VoltDB.dropStackTrace("Received remote hangup from foreign host " + hostname());
hostLog.warn("Received remote hangup from foreign host " + hostname());
m_hostMessenger.reportForeignHostFailed(m_hostId);
}
}
@Override
public Runnable offBackPressure() {
return new Runnable() {
@Override
public void run() {}
};
}
@Override
public Runnable onBackPressure() {
return new Runnable() {
@Override
public void run() {}
};
}
@Override
public QueueMonitor writestreamMonitor() {
return null;
}
}
/** Create a ForeignHost and install in VoltNetwork */
ForeignHost(HostMessenger host, int hostId, SocketChannel socket, int deadHostTimeout,
InetSocketAddress listeningAddress)
throws IOException
{
m_hostMessenger = host;
m_handler = new FHInputHandler();
m_hostId = hostId;
m_closing = false;
m_isUp = true;
m_sc = socket;
m_socket = socket.socket();
m_deadHostTimeout = deadHostTimeout;
m_listeningAddress = listeningAddress;
}
public void register(HostMessenger host) throws IOException {
m_connection = host.getNetwork().registerChannel( m_sc, m_handler, 0);
}
public void enableRead() {
m_connection.enableReadSelection();
}
synchronized void close()
{
m_isUp = false;
if (m_closing) return;
m_closing = true;
if (m_connection != null)
m_connection.unregister();
}
/**
* Used only for test code to kill this FH
*/
void killSocket() {
try {
m_closing = true;
m_socket.setKeepAlive(false);
m_socket.setSoLinger(false, 0);
Thread.sleep(25);
m_socket.close();
Thread.sleep(25);
System.gc();
Thread.sleep(25);
}
catch (Exception e) {
// don't REALLY care if this fails
e.printStackTrace();
}
}
/*
* Huh!? The constructor registers the ForeignHost with VoltNetwork so finalizer
* will never get called unless the ForeignHost is unregistered with the VN.
*/
@Override
protected void finalize() throws Throwable
{
if (m_closing) return;
close();
super.finalize();
}
boolean isUp()
{
return m_isUp;
}
/** Send a message to the network. This public method is re-entrant. */
void send(
final long destinations[],
final VoltMessage message)
{
if (destinations.length == 0) {
return;
}
int len = 4 /* length prefix */
+ 8 /* source hsid */
+ 4 /* destinationCount */
+ 8 * destinations.length /* destination list */
+ message.getSerializedSize();
final ByteBuffer buf = ByteBuffer.allocate(len);
buf.putInt(len - 4);
buf.putLong(message.m_sourceHSId);
buf.putInt(destinations.length);
for (int ii = 0; ii < destinations.length; ii++) {
buf.putLong(destinations[ii]);
}
try {
message.flattenToBuffer(buf);
}
catch (IOException e) {
throw new IllegalStateException(e);
}
buf.flip();
m_connection.writeStream().enqueue(
new DeferredSerialization() {
@Override
public final ByteBuffer[] serialize() throws IOException{
return new ByteBuffer[] { buf };
}
@Override
public final void cancel() {
/*
* Can this be removed?
*/
}
});
long current_time = EstTime.currentTimeMillis();
long current_delta = current_time - m_lastMessageMillis.get();
// NodeFailureFault no longer immediately trips FHInputHandler to
// set m_isUp to false, so use both that and m_closing to
// avoid repeat reports of a single node failure
if ((!m_closing && m_isUp) &&
(current_delta > m_deadHostTimeout))
{
hostLog.error("DEAD HOST DETECTED, hostname: " + hostname());
hostLog.info("\tcurrent time: " + current_time);
hostLog.info("\tlast message: " + m_lastMessageMillis);
hostLog.info("\tdelta (millis): " + current_delta);
hostLog.info("\ttimeout value (millis): " + m_deadHostTimeout);
VoltDB.dropStackTrace("Timed out foreign host " + hostname() + " with delta " + current_delta);
m_hostMessenger.reportForeignHostFailed(m_hostId);
}
}
String hostname() {
return m_connection.getHostnameOrIP();
}
/** Deliver a deserialized message from the network to a local mailbox */
private void deliverMessage(long destinationHSId, VoltMessage message) {
if (!m_hostMessenger.validateForeignHostId(m_hostId)) {
hostLog.warn(String.format("Message (%s) sent to site id: %s @ (%s) at " +
m_hostMessenger.getHostId() + " from " + CoreUtils.hsIdToString(message.m_sourceHSId) +
" which is a known failed host. The message will be dropped\n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId), m_socket.getRemoteSocketAddress().toString()));
return;
}
Mailbox mailbox = m_hostMessenger.getMailbox(destinationHSId);
/*
* At this point we are OK with messages going to sites that don't exist
* because we are saying that things can come and go
*/
if (mailbox == null) {
hostLog.info(String.format("Message (%s) sent to unknown site id: %s @ (%s) at " +
m_hostMessenger.getHostId() + " from " + CoreUtils.hsIdToString(message.m_sourceHSId) + "\n",
message.getClass().getSimpleName(),
CoreUtils.hsIdToString(destinationHSId), m_socket.getRemoteSocketAddress().toString()));
/*
* If it is for the wrong host, that definitely isn't cool
*/
if (m_hostMessenger.getHostId() != (int)destinationHSId) {
VoltDB.crashLocalVoltDB("Received a message at wrong host", false, null);
}
return;
}
// deliver the message to the mailbox
mailbox.deliver(message);
}
/** Read data from the network. Runs in the context of Port when
* data is available.
* @throws IOException
*/
private void handleRead(ByteBuffer in, Connection c) throws IOException {
// port is locked by VoltNetwork when in valid use.
// assert(m_port.m_lock.tryLock() == true);
long recvDests[] = null;
final long sourceHSId = in.getLong();
final int destCount = in.getInt();
if (destCount == -1) {//This is a poison pill
byte messageBytes[] = new byte[in.getInt()];
in.get(messageBytes);
String message = new String(messageBytes, "UTF-8");
message = String.format("Fatal error from id,hostname(%d,%s): %s",
m_hostId, hostname(), message);
org.voltdb.VoltDB.crashLocalVoltDB(message, false, null);
}
recvDests = new long[destCount];
for (int i = 0; i < destCount; i++) {
recvDests[i] = in.getLong();
}
final VoltMessage message =
m_hostMessenger.getMessageFactory().createMessageFromBuffer(in, sourceHSId);
for (int i = 0; i < destCount; i++) {
deliverMessage( recvDests[i], message);
}
//m_lastMessageMillis = System.currentTimeMillis();
m_lastMessageMillis.lazySet(EstTime.currentTimeMillis());
// ENG-1608. We sniff for FailureSiteUpdateMessages here so
// that a node will participate in the failure resolution protocol
// even if it hasn't directly witnessed a node fault.
if (message instanceof FailureSiteUpdateMessage)
{
for (long failedHostId : ((FailureSiteUpdateMessage)message).m_failedHSIds) {
m_hostMessenger.reportForeignHostFailed((int)failedHostId);
}
}
}
public void sendPoisonPill(String err) {
byte errBytes[];
try {
errBytes = err.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
ByteBuffer message = ByteBuffer.allocate( 20 + errBytes.length);
message.putInt(message.capacity() - 4);
message.putLong(-1);
message.putInt(-1);
message.putInt(errBytes.length);
message.put(errBytes);
message.flip();
m_connection.writeStream().enqueue(message);
}
public void updateDeadHostTimeout(int timeout) {
m_deadHostTimeout = timeout;
}
} |
package org.voltcore.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class LatencyWatchdog {
static volatile Map<Thread, Long> m_latencyMap = new HashMap<Thread, Long>();
static final long WATCHDOG_DELAY = 50;
static final long MIN_LOG_INTERVAL = 5 * 1000; /* millisecond */
static public final boolean m_enable = true; /* Compiler will eliminate the code within its scope when turn off */
static ScheduledThreadPoolExecutor executor = CoreUtils.getScheduledThreadPoolExecutor("Latency Watchdog Executor", 10, CoreUtils.SMALL_STACK_SIZE);
static volatile long m_lastLogTime = 0;
static class WatchdogCallback implements Runnable {
final Thread m_thread;
WatchdogCallback(Thread t) {
m_thread = t;
}
@Override
public void run() {
Thread.currentThread().setName("Latency Watchdog - " + m_thread.getName());
long timestamp = m_latencyMap.get(m_thread);
long now = System.currentTimeMillis();
if ((now - timestamp > WATCHDOG_DELAY) && (now - m_lastLogTime > MIN_LOG_INTERVAL)) {
System.out.printf("Thread [%s] has been delayed for %d milliseconds\n", m_thread.getName(), now - timestamp);
m_lastLogTime = now;
for (StackTraceElement ste : m_thread.getStackTrace()) {
System.out.println(ste);
}
}
//executor.scheduleWithFixedDelay(new WatchdogCallback(m_thread), WATCHDOG_DELAY, WATCHDOG_DELAY, TimeUnit.MILLISECONDS);
}
}
public static void pet(Thread t) {
if (!m_enable)
return;
if (m_latencyMap.containsKey(t)) {
// feed it
m_latencyMap.put(t, System.currentTimeMillis());
} else {
// create a watchdog then feed it
m_latencyMap.put(t, System.currentTimeMillis());
executor.scheduleWithFixedDelay(new WatchdogCallback(t), WATCHDOG_DELAY, WATCHDOG_DELAY, TimeUnit.MILLISECONDS);
}
}
} |
package gov.nih.nci.cananolab.dto.common;
import gov.nih.nci.cananolab.domain.common.Report;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
/**
* Report view bean
*
* @author pansu
*
*/
public class ReportBean extends LabFileBean {
private String[] particleNames;
public ReportBean() {
super();
domainFile = new Report();
domainFile.setUriExternal(false);
}
public ReportBean(Report report) {
super(report);
this.domainFile = report;
particleNames = new String[report.getNanoparticleSampleCollection()
.size()];
int i = 0;
for (NanoparticleSample particle : report
.getNanoparticleSampleCollection()) {
particleNames[i] = particle.getName();
i++;
}
}
public ReportBean(Report report, boolean loadSamples) {
super(report);
this.domainFile = report;
if (loadSamples) {
particleNames = new String[report.getNanoparticleSampleCollection()
.size()];
int i = 0;
for (NanoparticleSample particle : report
.getNanoparticleSampleCollection()) {
particleNames[i] = particle.getName();
i++;
}
}
}
public boolean equals(Object obj) {
boolean eq = false;
if (obj instanceof ReportBean) {
ReportBean c = (ReportBean) obj;
Long thisId = domainFile.getId();
if (thisId != null && thisId.equals(c.getDomainFile().getId())) {
eq = true;
}
}
return eq;
}
public String[] getParticleNames() {
return particleNames;
}
public void setParticleNames(String[] particleNames) {
this.particleNames = particleNames;
}
} |
/* FRC 4183 - The Bit Buckets
* Tucson, AZ
*
* FRC 2015 Codebase
*/
package org.bitbuckets.frc2015.control;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.SpeedController;
/**
* This class is a {@link org.bitbuckets.frc2015.util.MotionController} that is designed for Encoder control of a motor.
*/
public class EncoderMotionController {
private PIDController pidController;
/**
* Sets up the controller with the required inputs.
*
* @param encoder The encoder to be read from.
* @param motor The motor to output to.
* @param inputs The kp, ki, and kd for the PID controller. Needs 3 inputs.
*/
public EncoderMotionController(Encoder encoder, SpeedController motor, double... inputs) {
try {
pidController = new PIDController(inputs[0], inputs[1], inputs[2], encoder, motor);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
pidController = new PIDController(.5, .1, .2, encoder, motor);
}
}
/**
* Changes the setpoint of the PID controller.
*
* @param newSet The new setpoint.
*/
public void changeSetpoint(double newSet) {
pidController.setSetpoint(newSet);
}
/**
* Set whether the PID controller should be enabled.
*
* @param enabled If the PID controller should be enabled.
*/
public void setEnabled(boolean enabled) {
if (enabled) {
pidController.enable();
} else {
pidController.disable();
}
}
} |
package de.gurkenlabs.utiliti;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.GameData;
import de.gurkenlabs.litiengine.Resources;
import de.gurkenlabs.litiengine.SpriteSheetInfo;
import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer;
import de.gurkenlabs.litiengine.environment.tilemap.IMap;
import de.gurkenlabs.litiengine.environment.tilemap.ITileset;
import de.gurkenlabs.litiengine.environment.tilemap.MapOrientation;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Map;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset;
import de.gurkenlabs.litiengine.graphics.ImageCache;
import de.gurkenlabs.litiengine.graphics.ImageFormat;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.graphics.TextRenderer;
import de.gurkenlabs.litiengine.graphics.emitters.xml.CustomEmitter;
import de.gurkenlabs.litiengine.graphics.emitters.xml.EmitterData;
import de.gurkenlabs.litiengine.gui.screens.Screen;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.util.MathUtilities;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
import de.gurkenlabs.litiengine.util.io.ImageSerializer;
import de.gurkenlabs.litiengine.util.io.XmlUtilities;
import de.gurkenlabs.utiliti.components.EditorComponent;
import de.gurkenlabs.utiliti.components.EditorComponent.ComponentType;
import de.gurkenlabs.utiliti.components.MapComponent;
import de.gurkenlabs.utiliti.swing.EditorFileChooser;
import de.gurkenlabs.utiliti.swing.XmlImportDialog;
import de.gurkenlabs.utiliti.swing.dialogs.SpritesheetImportPanel;
import de.gurkenlabs.utiliti.swing.panels.MapObjectPanel;
public class EditorScreen extends Screen {
private static final Logger log = Logger.getLogger(EditorScreen.class.getName());
private static final int STATUS_DURATION = 5000;
private static final String DEFAULT_GAME_NAME = "game";
private static final String NEW_GAME_STRING = "NEW GAME *";
private static final String GAME_FILE_NAME = "Game Resource File";
private static final String SPRITE_FILE_NAME = "Sprite Info File";
private static final String SPRITESHEET_FILE_NAME = "Spritesheet Image";
public static final Color COLLISION_COLOR = new Color(255, 0, 0, 125);
public static final Color BOUNDINGBOX_COLOR = new Color(0, 0, 255, 125);
public static final Color COMPONENTBACKGROUND_COLOR = new Color(100, 100, 100, 125);
private static EditorScreen instance;
private final List<EditorComponent> comps;
private double padding;
private MapComponent mapComponent;
private GameData gameFile = new GameData();
private EditorComponent current;
private String projectPath;
private String currentResourceFile;
private MapObjectPanel mapEditorPanel;
private MapSelectionPanel mapSelectionPanel;
private long statusTick;
private String currentStatus;
private boolean loading;
private EditorScreen() {
super("Editor");
this.comps = new ArrayList<>();
}
public static EditorScreen instance() {
if (instance != null) {
return instance;
}
instance = new EditorScreen();
return instance;
}
public boolean fileLoaded() {
return this.currentResourceFile != null;
}
@Override
public void prepare() {
padding = this.getWidth() / 50;
// init components
this.mapComponent = new MapComponent(this);
this.comps.add(this.mapComponent);
super.prepare();
}
@Override
public void render(final Graphics2D g) {
Game.getCamera().updateFocus();
if (Game.getEnvironment() != null) {
Game.getEnvironment().render(g);
}
if (ImageCache.IMAGES.size() > 200) {
ImageCache.IMAGES.clear();
log.log(Level.INFO, "cache cleared!");
}
if (this.currentResourceFile != null) {
Game.getScreenManager().setTitle(Game.getInfo().getName() + " " + Game.getInfo().getVersion() + " - " + this.currentResourceFile);
String mapName = Game.getEnvironment() != null && Game.getEnvironment().getMap() != null ? "\nMap: " + Game.getEnvironment().getMap().getName() : "";
Program.getTrayIcon().setToolTip(Game.getInfo().getName() + " " + Game.getInfo().getVersion() + "\n" + this.currentResourceFile + mapName);
} else if (this.getProjectPath() != null) {
Game.getScreenManager().setTitle(Game.getInfo().getTitle() + " - " + NEW_GAME_STRING);
Program.getTrayIcon().setToolTip(Game.getInfo().getTitle() + "\n" + NEW_GAME_STRING);
} else {
Game.getScreenManager().setTitle(Game.getInfo().getTitle());
}
super.render(g);
// render mouse/zoom and fps
g.setFont(g.getFont().deriveFont(11f));
g.setColor(Color.WHITE);
Point tile = Input.mouse().getTile();
TextRenderer.render(g, "x: " + (int) Input.mouse().getMapLocation().getX() + " y: " + (int) Input.mouse().getMapLocation().getY() + " tile: [" + tile.x + ", " + tile.y + "]" + " zoom: " + (int) (Game.getCamera().getRenderScale() * 100) + " %", 10,
Game.getScreenManager().getResolution().getHeight() - 40);
TextRenderer.render(g, Game.getMetrics().getFramesPerSecond() + " FPS", 10, Game.getScreenManager().getResolution().getHeight() - 20);
// render status
if (this.currentStatus != null && !this.currentStatus.isEmpty()) {
long deltaTime = Game.getLoop().getDeltaTime(this.statusTick);
if (deltaTime > STATUS_DURATION) {
this.currentStatus = null;
}
// fade out status color
final double fadeOutTime = 0.75 * STATUS_DURATION;
if (deltaTime > fadeOutTime) {
double fade = deltaTime - fadeOutTime;
int alpha = (int) (255 - (fade / (STATUS_DURATION - fadeOutTime)) * 255);
g.setColor(new Color(255, 255, 255, MathUtilities.clamp(alpha, 0, 255)));
}
Font old = g.getFont();
g.setFont(g.getFont().deriveFont(20.0f));
TextRenderer.render(g, this.currentStatus, 10, Game.getScreenManager().getResolution().getHeight() - 60);
g.setFont(old);
}
}
public GameData getGameFile() {
return this.gameFile;
}
public String getProjectPath() {
return projectPath;
}
public double getPadding() {
return this.padding;
}
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
public void changeComponent(EditorComponent.ComponentType type) {
if (this.current != null) {
this.current.suspend();
this.getComponents().remove(this.current);
}
for (EditorComponent comp : this.comps) {
if (comp.getComponentType() == type) {
this.current = comp;
this.current.prepare();
this.getComponents().add(this.current);
break;
}
}
}
public void create() {
JFileChooser chooser;
try {
chooser = new JFileChooser(new File(".").getCanonicalPath());
chooser.setDialogTitle(Resources.get("input_select_project_folder"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()) != JFileChooser.APPROVE_OPTION) {
return;
}
if (Game.getEnvironment() != null) {
Game.loadEnvironment(null);
}
// set up project settings
this.setProjectPath(chooser.getSelectedFile().getCanonicalPath());
// load all maps in the directory
this.mapComponent.loadMaps(this.getProjectPath());
this.currentResourceFile = null;
this.gameFile = new GameData();
// add sprite sheets by tile sets of all maps in the project director
for (Map map : this.mapComponent.getMaps()) {
this.loadSpriteSheets(map);
}
Program.getAssetTree().forceUpdate();
// load custom emitter files
this.loadCustomEmitters(this.getGameFile().getEmitters());
// update new game file by the loaded information
this.updateGameFileMaps();
// display first available map after loading all stuff
if (!this.mapComponent.getMaps().isEmpty()) {
this.mapComponent.loadEnvironment(this.mapComponent.getMaps().get(0));
this.changeComponent(ComponentType.MAP);
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
this.setCurrentStatus("created new project");
}
public void load() {
if (EditorFileChooser.showFileDialog(GameData.FILE_EXTENSION, GAME_FILE_NAME, false, GameData.FILE_EXTENSION) == JFileChooser.APPROVE_OPTION) {
this.load(EditorFileChooser.instance().getSelectedFile());
}
}
public void load(File gameFile) {
boolean proceedLoading = Program.notifyPendingChanges();
if (!proceedLoading) {
return;
}
final long currentTime = System.nanoTime();
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_LOAD, 0, 0);
Game.getScreenManager().getRenderComponent().setCursorOffsetX(0);
Game.getScreenManager().getRenderComponent().setCursorOffsetY(0);
this.loading = true;
try {
if (!FileUtilities.getExtension(gameFile).equals(GameData.FILE_EXTENSION)) {
log.log(Level.SEVERE, "unsupported file format {0}", FileUtilities.getExtension(gameFile));
return;
}
if (!gameFile.exists()) {
log.log(Level.SEVERE, "gameFile {0} does not exist", gameFile);
return;
}
UndoManager.clearAll();
// set up project settings
this.currentResourceFile = gameFile.getPath();
this.gameFile = GameData.load(gameFile.getPath());
Program.getUserPreferences().setLastGameFile(gameFile.getPath());
Program.getUserPreferences().addOpenedFile(this.currentResourceFile);
Program.loadRecentFiles();
this.setProjectPath(FileUtilities.getParentDirPath(gameFile.getAbsolutePath()));
// load maps from game file
this.mapComponent.loadMaps(this.getGameFile().getMaps());
ImageCache.clearAll();
Spritesheet.getSpritesheets().clear();
// load sprite sheets from different sources:
// 1. add sprite sheets from game file
// 2. add sprite sheets by tile sets of all maps in the game file
this.loadSpriteSheets(this.getGameFile().getSpriteSheets(), true);
log.log(Level.INFO, "{0} spritesheets loaded from {1}", new Object[] { this.getGameFile().getSpriteSheets().size(), this.currentResourceFile });
for (Map map : this.mapComponent.getMaps()) {
this.loadSpriteSheets(map);
}
// load custom emitter files
this.loadCustomEmitters(this.getGameFile().getEmitters());
Program.getAssetTree().forceUpdate();
// display first available map after loading all stuff
// also switch to map component
if (!this.mapComponent.getMaps().isEmpty()) {
this.mapComponent.loadEnvironment(this.mapComponent.getMaps().get(0));
} else {
Game.loadEnvironment(null);
}
this.changeComponent(ComponentType.MAP);
this.setCurrentStatus(Resources.get("status_gamefile_loaded"));
} finally {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
log.log(Level.INFO, "Loading gamefile {0} took: {1} ms", new Object[] { gameFile, (System.nanoTime() - currentTime) / 1000000.0 });
this.loading = false;
}
}
public void importSpriteFile() {
if (EditorFileChooser.showFileDialog(SPRITE_FILE_NAME, "Import " + SPRITE_FILE_NAME, false, SpriteSheetInfo.PLAIN_TEXT_FILE_EXTENSION) == JFileChooser.APPROVE_OPTION) {
File spriteFile = EditorFileChooser.instance().getSelectedFile();
if (spriteFile == null) {
return;
}
List<Spritesheet> loaded = Spritesheet.load(spriteFile.toString());
List<SpriteSheetInfo> infos = new ArrayList<>();
for (Spritesheet sprite : loaded) {
SpriteSheetInfo info = new SpriteSheetInfo(sprite);
infos.add(info);
this.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(info.getName()));
this.getGameFile().getSpriteSheets().add(info);
}
this.loadSpriteSheets(infos, true);
}
}
public void importSpriteSheets() {
if (EditorFileChooser.showFileDialog(SPRITESHEET_FILE_NAME, "Import " + SPRITESHEET_FILE_NAME, true, ImageFormat.getAllExtensions()) == JFileChooser.APPROVE_OPTION) {
this.importSpriteSheets(EditorFileChooser.instance().getSelectedFiles());
}
}
public void importSpriteSheets(File... files) {
SpritesheetImportPanel spritePanel = new SpritesheetImportPanel(files);
int option = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), spritePanel, Resources.get("menu_assets_editSprite"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (option != JOptionPane.OK_OPTION) {
return;
}
// TODO: somehow improve this to allow keeping the animation frames and only
// update the image
Collection<SpriteSheetInfo> sprites = spritePanel.getSpriteSheets();
for (SpriteSheetInfo info : sprites) {
this.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(info.getName()));
this.getGameFile().getSpriteSheets().add(info);
log.log(Level.INFO, "imported spritesheet {0}", new Object[] { info.getName() });
}
this.loadSpriteSheets(sprites, true);
}
public void importEmitters() {
XmlImportDialog.importXml("Emitter", file -> {
EmitterData emitter = XmlUtilities.readFromFile(EmitterData.class, file.toString());
if (emitter == null) {
return;
}
if (this.gameFile.getEmitters().stream().anyMatch(x -> x.getName().equals(emitter.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_emitter_question", emitter.getName()), Resources.get("import_emitter_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
return;
}
this.gameFile.getEmitters().removeIf(x -> x.getName().equals(emitter.getName()));
}
this.gameFile.getEmitters().add(emitter);
log.log(Level.INFO, "imported emitter {0} from {1}", new Object[] { emitter.getName(), file });
});
}
public void importBlueprints() {
XmlImportDialog.importXml("Blueprint", file -> {
Blueprint blueprint = XmlUtilities.readFromFile(Blueprint.class, file.toString());
if (blueprint == null) {
return;
}
if (this.gameFile.getBluePrints().stream().anyMatch(x -> x.getName().equals(blueprint.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_blueprint_question", blueprint.getName()), Resources.get("import_blueprint_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
return;
}
this.gameFile.getBluePrints().removeIf(x -> x.getName().equals(blueprint.getName()));
}
this.gameFile.getBluePrints().add(blueprint);
log.log(Level.INFO, "imported blueprint {0} from {1}", new Object[] { blueprint.getName(), file });
});
}
public void importTilesets() {
XmlImportDialog.importXml("Tilesets", Tileset.FILE_EXTENSION, file -> {
Tileset tileset = XmlUtilities.readFromFile(Tileset.class, file.toString());
if (tileset == null) {
return;
}
String path = FileUtilities.getParentDirPath(file.getPath());
tileset.setMapPath(path);
if (this.gameFile.getTilesets().stream().anyMatch(x -> x.getName().equals(tileset.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_tileset_title", tileset.getName()), Resources.get("import_tileset_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
return;
}
this.getMapComponent().loadTileset(tileset, false);
}
log.log(Level.INFO, "imported tileset {0} from {1}", new Object[] { tileset.getName(), file });
});
}
public boolean isLoading() {
return this.loading;
}
public void loadSpriteSheets(Collection<SpriteSheetInfo> infos, boolean forceAssetTreeUpdate) {
infos.parallelStream().forEach(info -> {
if (Spritesheet.find(info.getName()) != null) {
Spritesheet.update(info);
} else {
Spritesheet.load(info);
}
});
if (this.loading) {
return;
}
ImageCache.clearAll();
this.getMapComponent().reloadEnvironment();
if (forceAssetTreeUpdate) {
Program.getAssetTree().forceUpdate();
}
}
public void saveMapSnapshot() {
IMap currentMap = Game.getEnvironment().getMap();
BufferedImage img = Game.getRenderEngine().getMapRenderer(MapOrientation.ORTHOGONAL).getImage(currentMap);
try {
final String timeStamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
final File folder = new File("./screenshots/");
if (!folder.exists()) {
folder.mkdirs();
}
ImageSerializer.saveImage(new File("./screenshots/" + timeStamp + ImageFormat.PNG.toExtension()).toString(), img);
} catch (Exception e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
public void save(boolean selectFile) {
this.updateGameFileMaps();
if (this.getGameFile() == null) {
return;
}
if (this.currentResourceFile == null || selectFile) {
JFileChooser chooser;
try {
final String source = this.getProjectPath();
chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath());
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
FileFilter filter = new FileNameExtensionFilter(GAME_FILE_NAME, GameData.FILE_EXTENSION);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
chooser.setSelectedFile(new File(DEFAULT_GAME_NAME + "." + GameData.FILE_EXTENSION));
int result = chooser.showSaveDialog(Game.getScreenManager().getRenderComponent());
if (result == JFileChooser.APPROVE_OPTION) {
String newFile = this.saveGameFile(chooser.getSelectedFile().toString());
this.currentResourceFile = newFile;
}
} catch (IOException e1) {
log.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
} else {
this.saveGameFile(this.currentResourceFile);
}
}
public MapObjectPanel getMapObjectPanel() {
return mapEditorPanel;
}
public MapComponent getMapComponent() {
return this.mapComponent;
}
public String getCurrentResourceFile() {
return this.currentResourceFile;
}
public void setMapEditorPanel(MapObjectPanel mapEditorPanel) {
this.mapEditorPanel = mapEditorPanel;
}
public MapSelectionPanel getMapSelectionPanel() {
return mapSelectionPanel;
}
public void setMapSelectionPanel(MapSelectionPanel mapSelectionPanel) {
this.mapSelectionPanel = mapSelectionPanel;
}
public String getCurrentStatus() {
return currentStatus;
}
public List<Map> getChangedMaps() {
return this.getMapComponent().getMaps().stream().filter(UndoManager::hasChanges).distinct().collect(Collectors.toList());
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
this.statusTick = Game.getLoop().getTicks();
}
public void updateGameFileMaps() {
this.getGameFile().getMaps().clear();
for (Map map : this.mapComponent.getMaps()) {
this.getGameFile().getMaps().add(map);
}
Program.getAssetTree().forceUpdate();
}
private String saveGameFile(String target) {
String saveFile = this.getGameFile().save(target, Program.getUserPreferences().isCompressFile());
Program.getUserPreferences().setLastGameFile(this.currentResourceFile);
Program.getUserPreferences().addOpenedFile(this.currentResourceFile);
Program.loadRecentFiles();
log.log(Level.INFO, "saved {0} maps, {1} spritesheets, {2} tilesets, {3} emitters, {4} blueprints to {5}",
new Object[] { this.getGameFile().getMaps().size(), this.getGameFile().getSpriteSheets().size(), this.getGameFile().getTilesets().size(), this.getGameFile().getEmitters().size(), this.getGameFile().getBluePrints().size(), this.currentResourceFile });
this.setCurrentStatus(Resources.get("status_gamefile_saved"));
if (Program.getUserPreferences().isSyncMaps()) {
this.saveMaps();
}
this.getMapSelectionPanel().bind(this.getMapComponent().getMaps());
return saveFile;
}
private void saveMaps() {
for (Map map : EditorScreen.instance().getMapComponent().getMaps()) {
UndoManager.save(map);
for (String file : FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(this.getProjectPath(), "maps"), map.getName() + "." + Map.FILE_EXTENSION)) {
String newFile = XmlUtilities.save(map, file, Map.FILE_EXTENSION);
log.log(Level.INFO, "synchronized map {0}", new Object[] { newFile });
}
}
}
private void loadCustomEmitters(List<EmitterData> emitters) {
for (EmitterData emitter : emitters) {
CustomEmitter.load(emitter);
}
}
private void loadSpriteSheets(Map map) {
List<SpriteSheetInfo> infos = new ArrayList<>();
int cnt = 0;
for (ITileset tileSet : map.getTilesets()) {
if (tileSet.getImage() == null || Spritesheet.find(tileSet.getName()) != null) {
continue;
}
Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource());
if (sprite == null) {
sprite = Spritesheet.load(tileSet);
if (sprite == null) {
continue;
}
}
infos.add(new SpriteSheetInfo(sprite));
cnt++;
}
for (IImageLayer imageLayer : map.getImageLayers()) {
Spritesheet sprite = Spritesheet.find(imageLayer.getImage().getSource());
if (sprite == null) {
BufferedImage img = Resources.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true);
if (img == null) {
continue;
}
sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight());
if (sprite == null) {
continue;
}
}
SpriteSheetInfo info = new SpriteSheetInfo(sprite);
infos.add(info);
this.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(info.getName()));
this.getGameFile().getSpriteSheets().add(info);
cnt++;
}
this.loadSpriteSheets(infos, false);
for (SpriteSheetInfo info : infos) {
if (!this.getGameFile().getSpriteSheets().stream().anyMatch(x -> x.getName().equals(info.getName()))) {
this.getGameFile().getSpriteSheets().add(info);
}
}
if (cnt > 0) {
log.log(Level.INFO, "{0} tilesets loaded from {1}", new Object[] { cnt, map.getName() });
}
}
} |
package ibis.connect.socketFactory;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Enumeration;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.lang.reflect.Constructor;
import ibis.connect.util.MyDebug;
/* A generalized SocketFactory which supports:
-- client/server connection scheme
-- brokered connections through a control link
*/
public class ExtSocketFactory
{
/** Vector of SocketTypes in the order of preference
* for the current strategy.
*/
private static Vector types = new Vector();
/** Map which converts a SocketType nicknames into
* the class name which implements it.
*/
private static Hashtable nicknames = new Hashtable();
private static SocketType defaultClientServer = null;
private static SocketType defaultBrokeredLink = null;
// Some possible default strategies...
// -1- Plain TCP only- no firewall support.
private static final String[] strategyTCP =
{ "PlainTCP" };
// -2- full range of conection methods: supports firewalls
private static final String[] strategyFirewall =
{ "TCPSplice", "RoutedMessages", "PlainTCP" };
// -3- supports firewall for control only, no splicing. Usefull for tests only.
private static final String[] strategyControl =
{ "RoutedMessages", "PlainTCP" };
// -4- TCP splicing only- for tests.
private static final String[] strategySplicing =
{ "TCPSplice", "PlainTCP" };
// Pick one of the above choices for defaults
private static String[] defaultTypes = strategyTCP;
/* static constructor
*/
static {
if(MyDebug.VERBOSE())
System.err.println("
// init types table
declareNickname("PlainTCP",
"ibis.connect.socketFactory.PlainTCPSocketType");
declareNickname("TCPSplice",
"ibis.connect.tcpSplicing.TCPSpliceSocketType");
declareNickname("RoutedMessages",
"ibis.connect.routedMessages.RoutedMessagesSocketType");
declareNickname("ParallelStreams",
"ibis.connect.parallelStreams.ParallelStreamsSocketType");
declareNickname("PortRange",
"ibis.connect.socketFactory.PortRangeSocketType");
declareNickname("SSL",
"ibis.connect.socketFactory.SSLSocketType");
Properties p = System.getProperties();
String bl = p.getProperty("ibis.connect.data_links");
String cs = p.getProperty("ibis.connect.control_links");
if(bl == null || cs == null) {
if(MyDebug.VERBOSE())
System.err.println("# Loading defaults...");
for(int i=0; i<defaultTypes.length; i++)
{
String n = defaultTypes[i];
loadSocketType(n);
}
}
if(bl == null) {
defaultBrokeredLink = findBrokeredType();
} else {
defaultBrokeredLink = loadSocketType(bl);
}
if(cs == null) {
defaultClientServer = findClientServerType();
} else {
defaultClientServer = loadSocketType(cs);
}
if(MyDebug.VERBOSE()) {
System.err.println("# Default for client-server: " +
defaultClientServer.getSocketTypeName());
System.err.println("# Default for brokered link: " +
defaultBrokeredLink.getSocketTypeName());
System.err.println("
}
}
/* static destructor
*/
public static void shutdown()
{
for(int i=0; i<types.size(); i++)
{
SocketType t = (SocketType)types.get(i);
t.destroySocketType();
}
}
private static void declareNickname(String nickname, String className)
{
nicknames.put(nickname.toLowerCase(), className);
}
/* loads a SocketType into the factory
* name: a nickname from the 'nicknames' hashtable, or a
* fully-qualified class name which extends SocketType
*/
private static synchronized SocketType loadSocketType(String socketType)
{
SocketType t = null;
Constructor cons;
String className = (String)nicknames.get(socketType.toLowerCase());
if(className == null)
className = socketType;
try {
Class c = Class.forName(className);
cons = c.getConstructor(null);
} catch(Exception e) {
System.err.println("# ExtSocketFactory: error while loading socket type.");
System.err.println("# ExtSocketFactory: socket type "+socketType+" not found.");
System.err.println("# known types are:");
Enumeration i = nicknames.keys();
while(i.hasMoreElements()) {
System.err.println((String)i.nextElement());
}
throw new Error("ExtSocketFactory: class not found: "+className, e);
}
try {
t = (SocketType)cons.newInstance(null);
if (MyDebug.VERBOSE()) {
System.err.println("# Registering socket type: "+t.getSocketTypeName());
System.err.println("# class name: "+t.getClass().getName());
System.err.println("# supports client/server: "+t.supportsClientServer());
System.err.println("# supports brokered links: "+t.supportsBrokeredLinks());
}
types.add(t);
} catch(Exception e) {
System.err.println("# ExtSocketFactory: Socket type constructor " + className + " got exception:");
e.printStackTrace();
System.err.println("# ExtSocketFactory: loadSocketType returns null");
}
return t;
}
// Bootstrap client sockets: Socket(addr, port);
public static Socket createClientSocket(InetAddress addr, int port)
throws IOException
{
Socket s = null;
SocketType t = defaultClientServer;
if(t == null)
throw new Error("no socket type found!");
ClientServerSocketFactory f = null;
try {
f = (ClientServerSocketFactory)t;
} catch(Exception e) {
System.err.println("SocketFactory: SocketType "+
t.getSocketTypeName()+
" does not support client/sever connection establishment.");
throw new Error(e);
}
s = f.createClientSocket(addr, port);
return s;
}
// Bootstrap server sockets: ServerSocket(port, backlog, addr);
public static ServerSocket createServerSocket(int port, int backlog, InetAddress addr)
throws IOException
{
return createServerSocket(new InetSocketAddress(addr, port), backlog);
}
public static ServerSocket createServerSocket(InetSocketAddress addr, int backlog)
throws IOException
{
ServerSocket s = null;
SocketType t = defaultClientServer;
if(t == null)
throw new Error("no socket type found!");
ClientServerSocketFactory f = null;
try {
f = (ClientServerSocketFactory)t;
} catch(Exception e) {
System.err.println("SocketFactory: SocketType "+
t.getSocketTypeName()+
" does not support client/sever connection establishment.");
throw new Error(e);
}
s = f.createServerSocket(addr, backlog);
return s;
}
private static Socket createBrokeredSocket(InputStream in, OutputStream out,
boolean hintIsServer,
SocketType t,
SocketType.ConnectProperties props)
throws IOException
{
Socket s = null;
BrokeredSocketFactory f = null;
try {
f = (BrokeredSocketFactory)t;
} catch(Exception e) {
System.err.println("SocketFactory: SocketType "+
t.getSocketTypeName()+
" does not support brokered connection establishment.");
throw new Error(e);
}
MyDebug.debug("SocketFactory: creating brokered socket- hint="+hintIsServer+
"; type="+t.getSocketTypeName());
s = f.createBrokeredSocket(in, out, hintIsServer, props);
return s;
}
// Data connections: when a service link is available
public static Socket createBrokeredSocket(InputStream in, OutputStream out,
boolean hintIsServer)
throws IOException
{
SocketType t = defaultBrokeredLink;
SocketType.ConnectProperties props =
new SocketType.DefaultConnectProperties();
if(t == null)
throw new Error("no socket type found!");
return createBrokeredSocket(in, out, hintIsServer, t, props);
}
public static Socket createBrokeredSocket(InputStream in, OutputStream out,
boolean hintIsServer,
SocketType.ConnectProperties props)
throws IOException
{
SocketType t = null;
String st = null;
Socket s;
if(props != null) {
st = props.getProperty("SocketType");
}
if(st == null) {
s = createBrokeredSocket(in, out, hintIsServer);
} else {
if(MyDebug.VERBOSE()) {
System.err.println("# Selected socket type '"+st+"' through properties.");
}
t = findSocketType(st);
if(t == null)
throw new Error("Socket type not found: "+st);
s = createBrokeredSocket(in, out, hintIsServer, t, props);
}
return s;
}
/* Helper function to automatically design the 'Brokered' part
* of new SocketTypes which are basically client/server.
*/
/* TODO: the 'hint' shouldn't be needed. There should be an
* election to chose who is client and who is server.
* WARNING: this will introduce a change in the API!
*/
public static Socket createBrokeredSocketFromClientServer(ClientServerSocketFactory type,
InputStream in, OutputStream out,
boolean hintIsServer)
throws IOException
{
Socket s = null;
if(hintIsServer) {
ServerSocket server = type.createServerSocket(new InetSocketAddress(InetAddress.getLocalHost(), 0), 1);
ObjectOutputStream os = new ObjectOutputStream(out);
Hashtable lInfo = new Hashtable();
lInfo.put("socket_address", server.getInetAddress());
lInfo.put("socket_port", new Integer(server.getLocalPort()));
os.writeObject(lInfo);
os.flush();
s = server.accept();
} else {
ObjectInputStream is = new ObjectInputStream(in);
Hashtable rInfo = null;
try {
rInfo = (Hashtable)is.readObject();
} catch (ClassNotFoundException e) {
throw new Error(e);
}
InetAddress raddr = (InetAddress)rInfo.get("socket_address");
int rport = ((Integer) rInfo.get("socket_port") ).intValue();
s = type.createClientSocket(raddr, rport);
}
return s;
}
/* Find by name a SocketType in the list of known SocketTypes
*/
// TODO: ugly code. This should use a Hashtable.
private static synchronized SocketType findSocketType(String name)
{
SocketType t = null;
for(int i=0; i<types.size(); i++)
{
t = (SocketType)types.get(i);
if(t.getSocketTypeName().equalsIgnoreCase(name))
return t;
}
return loadSocketType(name);
}
/* Find a default client/server SocketType when none is given
* by system properties (ibis.connect.control_links).
*/
private static synchronized SocketType findClientServerType()
{
for(int i=0; i<types.size(); i++)
{
SocketType t = (SocketType)types.get(i);
if(t.supportsClientServer())
{
if (MyDebug.VERBOSE()) {
System.err.println("# Selected type: '"+
t.getSocketTypeName()+
"' for client/server connection.");
}
return t;
}
}
System.err.println("# ExtSocketFactory: warning- no SocketType found for client/server link!");
return null;
}
/* Find a default brokered SocketType when none is given
* by system properties (ibis.connect.data_links).
*/
private static synchronized SocketType findBrokeredType()
{
for(int i=0; i<types.size(); i++)
{
SocketType t = (SocketType)types.get(i);
if(t.supportsBrokeredLinks())
{
if (MyDebug.VERBOSE()) {
System.err.println("# Selected type: '"+
t.getSocketTypeName()+
"' for brokered link.");
}
return t;
}
}
System.err.println("# ExtSocketFactory: warning- no SocketType found for brokered links!");
return null;
}
} |
package markehme.factionsplus;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class FactionsPlusUpdate {
static public void checkUpdates() {
String content = null;
URLConnection connection = null;
String v = FactionsPlus.version;
if(FactionsPlus.config.getBoolean("disableUpdateCheck")) {
return;
}
FactionsPlus.info("Checking for updates ... ");
Scanner scanner=null;
try {
connection = new URL("http:
scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
} catch ( Exception ex ) {
ex.printStackTrace();
FactionsPlus.info("Failed to check for updates.");
return;
}finally{
if (null != scanner) {
scanner.close();
}
}
if(!content.trim().equalsIgnoreCase(v.trim())) {
FactionsPlus.log.warning("! -=====================================- !");
FactionsPlus.log.warning("FactionsPlus has an update, you");
FactionsPlus.log.warning("can upgrade to version " + content.trim() + " via");
FactionsPlus.log.warning("http://dev.bukkit.org/server-mods/factionsplus/");
FactionsPlus.log.warning("! -=====================================- !");
} else {
FactionsPlus.info("Up to date!");
}
}
} |
package ie.lero.evoting.test.data;
import election.tally.AbstractBallotCounting;
import election.tally.AbstractCountStatus;
import election.tally.Ballot;
import election.tally.BallotBox;
import election.tally.BallotCounting;
import election.tally.Candidate;
import election.tally.CandidateStatus;
import election.tally.Constituency;
import election.tally.CountConfiguration;
import election.tally.Decision;
import election.tally.DecisionStatus;
import election.tally.ElectionStatus;
public class TestDataGenerator {
private static boolean testOutOfRangeValues = true;
private static int abstractBallotCounting_count = 0;
private static int abstractCountStatus_count = 0;
private static int ballot_count = 0;
private static int ballotBox_count = 0;
private static int ballotCounting_count = 0;
private static int candidate_count = 0;
private static int constituency_count = 0;
private static int decision_count = 0;
/**
* AbstractBallotCounting is a top level class; it is extended by
* BallotCouting but is neither used as a field nor a formal parameter in
* any other class.
*/
//@ requires 0 <= n;
public static AbstractBallotCounting getAbstractBallotCounting(int n) {
if (abstractBallotCounting_count == 0 || n == 0) {
abstractBallotCounting_count++;
final AbstractBallotCounting ballotCounting = new BallotCounting();
return ballotCounting;
}
throw new java.util.NoSuchElementException();
}
// TODO construct a set of unique values
// TODO construct out-of-range values
public static byte[] getByteArray() {
final byte[] bytes = {
DecisionStatus.DEEM_ELECTED,
DecisionStatus.EXCLUDE,
DecisionStatus.NO_DECISION,
ElectionStatus.COUNTING,
ElectionStatus.EMPTY,
ElectionStatus.FINISHED,
ElectionStatus.LOADING,
ElectionStatus.PRECOUNT,
ElectionStatus.PRELOAD,
ElectionStatus.SETTING_UP,
AbstractCountStatus.ALL_SEATS_FILLED,
AbstractCountStatus.CANDIDATE_ELECTED,
AbstractCountStatus.CANDIDATE_EXCLUDED,
AbstractCountStatus.CANDIDATES_HAVE_QUOTA,
AbstractCountStatus.END_OF_COUNT,
AbstractCountStatus.LAST_SEAT_BEING_FILLED,
AbstractCountStatus.MORE_CONTINUING_CANDIDATES_THAN_REMAINING_SEATS,
AbstractCountStatus.NO_SEATS_FILLED_YET,
AbstractCountStatus.NO_SURPLUS_AVAILABLE,
AbstractCountStatus.ONE_CONTINUING_CANDIDATE_PER_REMAINING_SEAT,
AbstractCountStatus.ONE_OR_MORE_SEATS_REMAINING,
AbstractCountStatus.READY_FOR_NEXT_ROUND_OF_COUNTING,
AbstractCountStatus.READY_TO_COUNT,
AbstractCountStatus.READY_TO_MOVE_BALLOTS,
AbstractCountStatus.SURPLUS_AVAILABLE,
CandidateStatus.CONTINUING,
CandidateStatus.ELECTED,
CandidateStatus.ELIMINATED
};
return bytes;
}
//@ requires 0 <= n;
public static Constituency getConstituency(int n) {
if (constituency_count == 0 || n == 0) {
constituency_count++;
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(1, 5);
constituency.setNumberOfCandidates(2);
return constituency;
} else if (n <= 3) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(n, 3);
constituency.setNumberOfCandidates(n + 1);
return constituency;
} else if (n <= 5) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(n, 5);
constituency.setNumberOfCandidates(n + 2);
} else if (n == 6) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(1, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 7) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(2, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 8) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(3, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 9) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(4, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 10) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(2, 5);
constituency.setNumberOfCandidates(n);
} else if (n == 11) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(3, 5);
constituency.setNumberOfCandidates(n);
} else if (n == 12) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(5, 5);
constituency.setNumberOfCandidates(Candidate.MAX_CANDIDATES);
} else if (n == 13) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(4, 4);
constituency.setNumberOfCandidates(Candidate.MAX_CANDIDATES - 1);
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static Ballot getBallot(int n) {
if (ballot_count == 0 || n == 0) {
ballot_count++;
int[] list = new int[0];
return new Ballot(list);
} else if (n <= Candidate.MAX_CANDIDATES) {
int[] list = new int[n];
for (int preference = 0; preference < n; preference++) {
list[preference] = Candidate.getUniqueID();
}
return new Ballot(list);
}
// TODO find all unique permutations of preferences
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static Candidate getCandidate(int n) {
if (candidate_count == 0 || n == 0) {
candidate_count++;
return new Candidate();
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static BallotBox getBallotBox(int n) {
if (ballotBox_count == 0 || n == 0) {
ballotBox_count++;
final BallotBox emptyBallotBox = new BallotBox();
return emptyBallotBox;
} else if (n == 1) {
final BallotBox oneBallotInBox = new BallotBox();
Candidate firstCandidate = new Candidate();
int[] list = new int[1];
list[0] = firstCandidate.getCandidateID();
oneBallotInBox.accept(list);
return oneBallotInBox;
} else if (n == 2) {
final BallotBox twoBallotsInBox = new BallotBox();
Candidate firstCandidate = new Candidate();
Candidate secondCandidate = new Candidate();
int[] list = new int[2];
list[0] = firstCandidate.getCandidateID();
list[1] = secondCandidate.getCandidateID();
twoBallotsInBox.accept(list);
list[0] = secondCandidate.getCandidateID();
list[1] = firstCandidate.getCandidateID();
twoBallotsInBox.accept(list);
return twoBallotsInBox;
}
// Two way ties
else if (n == 3) {
BallotBox ballotBox = new BallotBox();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
int[] list = new int[3];
// First ballot
list[0] = candidate1.getCandidateID();
list[1] = candidate2.getCandidateID();
list[2] = candidate3.getCandidateID();
ballotBox.accept(list);
// Second ballot
list[0] = candidate3.getCandidateID();
list[1] = candidate2.getCandidateID();
list[2] = candidate1.getCandidateID();
ballotBox.accept(list);
return ballotBox;
}
// Three way ties
else if (n == 4) {
BallotBox ballotBox = new BallotBox();
Candidate candidate1 = new Candidate();
Candidate candidate2 = new Candidate();
Candidate candidate3 = new Candidate();
Candidate candidate4 = new Candidate();
Candidate candidate5 = new Candidate();
int[] list = new int[4];
// First ballot
list[0] = candidate1.getCandidateID();
list[1] = candidate2.getCandidateID();
list[2] = candidate3.getCandidateID();
ballotBox.accept(list);
// Second ballot
list[0] = candidate2.getCandidateID();
list[1] = candidate3.getCandidateID();
list[2] = candidate4.getCandidateID();
list[3] = candidate5.getCandidateID();
ballotBox.accept(list);
// Last ballot
list[0] = candidate3.getCandidateID();
list[1] = candidate4.getCandidateID();
list[2] = candidate5.getCandidateID();
ballotBox.accept(list);
return ballotBox;
}
throw new java.util.NoSuchElementException();
}
public static int[] getIntArray() {
final int[] integers = {
AbstractBallotCounting.NONE_FOUND_YET,
Ballot.MAX_BALLOTS,
Ballot.NONTRANSFERABLE,
Candidate.MAX_CANDIDATES,
Candidate.NO_CANDIDATE,
CountConfiguration.MAXCOUNT,
CountConfiguration.MAXVOTES,
Decision.MAX_DECISIONS
};
return integers;
}
public static long[] getLongArray() {
final long[] longs = new long[0];
return longs;
}
//@ requires 0 <= n;
public static Decision getDecision(int n) {
if (decision_count == 0 || n == 0) {
decision_count++;
return new Decision();
}
else if (n == 1) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.DEEM_ELECTED);
return decision;
}
else if (n == 2) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.EXCLUDE);
return decision;
}
else if (n == 3) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.NO_DECISION);
return decision;
}
throw new java.util.NoSuchElementException();
}
/**
* BallotCounting is the top level object in the system; it is neither
* a field nor a formal parameter for any other object.
*
* @param n
* @return
*/
//@ requires 0 <= n;
public static BallotCounting getBallotCounting(int n) {
if (ballotCounting_count == 0 || n == 0) {
ballotCounting_count++;
return new BallotCounting();
}
throw new java.util.NoSuchElementException();
}
public static Object[] getIntArrayAsObject() {
final Object[] intArray = new Object[0];
return intArray;
}
//@ requires 0 <= n;
public static AbstractCountStatus getAbstractCountStatus(int n) {
if (abstractCountStatus_count == 0 || n == 0) {
abstractCountStatus_count++;
BallotCounting ballotCounting = new BallotCounting();
return ballotCounting.getCountStatus();
}
throw new java.util.NoSuchElementException();
}
} |
package com.healthmarketscience.jackcess;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Access table (logical) index. Logical indexes are backed for IndexData,
* where one or more logical indexes could be backed by the same data.
*
* @author Tim McCune
*/
public class Index implements Comparable<Index> {
protected static final Log LOG = LogFactory.getLog(Index.class);
/** index type for primary key indexes */
static final byte PRIMARY_KEY_INDEX_TYPE = (byte)1;
/** index type for foreign key indexes */
static final byte FOREIGN_KEY_INDEX_TYPE = (byte)2;
/** flag for indicating that updates should cascade in a foreign key index */
private static final byte CASCADE_UPDATES_FLAG = (byte)1;
/** flag for indicating that deletes should cascade in a foreign key index */
private static final byte CASCADE_DELETES_FLAG = (byte)1;
/** index table type for the "primary" table in a foreign key index */
private static final byte PRIMARY_TABLE_TYPE = (byte)1;
/** indicate an invalid index number for foreign key field */
private static final int INVALID_INDEX_NUMBER = -1;
/** the actual data backing this index (more than one index may be backed by
the same data */
private final IndexData _data;
/** 0-based index number */
private final int _indexNumber;
/** the type of the index */
private final byte _indexType;
/** Index name */
private String _name;
/** foreign key reference info, if any */
private final ForeignKeyReference _reference;
protected Index(ByteBuffer tableBuffer, List<IndexData> indexDatas,
JetFormat format)
throws IOException
{
ByteUtil.forward(tableBuffer, format.SKIP_BEFORE_INDEX_SLOT); //Forward past Unknown
_indexNumber = tableBuffer.getInt();
int indexDataNumber = tableBuffer.getInt();
// read foreign key reference info
byte relIndexType = tableBuffer.get();
int relIndexNumber = tableBuffer.getInt();
int relTablePageNumber = tableBuffer.getInt();
byte cascadeUpdatesFlag = tableBuffer.get();
byte cascadeDeletesFlag = tableBuffer.get();
_indexType = tableBuffer.get();
if((_indexType == FOREIGN_KEY_INDEX_TYPE) &&
(relIndexNumber != INVALID_INDEX_NUMBER)) {
_reference = new ForeignKeyReference(
relIndexType, relIndexNumber, relTablePageNumber,
(cascadeUpdatesFlag == CASCADE_UPDATES_FLAG),
(cascadeDeletesFlag == CASCADE_DELETES_FLAG));
} else {
_reference = null;
}
ByteUtil.forward(tableBuffer, format.SKIP_AFTER_INDEX_SLOT); //Skip past Unknown
_data = indexDatas.get(indexDataNumber);
_data.addIndex(this);
}
public IndexData getIndexData() {
return _data;
}
public Table getTable() {
return getIndexData().getTable();
}
public JetFormat getFormat() {
return getTable().getFormat();
}
public PageChannel getPageChannel() {
return getTable().getPageChannel();
}
public int getIndexNumber() {
return _indexNumber;
}
public byte getIndexFlags() {
return getIndexData().getIndexFlags();
}
public int getUniqueEntryCount() {
return getIndexData().getUniqueEntryCount();
}
public int getUniqueEntryCountOffset() {
return getIndexData().getUniqueEntryCountOffset();
}
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public boolean isPrimaryKey() {
return _indexType == PRIMARY_KEY_INDEX_TYPE;
}
public boolean isForeignKey() {
return _indexType == FOREIGN_KEY_INDEX_TYPE;
}
public ForeignKeyReference getReference() {
return _reference;
}
/**
* Whether or not {@code null} values are actually recorded in the index.
*/
public boolean shouldIgnoreNulls() {
return getIndexData().shouldIgnoreNulls();
}
/**
* Whether or not index entries must be unique.
* <p>
* Some notes about uniqueness:
* <ul>
* <li>Access does not seem to consider multiple {@code null} entries
* invalid for a unique index</li>
* <li>text indexes collapse case, and Access seems to compare <b>only</b>
* the index entry bytes, therefore two strings which differ only in
* case <i>will violate</i> the unique constraint</li>
* </ul>
*/
public boolean isUnique() {
return getIndexData().isUnique();
}
/**
* Returns the Columns for this index (unmodifiable)
*/
public List<IndexData.ColumnDescriptor> getColumns() {
return getIndexData().getColumns();
}
/**
* Whether or not the complete index state has been read.
*/
public boolean isInitialized() {
return getIndexData().isInitialized();
}
/**
* Forces initialization of this index (actual parsing of index pages).
* normally, the index will not be initialized until the entries are
* actually needed.
*/
public void initialize() throws IOException {
getIndexData().initialize();
}
/**
* Writes the current index state to the database.
* <p>
* Forces index initialization.
*/
public void update() throws IOException {
getIndexData().update();
}
/**
* Adds a row to this index
* <p>
* Forces index initialization.
*
* @param row Row to add
* @param rowId rowId of the row to be added
*/
public void addRow(Object[] row, RowId rowId)
throws IOException
{
getIndexData().addRow(row, rowId);
}
/**
* Removes a row from this index
* <p>
* Forces index initialization.
*
* @param row Row to remove
* @param rowId rowId of the row to be removed
*/
public void deleteRow(Object[] row, RowId rowId)
throws IOException
{
getIndexData().deleteRow(row, rowId);
}
/**
* Gets a new cursor for this index.
* <p>
* Forces index initialization.
*/
public IndexData.EntryCursor cursor()
throws IOException
{
return cursor(null, true, null, true);
}
/**
* Gets a new cursor for this index, narrowed to the range defined by the
* given startRow and endRow.
* <p>
* Forces index initialization.
*
* @param startRow the first row of data for the cursor, or {@code null} for
* the first entry
* @param startInclusive whether or not startRow is inclusive or exclusive
* @param endRow the last row of data for the cursor, or {@code null} for
* the last entry
* @param endInclusive whether or not endRow is inclusive or exclusive
*/
public IndexData.EntryCursor cursor(Object[] startRow,
boolean startInclusive,
Object[] endRow,
boolean endInclusive)
throws IOException
{
return getIndexData().cursor(startRow, startInclusive, endRow,
endInclusive);
}
public Object[] constructIndexRowFromEntry(Object... values)
{
return getIndexData().constructIndexRowFromEntry(values);
}
/**
* Constructs an array of values appropriate for this index from the given
* column value.
* @return the appropriate sparse array of data or {@code null} if not all
* columns for this index were provided
*/
public Object[] constructIndexRow(String colName, Object value)
{
return constructIndexRow(Collections.singletonMap(colName, value));
}
/**
* Constructs an array of values appropriate for this index from the given
* column values.
* @return the appropriate sparse array of data or {@code null} if not all
* columns for this index were provided
*/
public Object[] constructIndexRow(Map<String,Object> row)
{
return getIndexData().constructIndexRow(row);
}
@Override
public String toString() {
StringBuilder rtn = new StringBuilder();
rtn.append("\tName: (").append(getTable().getName()).append(") ")
.append(_name);
rtn.append("\n\tNumber: ").append(_indexNumber);
rtn.append("\n\tIs Primary Key: ").append(isPrimaryKey());
rtn.append("\n\tIs Foreign Key: ").append(isForeignKey());
if(_reference != null) {
rtn.append("\n\tForeignKeyReference: ").append(_reference);
}
rtn.append(_data.toString());
rtn.append("\n\n");
return rtn.toString();
}
public int compareTo(Index other) {
if (_indexNumber > other.getIndexNumber()) {
return 1;
} else if (_indexNumber < other.getIndexNumber()) {
return -1;
} else {
return 0;
}
}
/**
* Writes the logical index definitions into a table definition buffer.
* @param buffer Buffer to write to
* @param indexes List of IndexBuilders to write definitions for
*/
protected static void writeDefinitions(
ByteBuffer buffer, List<IndexBuilder> indexes, Charset charset)
throws IOException
{
// write logical index information
for(IndexBuilder idx : indexes) {
buffer.putInt(Table.MAGIC_TABLE_NUMBER); // seemingly constant magic value which matches the table def
buffer.putInt(idx.getIndexNumber()); // index num
buffer.putInt(idx.getIndexDataNumber()); // index data num
buffer.put((byte)0); // related table type
buffer.putInt(INVALID_INDEX_NUMBER); // related index num
buffer.putInt(0); // related table definition page number
buffer.put((byte)0); // cascade updates flag
buffer.put((byte)0); // cascade deletes flag
buffer.put(idx.getType()); // index type flags
buffer.putInt(0); // unknown
}
// write index names
for(IndexBuilder idx : indexes) {
Table.writeName(buffer, idx.getName(), charset);
}
}
/**
* Information about a foreign key reference defined in an index (when
* referential integrity should be enforced).
*/
public static class ForeignKeyReference
{
private final byte _tableType;
private final int _otherIndexNumber;
private final int _otherTablePageNumber;
private final boolean _cascadeUpdates;
private final boolean _cascadeDeletes;
public ForeignKeyReference(
byte tableType, int otherIndexNumber, int otherTablePageNumber,
boolean cascadeUpdates, boolean cascadeDeletes)
{
_tableType = tableType;
_otherIndexNumber = otherIndexNumber;
_otherTablePageNumber = otherTablePageNumber;
_cascadeUpdates = cascadeUpdates;
_cascadeDeletes = cascadeDeletes;
}
public byte getTableType() {
return _tableType;
}
public boolean isPrimaryTable() {
return(getTableType() == PRIMARY_TABLE_TYPE);
}
public int getOtherIndexNumber() {
return _otherIndexNumber;
}
public int getOtherTablePageNumber() {
return _otherTablePageNumber;
}
public boolean isCascadeUpdates() {
return _cascadeUpdates;
}
public boolean isCascadeDeletes() {
return _cascadeDeletes;
}
@Override
public String toString() {
return new StringBuilder()
.append("\n\t\tOther Index Number: ").append(_otherIndexNumber)
.append("\n\t\tOther Table Page Num: ").append(_otherTablePageNumber)
.append("\n\t\tIs Primary Table: ").append(isPrimaryTable())
.append("\n\t\tIs Cascade Updates: ").append(isCascadeUpdates())
.append("\n\t\tIs Cascade Deletes: ").append(isCascadeDeletes())
.toString();
}
}
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.samskivert.jdbc.depot.Key.WhereCondition;
import com.samskivert.jdbc.depot.annotation.Computed;
import com.samskivert.jdbc.depot.clause.DeleteClause;
import com.samskivert.jdbc.depot.clause.FieldOverride;
import com.samskivert.jdbc.depot.clause.ForUpdate;
import com.samskivert.jdbc.depot.clause.FromOverride;
import com.samskivert.jdbc.depot.clause.GroupBy;
import com.samskivert.jdbc.depot.clause.InsertClause;
import com.samskivert.jdbc.depot.clause.Join;
import com.samskivert.jdbc.depot.clause.Limit;
import com.samskivert.jdbc.depot.clause.OrderBy;
import com.samskivert.jdbc.depot.clause.SelectClause;
import com.samskivert.jdbc.depot.clause.UpdateClause;
import com.samskivert.jdbc.depot.clause.Where;
import com.samskivert.jdbc.depot.expression.ColumnExp;
import com.samskivert.jdbc.depot.expression.ExpressionVisitor;
import com.samskivert.jdbc.depot.expression.FunctionExp;
import com.samskivert.jdbc.depot.expression.LiteralExp;
import com.samskivert.jdbc.depot.expression.SQLExpression;
import com.samskivert.jdbc.depot.expression.ValueExp;
import com.samskivert.jdbc.depot.operator.Conditionals.In;
import com.samskivert.jdbc.depot.operator.Conditionals.IsNull;
import com.samskivert.jdbc.depot.operator.Conditionals.FullTextMatch;
import com.samskivert.jdbc.depot.operator.Logic.Not;
import com.samskivert.jdbc.depot.operator.SQLOperator.BinaryOperator;
import com.samskivert.jdbc.depot.operator.SQLOperator.MultiOperator;
/**
* Implements the base functionality of the SQL-building pass of {@link SQLBuilder}. Dialectal
* subclasses of this should be created and returned from {@link SQLBuilder#getBuildVisitor()}.
*
* This class is intimately paired with {#link BindVisitor}.
*/
public abstract class BuildVisitor implements ExpressionVisitor
{
public String getQuery ()
{
return _builder.toString();
}
public void visit (FromOverride override)
throws Exception
{
_builder.append(" from " );
List<Class<? extends PersistentRecord>> from = override.getFromClasses();
for (int ii = 0; ii < from.size(); ii++) {
if (ii > 0) {
_builder.append(", ");
}
appendTableName(from.get(ii));
_builder.append(" as ");
appendTableAbbreviation(from.get(ii));
}
}
public void visit (FieldOverride fieldOverride)
throws Exception
{
fieldOverride.getOverride().accept(this);
if (_aliasFields) {
_builder.append(" as ");
appendIdentifier(fieldOverride.getField());
}
}
public void visit (WhereCondition<? extends PersistentRecord> whereCondition)
throws Exception
{
Class<? extends PersistentRecord> pClass = whereCondition.getPersistentClass();
String[] keyFields = Key.getKeyFields(pClass);
Comparable[] values = whereCondition.getValues();
for (int ii = 0; ii < keyFields.length; ii ++) {
if (ii > 0) {
_builder.append(" and ");
}
appendRhsColumn(pClass, keyFields[ii]);
_builder.append(values[ii] == null ? " is null " : " = ? ");
}
}
public void visit (Key key)
throws Exception
{
_builder.append(" where ");
key.condition.accept(this);
}
public void visit (MultiKey<? extends PersistentRecord> key)
throws Exception
{
_builder.append(" where ");
boolean first = true;
for (Map.Entry<String, Comparable> entry : key.getSingleFieldsMap().entrySet()) {
if (first) {
first = false;
} else {
_builder.append(" and ");
}
appendRhsColumn(key.getPersistentClass(), entry.getKey());
_builder.append(entry.getValue() == null ? " is null " : " = ? ");
}
if (!first) {
_builder.append(" and ");
}
appendRhsColumn(key.getPersistentClass(), key.getMultiField());
_builder.append(" in (");
Comparable[] values = key.getMultiValues();
for (int ii = 0; ii < values.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
_builder.append("?");
}
_builder.append(")");
}
public void visit (FunctionExp functionExp)
throws Exception
{
_builder.append(functionExp.getFunction());
_builder.append("(");
SQLExpression[] arguments = functionExp.getArguments();
for (int ii = 0; ii < arguments.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
arguments[ii].accept(this);
}
_builder.append(")");
}
public void visit (MultiOperator multiOperator)
throws Exception
{
SQLExpression[] conditions = multiOperator.getConditions();
for (int ii = 0; ii < conditions.length; ii++) {
if (ii > 0) {
_builder.append(" ").append(multiOperator.operator()).append(" ");
}
_builder.append("(");
conditions[ii].accept(this);
_builder.append(")");
}
}
public void visit (BinaryOperator binaryOperator)
throws Exception
{
binaryOperator.getLeftHandSide().accept(this);
_builder.append(binaryOperator.operator());
binaryOperator.getRightHandSide().accept(this);
}
public void visit (IsNull isNull)
throws Exception
{
isNull.getColumn().accept(this);
_builder.append(" is null");
}
public void visit (In in)
throws Exception
{
in.getColumn().accept(this);
_builder.append(" in (");
Comparable[] values = in.getValues();
for (int ii = 0; ii < values.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
_builder.append("?");
}
_builder.append(")");
}
public abstract void visit (FullTextMatch match)
throws Exception;
public void visit (ColumnExp columnExp)
throws Exception
{
appendRhsColumn(columnExp.getPersistentClass(), columnExp.getField());
}
public void visit (Not not)
throws Exception
{
_builder.append(" not (");
not.getCondition().accept(this);
_builder.append(")");
}
public void visit (GroupBy groupBy)
throws Exception
{
_builder.append(" group by ");
SQLExpression[] values = groupBy.getValues();
for (int ii = 0; ii < values.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
values[ii].accept(this);
}
}
public void visit (ForUpdate forUpdate)
throws Exception
{
_builder.append(" for update ");
}
public void visit (OrderBy orderBy)
throws Exception
{
_builder.append(" order by ");
SQLExpression[] values = orderBy.getValues();
OrderBy.Order[] orders = orderBy.getOrders();
for (int ii = 0; ii < values.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
values[ii].accept(this);
_builder.append(" ").append(orders[ii]);
}
}
public void visit (Where where)
throws Exception
{
_builder.append(" where ");
where.getCondition().accept(this);
}
public void visit (Join join)
throws Exception
{
switch (join.getType()) {
case INNER:
_builder.append(" inner join " );
break;
case LEFT_OUTER:
_builder.append(" left outer join " );
break;
case RIGHT_OUTER:
_builder.append(" right outer join " );
break;
}
appendTableName(join.getJoinClass());
_builder.append(" as ");
appendTableAbbreviation(join.getJoinClass());
_builder.append(" on ");
_ignoreOverrides = true;
join.getJoinCondition().accept(this);
_ignoreOverrides = false;
}
public void visit (Limit limit)
throws Exception
{
_builder.append(" limit ? offset ? ");
}
public void visit (LiteralExp literalExp)
throws Exception
{
_builder.append(literalExp.getText());
}
public void visit (ValueExp valueExp)
throws Exception
{
_builder.append("?");
}
public void visit (SelectClause<? extends PersistentRecord> selectClause)
throws Exception
{
Class<? extends PersistentRecord> pClass = selectClause.getPersistentClass();
boolean isInner = _innerClause;
_innerClause = true;
if (isInner) {
_builder.append("(");
}
_builder.append("select ");
if (_overrides.containsKey(pClass)) {
throw new IllegalArgumentException(
"Can not yet nest SELECTs on the same persistent record.");
}
Map<String, FieldOverride> overrideMap = new HashMap<String, FieldOverride>();
for (FieldOverride override : selectClause.getFieldOverrides()) {
overrideMap.put(override.getField(), override);
}
_overrides.put(pClass, overrideMap);
try {
// iterate over the fields we're filling in and figure out whence each one comes
boolean skip = true;
// while expanding column names in the SELECT query, do aliasing
_aliasFields = true;
for (String field : selectClause.getFields()) {
if (!skip) {
_builder.append(", ");
}
skip = false;
int len = _builder.length();
appendRhsColumn(pClass, field);
// if nothing was added, don't add a comma
if (_builder.length() == len) {
skip = true;
}
}
// then stop
_aliasFields = false;
if (selectClause.getFromOverride() != null) {
selectClause.getFromOverride().accept(this);
} else if (_types.getTableName(pClass) != null) {
_builder.append(" from ");
appendTableName(pClass);
_builder.append(" as ");
appendTableAbbreviation(pClass);
} else {
throw new SQLException("Query on @Computed entity with no FromOverrideClause.");
}
for (Join clause : selectClause.getJoinClauses()) {
clause.accept(this);
}
if (selectClause.getWhereClause() != null) {
selectClause.getWhereClause().accept(this);
}
if (selectClause.getGroupBy() != null) {
selectClause.getGroupBy().accept(this);
}
if (selectClause.getOrderBy() != null) {
selectClause.getOrderBy().accept(this);
}
if (selectClause.getLimit() != null) {
selectClause.getLimit().accept(this);
}
if (selectClause.getForUpdate() != null) {
selectClause.getForUpdate().accept(this);
}
} finally {
_overrides.remove(pClass);
}
if (isInner) {
_builder.append(")");
}
}
public void visit (UpdateClause<? extends PersistentRecord> updateClause)
throws Exception
{
Class<? extends PersistentRecord> pClass = updateClause.getPersistentClass();
_innerClause = true;
_builder.append("update ");
appendTableName(pClass);
_builder.append(" as ");
appendTableAbbreviation(pClass);
_builder.append(" set ");
String[] fields = updateClause.getFields();
Object pojo = updateClause.getPojo();
SQLExpression[] values = updateClause.getValues();
for (int ii = 0; ii < fields.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
appendLhsColumn(pClass, fields[ii]);
_builder.append(" = ");
if (pojo != null) {
_builder.append("?");
} else {
values[ii].accept(this);
}
}
updateClause.getWhereClause().accept(this);
}
public void visit (DeleteClause<? extends PersistentRecord> deleteClause)
throws Exception
{
_builder.append("delete from ");
appendTableName(deleteClause.getPersistentClass());
_builder.append(" as ");
appendTableAbbreviation(deleteClause.getPersistentClass());
_builder.append(" ");
deleteClause.getWhereClause().accept(this);
}
public void visit (InsertClause<? extends PersistentRecord> insertClause)
throws Exception
{
Class<? extends PersistentRecord> pClass = insertClause.getPersistentClass();
DepotMarshaller marsh = _types.getMarshaller(pClass);
_innerClause = true;
String[] fields = marsh.getColumnFieldNames();
_builder.append("insert into ");
appendTableName(insertClause.getPersistentClass());
_builder.append(" (");
for (int ii = 0; ii < fields.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
appendLhsColumn(pClass, fields[ii]);
}
_builder.append(") values(");
Set<String> idFields = insertClause.getIdentityFields();
for (int ii = 0; ii < fields.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
if (idFields.contains(fields[ii])) {
_builder.append("DEFAULT");
} else {
_builder.append("?");
}
}
_builder.append(")");
}
protected abstract void appendIdentifier (String field);
protected void appendTableName (Class<? extends PersistentRecord> type)
{
appendIdentifier(_types.getTableName(type));
}
protected void appendTableAbbreviation (Class<? extends PersistentRecord> type)
{
appendIdentifier(_types.getTableAbbreviation(type));
}
// Constructs a name used for assignment in e.g. INSERT/UPDATE. This is the SQL
// equivalent of an lvalue; something that can appear to the left of an equals sign.
// We do not prepend this identifier with a table abbreviation, nor do we expand
// field overrides, shadowOf declarations, or the like: it is just a column name.
protected void appendLhsColumn (Class<? extends PersistentRecord> type, String field)
throws Exception
{
DepotMarshaller dm = _types.getMarshaller(type);
FieldMarshaller fm = dm.getFieldMarshaller(field);
if (dm == null) {
throw new IllegalArgumentException(
"Unknown field on persistent record [record=" + type + ", field=" + field + "]");
}
appendIdentifier(fm.getColumnName());
}
// Appends an expression for the given field on the given persistent record; this can
// appear in a SELECT list, in WHERE clauses, etc, etc.
protected void appendRhsColumn (Class<? extends PersistentRecord> type, String field)
throws Exception
{
DepotMarshaller dm = _types.getMarshaller(type);
FieldMarshaller fm = dm.getFieldMarshaller(field);
if (dm == null) {
throw new IllegalArgumentException(
"Unknown field on persistent record [record=" + type + ", field=" + field + "]");
}
if (!_ignoreOverrides) {
Map<String, FieldOverride> fieldOverrides = _overrides.get(type);
if (fieldOverrides != null) {
// first, see if there's a field override
FieldOverride override = fieldOverrides.get(field);
if (override != null) {
// If a FieldOverride's target is in turn another FieldOverride, the second
// one is ignored. As an example, when creating ItemRecords from CloneRecords,
// we make Item.itemId = Clone.itemId. We also make Item.parentId = Item.itemId
// and would be dismayed to find Item.parentID = Item.itemId = Clone.itemId.
_ignoreOverrides = true;
override.accept(this);
_ignoreOverrides = false;
return;
}
}
}
Computed entityComputed = dm.getComputed();
// figure out the class we're selecting from unless we're otherwise overriden:
// for a concrete record, simply use the corresponding table; for a computed one,
// default to the shadowed concrete record, or null if there isn't one
Class<? extends PersistentRecord> tableClass;
if (entityComputed == null) {
tableClass = type;
} else if (!PersistentRecord.class.equals(entityComputed.shadowOf())) {
tableClass = entityComputed.shadowOf();
} else {
tableClass = null;
}
// handle the field-level @Computed annotation, if there is one
Computed fieldComputed = fm.getComputed();
if (fieldComputed != null) {
// check if the computed field has a literal SQL definition
if (fieldComputed.fieldDefinition().length() > 0) {
_builder.append(fieldComputed.fieldDefinition());
if (_aliasFields) {
_builder.append(" as ");
appendIdentifier(field);
}
return;
}
// or if we can simply ignore the field
if (!fieldComputed.required()) {
return;
}
// else see if there's an overriding shadowOf definition
if (fieldComputed.shadowOf() != null) {
tableClass = fieldComputed.shadowOf();
}
}
// if we get this far we hopefully have a table to select from
if (tableClass != null) {
appendTableAbbreviation(tableClass);
_builder.append(".");
appendIdentifier(fm.getColumnName());
return;
}
// else owie
throw new IllegalArgumentException(
"Persistent field has no definition [class=" + type + ", field=" + field + "]");
}
protected BuildVisitor (DepotTypes types)
{
_types = types;
}
protected DepotTypes _types;
/** A StringBuilder to hold the constructed SQL. */
protected StringBuilder _builder = new StringBuilder();
/** A mapping of field overrides per persistent record. */
protected Map<Class<? extends PersistentRecord>, Map<String, FieldOverride>> _overrides =
new HashMap<Class<? extends PersistentRecord>, Map<String,FieldOverride>>();
/** A flag that's set to true for inner SELECT's */
protected boolean _innerClause = false;
protected boolean _ignoreOverrides = false;
protected boolean _aliasFields = false;
} |
package org.jaxen.function;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
import org.jaxen.UnsupportedAxisException;
import org.jaxen.JaxenRuntimeException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import java.util.Iterator;
import java.util.Locale;
public class StringFunction implements Function
{
private static DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
static {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
symbols.setNaN("NaN");
symbols.setInfinity("Infinity");
format.setGroupingUsed(false);
format.setMaximumFractionDigits(32);
format.setDecimalFormatSymbols(symbols);
}
/**
* Create a new <code>StringFunction</code> object.
*/
public StringFunction() {}
/**
* Returns the string-value of
* <code>args.get(0)</code> or of the context node if ,code>args</code> is empty.
*
* @param context the context at the point in the
* expression where the function is called
* @param args list with zero or one element
*
* @return a <code>String</code>
*
* @throws FunctionCallException if <code>args</code> has more than one item
*/
public Object call(Context context,
List args) throws FunctionCallException
{
int size = args.size();
if ( size == 0 )
{
return evaluate( context.getNodeSet(),
context.getNavigator() );
}
else if ( size == 1 )
{
return evaluate( args.get(0),
context.getNavigator() );
}
throw new FunctionCallException( "string() takes at most argument." );
}
/**
* Returns the string-value of <code>obj</code>.
*
* @param obj the object whose string-value is calculated
* @param nav the navigator used to calculate the string-value
*
* @return a <code>String</code>. May be empty but is never null.
*/
public static String evaluate(Object obj,
Navigator nav)
{
try
{
if (obj == null) {
return "";
}
// Workaround because XOM uses lists for Text nodes
// so we need to check for that first
if (nav != null && nav.isText(obj))
{
return nav.getTextStringValue(obj);
}
if (obj instanceof List)
{
List list = (List) obj;
if (list.isEmpty())
{
return "";
}
// do not recurse: only first list should unwrap
obj = list.get(0);
}
if (nav != null) {
// This stack of instanceof really suggests there's
// a failure to take adavantage of polymorphism here
if (nav.isElement(obj))
{
return nav.getElementStringValue(obj);
}
else if (nav.isAttribute(obj))
{
return nav.getAttributeStringValue(obj);
}
else if (nav.isDocument(obj))
{
Iterator childAxisIterator = nav.getChildAxisIterator(obj);
while (childAxisIterator.hasNext())
{
Object descendant = childAxisIterator.next();
if (nav.isElement(descendant))
{
return nav.getElementStringValue(descendant);
}
}
}
else if (nav.isProcessingInstruction(obj))
{
return nav.getProcessingInstructionData(obj);
}
else if (nav.isComment(obj))
{
return nav.getCommentStringValue(obj);
}
else if (nav.isText(obj))
{
return nav.getTextStringValue(obj);
}
else if (nav.isNamespace(obj))
{
return nav.getNamespaceStringValue(obj);
}
}
if (obj instanceof String)
{
return (String) obj;
}
else if (obj instanceof Boolean)
{
return stringValue(((Boolean) obj).booleanValue());
}
else if (obj instanceof Number)
{
return stringValue(((Number) obj).doubleValue());
}
}
catch (UnsupportedAxisException e)
{
throw new JaxenRuntimeException(e);
}
return "";
}
private static String stringValue(double value)
{
// DecimalFormat formats negative zero as "-0".
// Therefore we need to test for zero explicitly here.
if (value == 0) return "0";
// need to synchronize object for thread-safety
String result = null;
synchronized (format) {
result = format.format(value);
}
return result;
}
private static String stringValue(boolean value)
{
return value ? "true" : "false";
}
} |
package org.jsmpp.session;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUSender;
import org.jsmpp.PDUStringException;
import org.jsmpp.SMPPConstant;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.DataCoding;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DataSmResp;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.OptionalParameter;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.PendingResponse;
import org.jsmpp.extra.ProcessRequestException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.connection.Connection;
import org.jsmpp.util.IntUtil;
import org.jsmpp.util.Sequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author uudashr
*
*/
public abstract class AbstractSession implements Session {
private static final Logger logger = LoggerFactory.getLogger(AbstractSession.class);
private static final Random random = new Random();
private final Map<Integer, PendingResponse<Command>> pendingResponse = new Hashtable<Integer, PendingResponse<Command>>();
private final Sequence sequence = new Sequence(1);
private final PDUSender pduSender;
private int pduProcessorDegree = 3;
private String sessionId = generateSessionId();
private int enquireLinkTimer = 5000;
private long transactionTimer = 2000;
public AbstractSession(PDUSender pduSender) {
this.pduSender = pduSender;
}
protected abstract AbstractSessionContext sessionContext();
protected abstract Connection connection();
protected abstract GenericMessageReceiverListener messageReceiverListener();
protected PDUSender pduSender() {
return pduSender;
}
protected Sequence sequence() {
return sequence;
}
protected PendingResponse<Command> removePendingResponse(int sequenceNumber) {
return pendingResponse.remove(sequenceNumber);
}
public String getSessionId() {
return sessionId;
}
public void setEnquireLinkTimer(int enquireLinkTimer) {
if (sessionContext().getSessionState().isBound()) {
try {
connection().setSoTimeout(enquireLinkTimer);
} catch (IOException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
this.enquireLinkTimer = enquireLinkTimer;
}
public int getEnquireLinkTimer() {
return enquireLinkTimer;
}
public void setTransactionTimer(long transactionTimer) {
this.transactionTimer = transactionTimer;
}
public long getTransactionTimer() {
return transactionTimer;
}
public SessionState getSessionState() {
return sessionContext().getSessionState();
}
public void addSessionStateListener(SessionStateListener l) {
sessionContext().addSessionStateListener(l);
}
public void removeSessionStateListener(SessionStateListener l) {
sessionContext().removeSessionStateListener(l);
}
public long getLastActivityTimestamp() {
return sessionContext().getLastActivityTimestamp();
}
public void setPduProcessorDegree(int pduProcessorDegree) throws IllegalStateException {
if (!getSessionState().equals(SessionState.CLOSED)) {
throw new IllegalStateException(
"Cannot set pdu processor degree since the pdu dispatcher thread already created.");
}
this.pduProcessorDegree = pduProcessorDegree;
}
/**
* Get the total of thread that can handle read and process PDU parallely.
*
* @return the total of thread that can handle read and process PDU
* parallely.
*/
public int getPduProcessorDegree() {
return pduProcessorDegree;
}
/**
* Send the data_sm command.
*
* @param serviceType is the service_type parameter.
* @param sourceAddrTon is the source_addr_ton parameter.
* @param sourceAddrNpi is the source_addr_npi parameter.
* @param sourceAddr is the source_addr parameter.
* @param destAddrTon is the dest_addr_ton parameter.
* @param destAddrNpi is the dest_addr_npi parameter.
* @param destinationAddr is the destination_addr parameter.
* @param esmClass is the esm_class parameter.
* @param registeredDelivery is the registered_delivery parameter.
* @param dataCoding is the data_coding parameter.
* @param optionalParameters is the optional parameters.
* @return the result of data_sm (data_sm_resp).
* @throws PDUStringException if there is an invalid PDU String found.
* @throws ResponseTimeoutException if the response take time too long.
* @throws InvalidResponseException if the response is invalid.
* @throws NegativeResponseException if the response return non-ok command_status.
* @throws IOException if there is an IO error found.
*/
public DataSmResult dataShortMessage(String serviceType,
TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi,
String sourceAddr, TypeOfNumber destAddrTon,
NumberingPlanIndicator destAddrNpi, String destinationAddr,
ESMClass esmClass, RegisteredDelivery registeredDelivery,
DataCoding dataCoding, OptionalParameter... optionalParameters)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
DataSmCommandTask task = new DataSmCommandTask(pduSender,
serviceType, sourceAddrTon, sourceAddrNpi, sourceAddr,
destAddrTon, destAddrNpi, destinationAddr, esmClass,
registeredDelivery, dataCoding, optionalParameters);
DataSmResp resp = (DataSmResp)executeSendCommand(task, getTransactionTimer());
return new DataSmResult(resp.getMessageId(), resp.getOptionalParameters());
}
public void close() {
sessionContext().close();
try {
connection().close();
} catch (IOException e) {
}
}
/**
* Validate the response, the command_status should be 0 otherwise will
* throw {@link NegativeResponseException}.
*
* @param response is the response.
* @throws NegativeResponseException if the command_status value is not zero.
*/
private static void validateResponse(Command response) throws NegativeResponseException {
if (response.getCommandStatus() != SMPPConstant.STAT_ESME_ROK) {
throw new NegativeResponseException(response.getCommandStatus());
}
}
protected DataSmResult fireAcceptDataSm(DataSm dataSm) throws ProcessRequestException {
GenericMessageReceiverListener messageReceiverListener = messageReceiverListener();
if (messageReceiverListener != null) {
return messageReceiverListener.onAcceptDataSm(dataSm);
} else {
throw new ProcessRequestException("MessageReceveiverListener hasn't been set yet", SMPPConstant.STAT_ESME_RX_R_APPN);
}
}
/**
* Execute send command command task.
*
* @param task is the task.
* @param timeout is the timeout in millisecond.
* @return the command response.
* @throws PDUStringException if there is invalid PDU String found.
* @throws ResponseTimeoutException if the response has reach it timeout.
* @throws InvalidResponseException if invalid response found.
* @throws NegativeResponseException if the negative response found.
* @throws IOException if there is an IO error found.
*/
protected Command executeSendCommand(SendCommandTask task, long timeout)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<Command> pendingResp = new PendingResponse<Command>(timeout);
pendingResponse.put(seqNum, pendingResp);
try {
task.executeTask(connection().getOutputStream(), seqNum);
} catch (IOException e) {
logger.error("Failed sending " + task.getCommandName() + " command", e);
pendingResponse.remove(seqNum);
close();
throw e;
}
try {
pendingResp.waitDone();
logger.debug(task.getCommandName() + " response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw new ResponseTimeoutException("No response after waiting for "
+ timeout + " millis when executing "
+ task.getCommandName() + " with sessionId " + sessionId
+ " and sequenceNumber " + seqNum, e);
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
Command resp = pendingResp.getResponse();
validateResponse(resp);
return resp;
}
private synchronized static final String generateSessionId() {
return IntUtil.toHexString(random.nextInt());
}
/**
* Ensure we have proper link.
*
* @throws ResponseTimeoutException if there is no valid response after defined millisecond.
* @throws InvalidResponseException if there is invalid response found.
* @throws IOException if there is an IO error found.
*/
protected void sendEnquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException {
EnquireLinkCommandTask task = new EnquireLinkCommandTask(pduSender);
try {
executeSendCommand(task, getTransactionTimer());
} catch (PDUStringException e) {
// should never happen, since it doesn't have any String parameter.
logger.warn("PDU String should be always valid", e);
} catch (NegativeResponseException e) {
// the command_status of the response should be always 0
logger.warn("command_status of response should be always 0", e);
}
}
private void unbind() throws ResponseTimeoutException,
InvalidResponseException, IOException {
UnbindCommandTask task = new UnbindCommandTask(pduSender);
try {
executeSendCommand(task, transactionTimer);
} catch (PDUStringException e) {
// exception should be never caught since we didn't send any string parameter.
logger.warn("PDU String should be always valid", e);
} catch (NegativeResponseException e) {
// ignore the negative response
logger.warn("Receive non-ok command_status (" + e.getCommandStatus() + ") for unbind_resp");
}
}
public void unbindAndClose() {
try {
unbind();
} catch (ResponseTimeoutException e) {
logger.error("Timeout waiting unbind response", e);
} catch (InvalidResponseException e) {
logger.error("Receive invalid unbind response", e);
} catch (IOException e) {
logger.error("IO error found ", e);
}
close();
}
} |
package org.ligi.axt.extensions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class InputStreamAXT {
private static final int CHARACTER_READ_BUFFER_SIZE = 1024;
private final InputStream inputStream;
public InputStreamAXT(InputStream inputStream) {
this.inputStream = inputStream;
}
public void toFile(File f) throws IOException {
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
public String readToString() throws IOException {
InputStreamReader is = new InputStreamReader(inputStream);
try {
return readFromInputStreamReaderToString(is);
} finally {
is.close();
}
}
private String readFromInputStreamReaderToString(InputStreamReader is) throws IOException {
BufferedReader reader = new BufferedReader(is, CHARACTER_READ_BUFFER_SIZE);
try {
char[] buffer = new char[CHARACTER_READ_BUFFER_SIZE];
StringBuilder sb = new StringBuilder();
int len;
while ((len = reader.read(buffer)) >= 0) {
sb.append(buffer, 0, len);
}
return sb.toString();
} finally {
reader.close();
}
}
} |
package com.lotsofun.farkle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.prefs.Preferences;
/**
* The Game class serves as the Model for the Farkle application. This class is responsible for tracking
* each player, setting high scores, storing the game mode, calculating all scoring, and determining
* game outcomes.
* @author Brant Mullinix
* @version 3.0.0
*/
public class Game {
/** Stores the high score */
private Preferences prefs;
/** Tracks the current player during the game */
private int currentPlayer = 1;
/** Stores the game mode (single player or two player) */
private GameMode gameMode;
/** References to the players in a game */
private Player[] players = new Player[2];
/** Reference to the controller for the game */
private FarkleController controller;
/** Used to determine if a player is given a bonus turn */
private boolean bonusTurn = false;
/**
* Constructor: Creates a new Game object, passes the GameMode and a
* reference to the controller, and retrieves and sets the high score
*
* @param gMode The selected game mode for the game
* @param controller The controller for the game that links the model to
* the view
*/
public Game(GameMode gMode, FarkleController controller) {
// Define the preferences file
prefs = Preferences.userRoot().node(this.getClass().getName());
// Set the game mode and controller fields
this.gameMode = gMode;
this.controller = controller;
// Player 1 is instantiated regardless of the game mode
players[0] = new Player(1);
// If the game mode is set to two player, instantiate player 2.
if (gameMode == GameMode.MULTIPLAYER) {
players[1] = new Player(2);
}
// Set the high score label
controller.setUIHighScore(getHighScore());
// Initialize the turns
resetGame();
}
/**
* Calculate the score of a list of integers representing a roll of dice per the
* rules of this version of Farkle. This method calculates the scores in accordance
* with the following requirements: <br /><br />
* 6.1.0: Each 1 rolled is worth 100 points<br />
* 6.2.0: Each 5 rolled is worth 50 points<br />
* 6.3.0: Three 1's are worth 1000 points<br />
* 6.4.0: Three of a kind of any value other than 1 is worth 100 times the value
* of the die (e.g. three 4's is worth 400 points).<br />
* 6.4.5: Four, five, or six of a kind is scored by doubling the three of a kind
* value for every additional matching die (e.g. five 3's would be scored as
* 300 X 2 X 2 = 1200.<br />
* 6.6.0: Three distinct doubles (e.g. 1-1-2-2-3-3) are worth 750 points. This
* scoring rule does not include the condition of rolling four of a kind along with
* a pair (e.g. 2-2-2-2-3-3 does not satisfy the three distinct doubles scoring rule).
* <br />
* 6.7.0: A straight (e.g. 1-2-3-4-5-6), which can only be achieved when all 6 dice
* are rolled, is worth 1500 points.
*
* @param roll A List of Integers representing the roll of dice for which the
* Farkle score will be calculated.
* @param checkHeldDice A flag that is set to true when the calculated score
* should be zero if any of the dice do not contribute to the score
* @return int - The calculated score for the list of dice
*/
public int calculateScore(List<Integer> roll, boolean checkHeldDice) {
// Initialize the calculated score and set it to 0
Integer calculatedScore;
// If roll is not null, continue calculating the score
if (roll != null) {
// Set calculatedScore to 0
calculatedScore = 0;
// Calculate the roll score if roll is not empty
if (!roll.isEmpty()) {
// Test to ensure all values are within the range of 1 to 6 (inclusive)
boolean incorrectValuePresent = false;
for (Integer value : roll) {
if (!((value == 1) || (value == 2) || (value == 3)
|| (value == 4) || (value == 5) || (value == 6))) {
incorrectValuePresent = true;
}
}
/* If all values are within the accepted range of 1 to 6 (inclusive)
* calculate the score
*/
if (!incorrectValuePresent) {
// Flag to check for one or two dice
boolean oneOrTwoStrictDie = false;
// Determine the number of dice held
int numberOfDieHeld = 0;
numberOfDieHeld = roll.size();
// Flag to check for a straight
boolean isStraight = true;
// Flags to check for three pair
boolean isThreePair = true;
int countOfPairs = 0;
/* This array stores the count of each die in the roll.
* Index 0 represents a die with value 1, etc.
*/
int[] countedDie = new int[6];
/* Determine the value of each die in the roll and add to
* the total count for each die value in countedDie
*/
for (int value : roll) {
/* decrement value to get the proper die index and
* increment the count for that value of die
*/
countedDie[--value]++;
}
/* Calculate the score for the list of dice by looping
* through the dice count for each value of die
*/
for (int i = 0; i < countedDie.length; i++) {
// Get the count for the current die value
Integer currentCount = countedDie[i];
// If the die is 2, 3, 4, or 6 (aka strict dice)
if (i >= 1 && i != 4)
{
// If the die appears 1 or 2 times set the flag to true
if ((currentCount == 1) || (currentCount == 2))
{
oneOrTwoStrictDie = true;
}
}
/* If the current count does not equal one, it can be
* deduced that this roll does not include a straight.
*/
if (currentCount != 1)
isStraight = false;
/* If the current count does not equal 2 and does not equal 0,
* it can be deduced that this roll does not include three pair
*/
if (currentCount != 2 && currentCount != 0)
isThreePair = false;
// Keep track of the total number of pairs
if (currentCount == 2) {
countOfPairs++;
}
// Temporary variable used for power calculations
Double temp;
// Add to the score based on the current die value
switch (i) {
/* If the current die value is 1 (index 0), add 100 to the score
* for every 1. If there are three or more, add 1000 * 2 ^ (count - 3)
*/
case 0:
if (currentCount > 0 && currentCount < 3) {
calculatedScore = calculatedScore
+ currentCount * 100;
} else if (currentCount >= 3) {
temp = (Math.pow(2, (currentCount - 3)));
calculatedScore = calculatedScore + 1000
* temp.intValue();
}
break;
/* If the current die value is 5 (index 4), add 50 to the score
* for every 5. If there are three or more, add 500 * 2 ^ (count - 3)
*/
case 4:
if (currentCount > 0 && currentCount < 3) {
calculatedScore += currentCount * 50;
} else if (currentCount >= 3) {
temp = Math.pow(2, (currentCount - 3));
calculatedScore = calculatedScore + 500
* temp.intValue();
}
break;
// The die value is 2, 3, 4, or 6.
default:
/* If the count of the current die is greater than 3,
* add the current die value * 100 * 2 ^ (count - 3)
*/
if (currentCount >= 3) {
temp = Math.pow(2, (currentCount - 3));
calculatedScore += (i + 1) * 100
* temp.intValue();
}
/* Else if the is straight flag is true, and the die
* value is 6 (index 5) and 6 dice were rolled, it is
* confirmed that a straight was rolled, set the
* calculated score to 1500
*/
else if (isStraight == true && i == 5
&& roll.size() == 6) {
calculatedScore = 1500;
}
/* Else if the is three pair flag is true, and the die
* value is 6 (index 5) and 6 dice were rolled, it is
* confirmed that 3 pairs was rolled, set the calculated
* score to 750
*/
else if (isThreePair == true && i == 5
&& roll.size() == 6) {
calculatedScore = 750;
}
}
}
/* If the checkHeldDice flag is true, we need to return 0 if any
* of the dice do not contribute to the score.
*/
if (checkHeldDice) {
/* if the number of counted pairs is less than 3, set the
* isThreePair flag to false.
*/
if (countOfPairs != 3)
{
isThreePair = false;
}
/* If a 2, 3, 4, or 6 occurs once or twice and the roll does
* not contain 3 pair or a straight, set calculatedScore to 0
*/
if (oneOrTwoStrictDie && !isStraight && !isThreePair)
{
calculatedScore = 0;
}
// If no dice are held, set calculatedScpre to 0.
if (numberOfDieHeld == 0) {
calculatedScore = 0;
}
}
/* Else, at least one die value was outside of the accepted range, set
* calculatedScore to 0
*/
} else {
calculatedScore = 0;
}
}
// The list of integers representing the roll was null. set calculatedScore to 0
} else {
calculatedScore = 0;
}
// Return the calculated score
return calculatedScore;
}
/**
* Calculate the highest possible score for a given roll of the dice, and details the
* dice that must be selected to achieve that score.
* @param dice The list of integers representing the roll of dice
* @return Object[] array - the first index holds the calculated highest possible
* score for a given roll, and the second index is a list of dice that must be selected
* to achieve that score.
*/
public Object[] calculateHighestScore(List<Integer> dice) {
// The calculated highest score
int highestScorePossible = 0;
// The Object[] array that will be returned
Object[] highestScore = new Object[2];
// The list of dice that must be selected to produce the highest score
List<Integer> highestScoringCombination = new ArrayList<Integer>();
/* If the dice list is not empty or null, calculate the score for all
* permutations of selected dice, and determine that which results in
* the highest score
*/
if ((dice != null) && dice.size() > 0) {
// Determine the number of permutations of selected dice
Integer magicNumber = (int) Math.pow(2, dice.size()) - 1;
// Calculate the score for each permutation
for (int i = 1; i <= magicNumber; i++) {
// The list of dice in this permutation
List<Integer> tempList = new ArrayList<Integer>();
// Compute the binary number for this permutation
char[] binaryNumber = new char[dice.size()];
Arrays.fill(binaryNumber, '0');
char[] ch = Integer.toBinaryString(i).toCharArray();
for (int c = 0; c < ch.length; c++) {
binaryNumber[(ch.length) - (c + 1)] = ch[c];
}
// Add the appropriate die from the roll for each 1 in binaryNumber
for (int j = 0; j < binaryNumber.length; j++) {
if (binaryNumber[j] == '1') {
tempList.add(dice.get(j));
}
}
// Calculate the score for this permutation
int tempScore = calculateScore(tempList, false);
// Compare tempScore to the previously set highest calculated score
if (tempScore > highestScorePossible) {
highestScorePossible = tempScore;
highestScoringCombination.clear();
highestScoringCombination = tempList;
}
}
}
/* Add the highest calculated score and that scores combination to the
* highest score array, and return it
*/
highestScore[0] = highestScorePossible;
highestScore[1] = highestScoringCombination;
return highestScore;
}
/**
* Set this turn's score to 0 and end the current player's turn
*/
public void farkle() {
// Set the turn score to 0 for the current player
controller.setTurnScore(currentPlayer, getTurnNumberForCurrentPlayer(),
0);
// End the current player's turn
getCurrentPlayer().endTurn(true);
// Get the next player
currentPlayer = getNextPlayer();
// Set the next player's roll score to 0
processHold(0);
}
/**
* Set this turn's score to the total of all rolls and end the current
* player's turn.
* @return int - Game score for the current player when this method was called
*/
public int bank() {
// The game score for the current player
int retVal = 0;
// Set the turn score for the current player in the controller
controller.setTurnScore(currentPlayer, getTurnNumberForCurrentPlayer(),
getRollScores());
// End the current player's turn
getCurrentPlayer().endTurn(false);
// Retrieve the game score for the current player
retVal = getCurrentPlayer().getGameScore();
// Set the new current player
currentPlayer = getNextPlayer();
// Return the game score
return retVal;
}
/**
* Get the integer index of the next player in the players array
*
* @return int - index of the next player
*/
public int getNextPlayer() {
/* If gameMode is Multiplayer, return the index of the player that is
* not current
*/
if (gameMode == GameMode.MULTIPLAYER) {
return (currentPlayer == 1) ? 2 : 1;
} else {
// gameMode is Singleplayer return the index for player 1
return 1;
}
}
/**
* Add the provided score to the map of roll scores for the current turn
*
* @param score - The roll score to add
*/
public void processHold(int score) {
Player player = getCurrentPlayer();
player.scoreRoll(score);
}
/**
* Increment the current roll number of the current player
*/
public void processRoll() {
getCurrentPlayer()
.setRollNumber(getCurrentPlayer().getRollNumber() + 1);
}
/**
* Get the total score of all the rolls for this turn
*
* @return int the total score of all rolls for this turn
*/
public int getRollScores() {
return getCurrentPlayer().getRollScores();
}
/**
* Get the current player
* @return the current player
*/
public Player getCurrentPlayer() {
return players[currentPlayer - 1];
}
/**
* Set the current player
* @param currentPlayer The index of the player to set as current (1 or 2)
*/
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
/**
* Get the game mode of the current game
* @return GameMode.SINGLEPLAYER or GameMode.MULTIPLAYER
*/
public GameMode getGameMode() {
return gameMode;
}
/**
* Get the array of players for the current game
* @return Player[] array of players for the current game
*/
public Player[] getPlayers() {
return players;
}
/**
* Get the high score
* @return int high score saved in Preferences
*/
public int getHighScore() {
return prefs.getInt("HighScore", 0);
}
/**
* Set the high score and save it in preferences
* @param highScore integer to save as the high score in preferences
*/
public void setHighScore(int highScore) {
prefs.putInt("HighScore", highScore);
}
/**
* Reset the stored high score to 0.
*/
public void resetHighScore() {
prefs.putInt("HighScore", 0);
}
/**
* Set all the turn scores, roll scores, and game scores for all players in the
* Game object to 0, and set the first player as the current player
*/
public void resetGame() {
// For each player, reset the roll scores, turn scores, and game scores
for (Player player : players) {
if (null != player) {
player.setTurnNumber(1);
player.resetTurnScores();
player.resetRollScores();
player.setGameScore(0);
player.setRollNumber(0);
}
}
// Set player 1 as the current player
this.setCurrentPlayer(1);
}
/**
* Set the name of a chosen player
*
* @param playerNumber Player's position - NOT AN INDEX (1 or 2)
* @param name The string used to set the player's name
*/
public void setPlayerName(int playerNumber, String name) {
if (null != name && playerNumber >= 1 && playerNumber <= 2) {
this.players[playerNumber - 1].setPlayerName(name);
}
}
/**
* Get the turn number for the current player
* @return int - Turn number for the current player
*/
public int getTurnNumberForCurrentPlayer() {
return this.getCurrentPlayer().getTurnNumber();
}
/**
* Get the game score for the current player
* @return int - Total game score for the current player
*/
public int getGameScoreForCurrentPlayer() {
return this.getCurrentPlayer().getGameScore();
}
/**
* Get the player number for the current player
* @return int - Player number for the current player
*/
public int getPlayerNumberForCurrentPlayer() {
return this.getCurrentPlayer().getPlayerNumber();
}
/**
* Get the game score for a chosen player
* @param playerNumber The player for which the game score is sought
* @return int - Total game score for the chosen player
*/
public int getGameScoreForPlayer(int playerNumber) {
return players[playerNumber - 1].getGameScore();
}
/**
* Get the name of a chosen player
* @param playerNumber The player for which the name is sought
* @return String - The name of the chosen player
*/
public String getPlayerName(int playerNumber) {
return players[playerNumber - 1].getPlayerName();
}
/**
* Get the player type for the current player
* @return The player type for the current player (PlayerType.USER or PlayerType.COMPUTER)
*/
public PlayerType getPlayerTypeForCurrentPlayer() {
return this.getCurrentPlayer().getType();
}
/**
* Set the player type for a chosen player
* @param playerNumber The player for which the type is to be set
* @param playerType The type to set the chose player to (PlayerType.USER or PlayerType.COMPUTER)
*/
public void setPlayerType(int playerNumber, PlayerType playerType) {
players[playerNumber - 1].setType(playerType);
}
/**
* Get the bonusTurn flag
*
* @return boolean - True if the current turn is a bonus turn, false otherwise
*/
public boolean isBonusTurn() {
return bonusTurn;
}
/**
* Set the bonustTurn flag
* @param isBonusTurn - True if the current turn is a bonus turn, false otherwise
*/
public void setBonusTurn(boolean isBonusTurn) {
this.bonusTurn = isBonusTurn;
}
/**
* Gets a String array with the winning player's name and score. Array will
* be of length 3 should there be a tie: player1, player2, score
*
* @return String[] array with the winning player's information
*/
public String[] getWinningPlayerInfo() {
// If this is sinle player mode, return the player's name and game score
if (this.gameMode != GameMode.MULTIPLAYER) {
return new String[] { getPlayerName(1),
"" + getGameScoreForPlayer(1) };
// Else determine the winner and return that player's name and score
} else {
// Get the score for each player
int player1Score = getGameScoreForPlayer(1);
int player2Score = getGameScoreForPlayer(2);
// If player 1 wins, return player 1's name and score
if (player1Score > player2Score) {
return new String[] { getPlayerName(1),
"" + getGameScoreForPlayer(1) };
// Else if player 2 wins, return player 2's name and score
} else if (player1Score < player2Score) {
return new String[] { getPlayerName(2),
"" + getGameScoreForPlayer(2) };
// Else there was a tie, return both players' names and the score
} else {
return new String[] { getPlayerName(1), getPlayerName(2),
"" + getGameScoreForPlayer(1) };
}
}
}
} |
package ru.job4j.tree;
import java.util.*;
public class Tree<E extends Comparable<E>> implements SimpleTree<E> {
private Node<E> root;
private int size;
public Tree() {
}
public Tree(E value) {
this.root = new Node<>(value);
}
public boolean isBinary() {
boolean rsl = true;
Queue<Node<E>> data = new LinkedList<>();
data.offer(this.root);
while (!data.isEmpty()) {
Node<E> el = data.poll();
if (el.leaves().size() > 2) {
rsl = false;
break;
}
for (Node<E> child : el.leaves()) {
data.offer(child);
}
}
return rsl;
}
@Override
public Optional<Node<E>> findBy(E value) {
Optional<Node<E>> rsl = Optional.empty();
Queue<Node<E>> data = new LinkedList<>();
data.offer(this.root);
while (!data.isEmpty()) {
Node<E> el = data.poll();
if (el.eqValue(value)) {
rsl = Optional.of(el);
break;
}
for (Node<E> child : el.leaves()) {
data.offer(child);
}
}
return rsl;
}
@Override
public boolean add(E parent, E child) {
Optional<Node<E>> aParent = findBy(parent);
Optional<Node<E>> aChild = findBy(child);
if (!aChild.isPresent() && aParent.isPresent()) {
if (aParent.get().leaves().add(new Node<>(child))) {
size++;
return true;
}
}
return false;
}
public void add(E e) {
Node<E> node = new Node<>(e);
if (root == null) {
root = node;
} else {
Node<E> current = root;
Node<E> parrent;
while (true) {
parrent = current;
if (e.compareTo(current.getValue()) < 0) {
current = current.getLeft();
if (current == null) {
parrent.setLeft(node);
size++;
return;
}
} else {
current = current.getRight();
if (current == null) {
parrent.setRight(node);
size++;
return;
}
}
}
}
}
private Node<E> current;
@Override
public Iterator<E> iterator() {
Deque<Node<E>> stack = new LinkedList<>();
current = root;
while (current.getLeft() != null) {
stack.push(current);
current = current.getLeft();
}
return new Iterator<E>() {
private E tmp;
private int count = size;
@Override
public boolean hasNext() {
return count != 0;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (current.getRight() != null) {
current = current.getRight();
while (current.getLeft() != null) {
stack.push(current);
current = current.getLeft();
}
} else {
if (tmp == null) {
tmp = current.getValue();
return tmp;
}
current = stack.pop();
}
count
return current.getValue();
}
};
}
} |
package c5db.discovery;
import c5db.C5ServerConstants;
import c5db.codec.UdpProtostuffDecoder;
import c5db.codec.UdpProtostuffEncoder;
import c5db.discovery.generated.Availability;
import c5db.discovery.generated.ModuleDescriptor;
import c5db.interfaces.C5Server;
import c5db.interfaces.DiscoveryModule;
import c5db.interfaces.discovery.NewNodeVisible;
import c5db.interfaces.discovery.NodeInfo;
import c5db.interfaces.discovery.NodeInfoReply;
import c5db.interfaces.discovery.NodeInfoRequest;
import c5db.interfaces.server.ModuleStateChange;
import c5db.messages.generated.ModuleType;
import c5db.util.FiberOnly;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.AbstractService;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.jetlang.channels.MemoryChannel;
import org.jetlang.channels.MemoryRequestChannel;
import org.jetlang.channels.Request;
import org.jetlang.channels.RequestChannel;
import org.jetlang.fibers.Fiber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Uses broadcast UDP packets to discover 'adjacent' nodes in the cluster. Maintains
* a state table for them, and provides information to other modules as they request it.
* <p/>
* Currently UDP broadcast has some issues on Mac OSX vs Linux. The big question,
* specifically, is what happens when multiple processes bind to 255.255.255.255:PORT
* and send packets? Which processes receive such packets?
* <ul>
* <li>On Mac OSX 10.8/9, all processes reliably receive all packets including
* the originating process</li>
* <li>On Linux (Ubuntu, modern) a variety of things appear to occur:
* <ul>
* <li>First to bind receives all packets</li>
* <li>All processes receives all packets</li>
* <li>No one receives any packets</li>
* <li>Please fill this doc in!</li>
* </ul></li>
* </ul>
* <p/>
* The beacon service needs to be refactored and different discovery methods need to be
* pluggable but all behind the discovery module interface.
*/
public class BeaconService extends AbstractService implements DiscoveryModule {
private static final Logger LOG = LoggerFactory.getLogger(BeaconService.class);
@Override
public ModuleType getModuleType() {
return ModuleType.Discovery;
}
@Override
public boolean hasPort() {
return true;
}
@Override
public int port() {
return discoveryPort;
}
@Override
public String acceptCommand(String commandString) {
return null;
}
private final RequestChannel<NodeInfoRequest, NodeInfoReply> nodeInfoRequests = new MemoryRequestChannel<>();
@Override
public RequestChannel<NodeInfoRequest, NodeInfoReply> getNodeInfo() {
return nodeInfoRequests;
}
@Override
public ListenableFuture<NodeInfoReply> getNodeInfo(long nodeId, ModuleType module) {
SettableFuture<NodeInfoReply> future = SettableFuture.create();
fiber.execute(() -> {
NodeInfo peer = peers.get(nodeId);
if (peer == null) {
future.set(NodeInfoReply.NO_REPLY);
} else {
Integer servicePort = peer.modules.get(module);
if (servicePort == null) {
future.set(NodeInfoReply.NO_REPLY);
} else {
List<String> peerAddresses = peer.availability.getAddressesList();
future.set(new NodeInfoReply(true, peerAddresses, servicePort));
}
}
});
return future;
}
@FiberOnly
private void handleNodeInfoRequest(Request<NodeInfoRequest, NodeInfoReply> message) {
NodeInfoRequest req = message.getRequest();
NodeInfo peer = peers.get(req.nodeId);
if (peer == null) {
message.reply(NodeInfoReply.NO_REPLY);
return;
}
Integer servicePort = peer.modules.get(req.moduleType);
if (servicePort == null) {
message.reply(NodeInfoReply.NO_REPLY);
return;
}
List<String> peerAddresses = peer.availability.getAddressesList();
// does this module run on that peer?
message.reply(new NodeInfoReply(true, peerAddresses, servicePort));
}
@Override
public String toString() {
return "BeaconService{" +
"discoveryPort=" + discoveryPort +
", nodeId=" + nodeId +
'}';
}
// For main system modules/pubsub stuff.
private final C5Server c5Server;
private final long nodeId;
private final int discoveryPort;
private final EventLoopGroup eventLoop;
private final Map<ModuleType, Integer> moduleInfo = new HashMap<>();
private final Map<Long, NodeInfo> peers = new HashMap<>();
private final org.jetlang.channels.Channel<Availability> incomingMessages = new MemoryChannel<>();
private final org.jetlang.channels.Channel<NewNodeVisible> newNodeVisibleChannel = new MemoryChannel<>();
private final Fiber fiber;
// These should be final, but they are initialized in doStart().
private Channel broadcastChannel = null;
private InetSocketAddress sendAddress = null;
private Bootstrap bootstrap = null;
private List<String> localIPs;
private class BeaconMessageHandler extends SimpleChannelInboundHandler<Availability> {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception, ignoring datagram", cause);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Availability msg) throws Exception {
incomingMessages.publish(msg);
}
}
/**
* @param nodeId the id of this node.
* @param discoveryPort the port to send discovery beacons on and to listen to
*/
public BeaconService(long nodeId,
int discoveryPort,
final Fiber fiber,
EventLoopGroup eventLoop,
Map<ModuleType, Integer> modules,
C5Server theC5Server
) {
this.discoveryPort = discoveryPort;
this.nodeId = nodeId;
this.fiber = fiber;
moduleInfo.putAll(modules);
this.c5Server = theC5Server;
this.eventLoop = eventLoop;
c5Server.getModuleStateChangeChannel().subscribe(fiber, this::serviceChange);
}
@Override
public ListenableFuture<ImmutableMap<Long, NodeInfo>> getState() {
final SettableFuture<ImmutableMap<Long, NodeInfo>> future = SettableFuture.create();
fiber.execute(() -> {
future.set(getCopyOfState());
});
return future;
}
@Override
public org.jetlang.channels.Channel<NewNodeVisible> getNewNodeNotifications() {
return newNodeVisibleChannel;
}
private ImmutableMap<Long, NodeInfo> getCopyOfState() {
return ImmutableMap.copyOf(peers);
}
@FiberOnly
private void sendBeacon() {
if (broadcastChannel == null) {
LOG.debug("Channel not available yet, deferring beacon send");
return;
}
LOG.trace("Sending beacon broadcast message to {}", sendAddress);
List<ModuleDescriptor> msgModules = new ArrayList<>(moduleInfo.size());
for (ModuleType moduleType : moduleInfo.keySet()) {
msgModules.add(
new ModuleDescriptor(moduleType,
moduleInfo.get(moduleType))
);
}
Availability beaconMessage = new Availability(nodeId, 0, localIPs, msgModules);
broadcastChannel.writeAndFlush(new
UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, beaconMessage));
// Fix issue #76, feed back the beacon Message to our own database:
processWireMessage(beaconMessage);
}
@FiberOnly
private void processWireMessage(Availability message) {
LOG.trace("Got incoming message {}", message);
if (message.getNodeId() == 0) {
// if (!message.hasNodeId()) {
LOG.error("Incoming availability message does not have node id, ignoring!");
return;
}
// Always just overwrite what was already there for now.
// TODO consider a more sophisticated merge strategy?
NodeInfo nodeInfo = new NodeInfo(message);
if (!peers.containsKey(message.getNodeId())) {
getNewNodeNotifications().publish(new NewNodeVisible(message.getNodeId(), nodeInfo));
}
peers.put(message.getNodeId(), nodeInfo);
}
@FiberOnly
private void serviceChange(ModuleStateChange message) {
if (message.state == State.RUNNING) {
LOG.debug("BeaconService adding running module {} on port {}",
message.module.getModuleType(),
message.module.port());
moduleInfo.put(message.module.getModuleType(), message.module.port());
} else if (message.state == State.STOPPING || message.state == State.FAILED || message.state == State.TERMINATED) {
LOG.debug("BeaconService removed module {} on port {} with state {}",
message.module.getModuleType(),
message.module.port(),
message.state);
moduleInfo.remove(message.module.getModuleType());
} else {
LOG.debug("BeaconService got unknown state module change {}", message);
}
}
@Override
protected void doStart() {
eventLoop.next().execute(() -> {
bootstrap = new Bootstrap();
bootstrap.group(eventLoop)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<DatagramChannel>() {
@Override
protected void initChannel(DatagramChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("protobufDecoder",
new UdpProtostuffDecoder<>(Availability.getSchema(), false));
p.addLast("protobufEncoder",
new UdpProtostuffEncoder<>(Availability.getSchema(), false));
p.addLast("beaconMessageHandler", new BeaconMessageHandler());
}
});
// Wait, this is why we are in a new executor...
//noinspection RedundantCast
bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> {
broadcastChannel = future.channel();
});
if (c5Server.isSingleNodeMode()) {
sendAddress = new InetSocketAddress(C5ServerConstants.LOOPBACK_ADDRESS, discoveryPort);
} else {
sendAddress = new InetSocketAddress(C5ServerConstants.BROADCAST_ADDRESS, discoveryPort);
}
try {
localIPs = getLocalIPs();
} catch (SocketException e) {
LOG.error("SocketException:", e);
notifyFailed(e);
}
// Schedule fiber tasks and subscriptions.
incomingMessages.subscribe(fiber, this::processWireMessage);
nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest);
fiber.scheduleAtFixedRate(this::sendBeacon, 2, 10, TimeUnit.SECONDS);
fiber.start();
notifyStarted();
});
}
@Override
protected void doStop() {
eventLoop.next().execute(() -> {
fiber.dispose();
notifyStopped();
});
}
private List<String> getLocalIPs() throws SocketException {
List<String> ips = new LinkedList<>();
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isPointToPoint()) {
continue; //ignore tunnel type interfaces
}
for (Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); addrs.hasMoreElements(); ) {
InetAddress addr = addrs.nextElement();
if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isAnyLocalAddress()) {
continue;
}
ips.add(addr.getHostAddress());
}
}
return ips;
}
} |
package ch.elexis.data;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
private static final String BUNDLE_NAME = "ch.elexis.data.messages";//$NON-NLS-1$
private Messages(){
// Do not instantiate
}
public static String BezugsKontakt_ContactDoesntExist;
public static String Contact_SalutationF;
public static String Contact_SalutationM;
public static String Fall_Accident;
public static String Fall_Birthdefect;
public static String Fall_CaseClosedCaption;
public static String Fall_CaseClosedText;
public static String Fall_CLOSED;
public static String Fall_Disease;
public static String Fall_IV_Name;
public static String Fall_KVG_Name;
public static String Fall_KVGRequirements;
public static String Fall_Maternity;
public static String Fall_MV_Name;
public static String Fall_NoMandatorCaption;
public static String Fall_NoMandatorText;
public static String Fall_Open;
public static String Fall_Other;
public static String Fall_Prevention;
public static String Fall_Private_Name;
public static String Fall_TarmedLeistung;
public static String Fall_TarmedPrinter;
public static String Fall_Undefined;
public static String Fall_UVG_Name;
public static String Fall_UVGRequirements;
public static String Fall_VVG_Name;
public static String GlobalActions_CantCreateKons;
public static String GlobalActions_DoSelectCase;
public static String GlobalActions_DoSelectPatient;
public static String GlobalActions_casclosed;
public static String GlobalActions_caseclosedexplanation;
public static String GlobalActions_SecondForToday;
public static String GlobalActions_SecondForTodayQuestion;
public static String LabItem_defaultGroup;
public static String LabItem_longOwnLab;
public static String LabItem_shortOwnLab;
public static String LabMapping_reasonDefinitionNotValid;
public static String LabMapping_reasonLineNotValid;
public static String LabMapping_reasonMoreContacts;
public static String LabMapping_reasonMoreLabItems;
public static String LabOrder_stateDone;
public static String LabOrder_stateImported;
public static String LabOrder_stateOrdered;
static {
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
} |
package jade.core;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Serializable;
import java.io.InterruptedIOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Vector;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.*;
import jade.domain.AgentManagementOntology;
import jade.domain.FIPAException;
/**
The <code>Agent</code> class is the common superclass for user
defined software agents. It provides methods to perform basic agent
tasks, such as:
<ul>
<li> <b> Message passing using <code>ACLMessage</code> objects,
both unicast and multicast with optional pattern matching. </b>
<li> <b> Complete Agent Platform life cycle support, including
starting, suspending and killing an agent. </b>
<li> <b> Scheduling and execution of multiple concurrent activities. </b>
<li> <b> Simplified interaction with <em>FIPA</em> system agents
for automating common agent tasks (DF registration, etc.). </b>
</ul>
Application programmers must write their own agents as
<code>Agent</code> subclasses, adding specific behaviours as needed
and exploiting <code>Agent</code> class capabilities.
@author Giovanni Rimassa - Universita` di Parma
@version $Date$ $Revision$
*/
public class Agent implements Runnable, Serializable, CommBroadcaster {
// This inner class is used to force agent termination when a signal
// from the outside is received
private class AgentDeathError extends Error {
AgentDeathError() {
super("Agent " + Thread.currentThread().getName() + " has been terminated.");
}
}
// This class manages bidirectional associations between Timer and
// Behaviour objects, using hash tables. This class is fully
// synchronized because is accessed both by agent internal thread
// and high priority Timer Dispatcher thread.
private static class AssociationTB {
private Map BtoT = new HashMap();
private Map TtoB = new HashMap();
public synchronized void addPair(Behaviour b, Timer t) {
BtoT.put(b, t);
TtoB.put(t, b);
}
public synchronized void removeMapping(Behaviour b) {
Timer t = (Timer)BtoT.remove(b);
if(t != null) {
TtoB.remove(t);
}
}
public synchronized void removeMapping(Timer t) {
Behaviour b = (Behaviour)TtoB.remove(t);
if(b != null) {
BtoT.remove(b);
}
}
public synchronized Timer getPeer(Behaviour b) {
return (Timer)BtoT.get(b);
}
public synchronized Behaviour getPeer(Timer t) {
return (Behaviour)TtoB.get(t);
}
}
private static TimerDispatcher theDispatcher;
static void setDispatcher(TimerDispatcher td) {
if(theDispatcher == null) {
theDispatcher = td;
theDispatcher.start();
}
}
static void stopDispatcher() {
theDispatcher.stop();
}
/**
Schedules a restart for a behaviour, after a certain amount of
time has passed.
@param b The behaviour to restart later.
@param millis The amount of time to wait before restarting
<code>b</code>.
@see jade.core.behaviours.Behaviour#block(long millis)
*/
public void restartLater(Behaviour b, long millis) {
if(millis == 0)
return;
Timer t = new Timer(System.currentTimeMillis() + millis, this);
pendingTimers.addPair(b, t);
theDispatcher.add(t);
}
// Restarts the behaviour associated with t. This method runs within
// the time-critical Timer Dispatcher thread.
void doTimeOut(Timer t) {
Behaviour b = pendingTimers.getPeer(t);
if(b != null) {
activateBehaviour(b);
}
}
/**
Notifies this agent that one of its behaviours has been restarted
for some reason. This method clears any timer associated with
behaviour object <code>b</code>, and it is unneeded by
application level code. To explicitly schedule behaviours, use
<code>block()</code> and <code>restart()</code> methods.
@param b The behaviour object which was restarted.
@see jade.core.behaviours.Behaviour#restart()
*/
public void notifyRestarted(Behaviour b) {
Timer t = pendingTimers.getPeer(b);
if(t != null) {
pendingTimers.removeMapping(b);
theDispatcher.remove(t);
}
}
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MIN = 0; // Hand-made type checking
/**
Represents the <em>initiated</em> agent state.
*/
public static final int AP_INITIATED = 1;
/**
Represents the <em>active</em> agent state.
*/
public static final int AP_ACTIVE = 2;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int AP_SUSPENDED = 3;
/**
Represents the <em>waiting</em> agent state.
*/
public static final int AP_WAITING = 4;
/**
Represents the <em>deleted</em> agent state.
*/
public static final int AP_DELETED = 5;
/**
Represents the <code>transit</code> agent state.
*/
public static final int AP_TRANSIT = 6;
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MAX = 7; // Hand-made type checking
/**
These constants represent the various Domain Life Cycle states
*/
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MIN = 9; // Hand-made type checking
/**
Represents the <em>active</em> agent state.
*/
public static final int D_ACTIVE = 10;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int D_SUSPENDED = 20;
/**
Represents the <em>retired</em> agent state.
*/
public static final int D_RETIRED = 30;
/**
Represents the <em>unknown</em> agent state.
*/
public static final int D_UNKNOWN = 40;
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MAX = 41; // Hand-made type checking
/**
Default value for message queue size. When the number of buffered
messages exceeds this value, older messages are discarded
according to a <b><em>FIFO</em></b> replacement policy.
@see jade.core.Agent#setQueueSize(int newSize)
@see jade.core.Agent#getQueueSize()
*/
public static final int MSG_QUEUE_SIZE = 100;
private MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE);
private Vector listeners = new Vector();
private String myName = null;
private String myAddress = null;
private Object stateLock = new Object(); // Used to make state transitions atomic
private Object waitLock = new Object(); // Used for agent waiting
private Object suspendLock = new Object(); // Used for agent suspension
private Thread myThread;
private Scheduler myScheduler;
private AssociationTB pendingTimers = new AssociationTB();
/**
The <code>Behaviour</code> that is currently executing.
@see jade.core.behaviours.Behaviour
*/
protected Behaviour currentBehaviour;
/**
Last message received.
@see jade.lang.acl.ACLMessage
*/
protected ACLMessage currentMessage;
// This variable is 'volatile' because is used as a latch to signal
// agent suspension and termination from outside world.
private volatile int myAPState;
// Temporary buffer for agent suspension
private int myBufferedState = AP_MIN;
private int myDomainState;
private Vector blockedBehaviours = new Vector();
private ACLParser myParser = ACLParser.create();
/**
Default constructor.
*/
public Agent() {
myAPState = AP_INITIATED;
myDomainState = D_UNKNOWN;
myScheduler = new Scheduler(this);
}
/**
Method to query the agent local name.
@return A <code>String</code> containing the local agent name
(e.g. <em>peter</em>).
*/
public String getLocalName() {
return myName;
}
/**
Method to query the agent complete name (<em><b>GUID</b></em>).
@return A <code>String</code> containing the complete agent name
(e.g. <em>peter@iiop://fipa.org:50/acc</em>).
*/
public String getName() {
return myName + '@' + myAddress;
}
/**
Method to query the agent home address. This is the address of
the platform where the agent was created, and will never change
during the whole lifetime of the agent.
@return A <code>String</code> containing the agent home address
(e.g. <em>iiop://fipa.org:50/acc</em>).
*/
public String getAddress() {
return myAddress;
}
// This is used by the agent container to wait for agent termination
void join() {
try {
myThread.join();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
public void setQueueSize(int newSize) throws IllegalArgumentException {
msgQueue.setMaxSize(newSize);
}
/**
Reads message queue size. A zero value means that the message
queue is unbounded (its size is limited only by amount of
available memory).
@return The actual size of the message queue.
@see jade.core.Agent#setQueueSize(int newSize)
*/
public int getQueueSize() {
return msgQueue.getMaxSize();
}
/**
Read current agent state. This method can be used to query an
agent for its state from the outside.
@return the Agent Platform Life Cycle state this agent is currently in.
*/
public int getState() {
return myAPState;
}
// State transition methods for Agent Platform Life-Cycle
/**
Make a state transition from <em>initiated</em> to
<em>active</em> within Agent Platform Life Cycle. Agents are
started automatically by JADE on agent creation and should not be
used by application developers, unless creating some kind of
agent factory. This method starts the embedded thread of the agent.
@param name The local name of the agent.
*/
public void doStart(String name) {
AgentContainerImpl thisContainer = Starter.getContainer();
try {
thisContainer.createAgent(name, this, AgentContainer.START);
}
catch(java.rmi.RemoteException jrre) {
jrre.printStackTrace();
}
}
void doStart(String name, String platformAddress, ThreadGroup myGroup) {
// Set this agent's name and address and start its embedded thread
if(myAPState == AP_INITIATED) {
myAPState = AP_ACTIVE;
myName = new String(name);
myAddress = new String(platformAddress);
myThread = new Thread(myGroup, this);
myThread.setName(myName);
myThread.setPriority(myGroup.getMaxPriority());
myThread.start();
}
}
/**
Make a state transition from <em>active</em> to
<em>transit</em> within Agent Platform Life Cycle. This method
is intended to support agent mobility and is called either by the
Agent Platform or by the agent itself to start a migration process.
<em>This method is currently not implemented.</em>
*/
public void doMove() {
myAPState = AP_TRANSIT;
// FIXME: Should do something more
}
/**
Make a state transition from <em>transit</em> to <em>active</em>
within Agent Platform Life Cycle. This method is intended to
support agent mobility and is called by the destination Agent
Platform when a migration process completes and the mobile agent
is about to be restarted on its new location.
*/
public void doExecute() {
myAPState = AP_ACTIVE;
activateAllBehaviours();
}
/**
Make a state transition from <em>active</em> or <em>waiting</em>
to <em>suspended</em> within Agent Platform Life Cycle; the
original agent state is saved and will be restored by a
<code>doActivate()</code> call. This method can be called from
the Agent Platform or from the agent iself and stops all agent
activities. Incoming messages for a suspended agent are buffered
by the Agent Platform and are delivered as soon as the agent
resumes. Calling <code>doSuspend()</code> on a suspended agent
has no effect.
@see jade.core.Agent#doActivate()
*/
public void doSuspend() {
synchronized(stateLock) {
if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) {
myBufferedState = myAPState;
myAPState = AP_SUSPENDED;
}
}
if(myAPState == AP_SUSPENDED) {
if(myThread.equals(Thread.currentThread())) {
waitUntilActivate();
}
}
}
/**
Make a state transition from <em>suspended</em> to
<em>active</em> or <em>waiting</em> (whichever state the agent
was in when <code>doSuspend()</code> was called) within Agent
Platform Life Cycle. This method is called from the Agent
Platform and resumes agent execution. Calling
<code>doActivate()</code> when the agent is not suspended has no
effect.
@see jade.core.Agent#doSuspend()
*/
public void doActivate() {
synchronized(stateLock) {
if(myAPState == AP_SUSPENDED) {
myAPState = myBufferedState;
}
}
if(myAPState != AP_SUSPENDED) {
switch(myBufferedState) {
case AP_ACTIVE:
activateAllBehaviours();
synchronized(suspendLock) {
myBufferedState = AP_MIN;
suspendLock.notify();
}
break;
case AP_WAITING:
doWake();
break;
}
}
}
/**
Make a state transition from <em>active</em> to <em>waiting</em>
within Agent Platform Life Cycle. This method can be called by
the Agent Platform or by the agent itself and causes the agent to
block, stopping all its activities until some event happens. A
waiting agent wakes up as soon as a message arrives or when
<code>doWake()</code> is called. Calling <code>doWait()</code> on
a suspended or waiting agent has no effect.
@see jade.core.Agent#doWake()
*/
public void doWait() {
doWait(0);
}
/**
Make a state transition from <em>active</em> to <em>waiting</em>
within Agent Platform Life Cycle. This method adds a timeout to
the other <code>doWait()</code> version.
@param millis The timeout value, in milliseconds.
@see jade.core.Agent#doWait()
*/
public void doWait(long millis) {
synchronized(stateLock) {
if(myAPState == AP_ACTIVE)
myAPState = AP_WAITING;
}
if(myAPState == AP_WAITING) {
if(myThread.equals(Thread.currentThread())) {
waitUntilWake(millis);
}
}
}
/**
Make a state transition from <em>waiting</em> to <em>active</em>
within Agent Platform Life Cycle. This method is called from
Agent Platform and resumes agent execution. Calling
<code>doWake()</code> when an agent is not waiting has no effect.
@see jade.core.Agent#doWait()
*/
public void doWake() {
synchronized(stateLock) {
if(myAPState == AP_WAITING) {
myAPState = AP_ACTIVE;
}
}
if(myAPState == AP_ACTIVE) {
activateAllBehaviours();
synchronized(waitLock) {
waitLock.notify(); // Wakes up the embedded thread
}
}
}
// This method handles both the case when the agents decides to exit
// and the case in which someone else kills him from outside.
/**
Make a state transition from <em>active</em>, <em>suspended</em>
or <em>waiting</em> to <em>deleted</em> state within Agent
Platform Life Cycle, thereby destroying the agent. This method
can be called either from the Agent Platform or from the agent
itself. Calling <code>doDelete()</code> on an already deleted
agent has no effect.
*/
public void doDelete() {
if(myAPState != AP_DELETED) {
myAPState = AP_DELETED;
if(!myThread.equals(Thread.currentThread()))
myThread.interrupt();
}
}
/**
This method is the main body of every agent. It can handle
automatically <b>AMS</b> registration and deregistration and
provides startup and cleanup hooks for application programmers to
put their specific code into.
@see jade.core.Agent#setup()
@see jade.core.Agent#takeDown()
*/
public final void run() {
try{
registerWithAMS(null,Agent.AP_ACTIVE,null,null,null);
setup();
mainLoop();
}
catch(InterruptedException ie) {
// Do Nothing, since this is a killAgent from outside
}
catch(InterruptedIOException iioe) {
// Do nothing, since this is a killAgent from outside
}
catch(Exception e) {
System.err.println("*** Uncaught Exception for agent " + myName + " ***");
e.printStackTrace();
}
catch(AgentDeathError ade) {
// Do Nothing, since this is a killAgent from outside
}
finally {
if(myAPState == AP_DELETED) {
takeDown();
destroy();
}
else
System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!");
}
}
/**
This protected method is an empty placeholder for application
specific startup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has been already registered with the Agent Platform <b>AMS</b>
and is able to send and receive messages. However, the agent
execution model is still sequential and no behaviour scheduling
is active yet.
This method can be used for ordinary startup tasks such as
<b>DF</b> registration, but is essential to add at least a
<code>Behaviour</code> object to the agent, in order for it to be
able to do anything.
@see jade.core.Agent#addBehaviour(Behaviour b)
@see jade.core.behaviours.Behaviour
*/
protected void setup() {}
/**
This protected method is an empty placeholder for application
specific cleanup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has not deregistered itself with the Agent Platform <b>AMS</b>
and is still able to exchange messages with other
agents. However, no behaviour scheduling is active anymore and
the Agent Platform Life Cycle state is already set to
<em>deleted</em>.
This method can be used for ordinary cleanup tasks such as
<b>DF</b> deregistration, but explicit removal of all agent
behaviours is not needed.
*/
protected void takeDown() {}
/**
TO DO
*/
protected void beforeMotion() {
}
/**
TO DO
*/
protected void afterMotion() {
}
private void mainLoop() throws InterruptedException, InterruptedIOException {
while(myAPState != AP_DELETED) {
// Select the next behaviour to execute
currentBehaviour = myScheduler.schedule();
// Just do it!
currentBehaviour.action();
// Check for Agent state changes
switch(myAPState) {
case AP_WAITING:
waitUntilWake(0);
break;
case AP_SUSPENDED:
waitUntilActivate();
break;
case AP_DELETED:
return;
case AP_TRANSIT:
// Create a Migration transactional object and wait on it
return;
case AP_ACTIVE:
break;
}
// When it is needed no more, delete it from the behaviours queue
if(currentBehaviour.done()) {
myScheduler.remove(currentBehaviour);
currentBehaviour = null;
}
else if(!currentBehaviour.isRunnable()) {
// Remove blocked behaviours from scheduling queue and put it
// in blocked behaviours queue
myScheduler.remove(currentBehaviour);
blockedBehaviours.addElement(currentBehaviour);
currentBehaviour = null;
}
// Now give CPU control to other agents
Thread.yield();
}
}
private void waitUntilWake(long millis) {
synchronized(waitLock) {
long timeToWait = millis;
while(myAPState == AP_WAITING) {
try {
long startTime = System.currentTimeMillis();
waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while
long elapsedTime = System.currentTimeMillis() - startTime;
// If this was a timed wait, update time to wait; if the
// total time has passed, wake up.
if(millis != 0) {
timeToWait -= elapsedTime;
if(timeToWait <= 0)
myAPState = AP_ACTIVE;
}
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void waitUntilActivate() {
synchronized(suspendLock) {
while(myAPState == AP_SUSPENDED) {
try {
suspendLock.wait(); // Blocks on suspended state monitor
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void destroy() {
try {
deregisterWithAMS();
}
catch(FIPAException fe) {
fe.printStackTrace();
}
notifyDestruction();
}
/**
This method adds a new behaviour to the agent. This behaviour
will be executed concurrently with all the others, using a
cooperative round robin scheduling. This method is typically
called from an agent <code>setup()</code> to fire off some
initial behaviour, but can also be used to spawn new behaviours
dynamically.
@param b The new behaviour to add to the agent.
@see jade.core.Agent#setup()
@see jade.core.behaviours.Behaviour
*/
public void addBehaviour(Behaviour b) {
myScheduler.add(b);
}
/**
This method removes a given behaviour from the agent. This method
is called automatically when a top level behaviour terminates,
but can also be called from a behaviour to terminate itself or
some other behaviour.
@param b The behaviour to remove.
@see jade.core.behaviours.Behaviour
*/
public void removeBehaviour(Behaviour b) {
myScheduler.remove(b);
}
/**
Send an <b>ACL</b> message to another agent. This methods sends
a message to the agent specified in <code>:receiver</code>
message field (more than one agent can be specified as message
receiver).
@param msg An ACL message object containing the actual message to
send.
@see jade.lang.acl.ACLMessage
*/
public final void send(ACLMessage msg) {
if(msg.getSource() == null)
msg.setSource(myName);
CommEvent event = new CommEvent(this, msg);
broadcastEvent(event);
}
/**
Send an <b>ACL</b> message to the agent contained in a given
<code>AgentGroup</code>. This method allows simple message
multicast to be done. A similar result can be obtained putting
many agent names in <code>:receiver</code> message field; the
difference is that in that case every receiver agent can read all
other receivers' names, whereas this method hides multicasting to
receivers.
@param msg An ACL message object containing the actual message to
send.
@param g An agent group object holding all receivers names.
@see jade.lang.acl.ACLMessage
@see jade.core.AgentGroup
*/
public final void send(ACLMessage msg, AgentGroup g) {
if(msg.getSource() == null)
msg.setSource(myName);
CommEvent event = new CommEvent(this, msg, g);
broadcastEvent(event);
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is non-blocking and returns the first message
in the queue, if any. Therefore, polling and busy waiting is
required to wait for the next message sent using this method.
@return A new ACL message, or <code>null</code> if no message is
present.
@see jade.lang.acl.ACLMessage
*/
public final ACLMessage receive() {
synchronized(waitLock) {
if(msgQueue.isEmpty()) {
return null;
}
else {
currentMessage = msgQueue.removeFirst();
return currentMessage;
}
}
}
/**
Receives an <b>ACL</b> message matching a given template. This
method is non-blocking and returns the first matching message in
the queue, if any. Therefore, polling and busy waiting is
required to wait for a specific kind of message using this method.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, or
<code>null</code> if no such message is present.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
*/
public final ACLMessage receive(MessageTemplate pattern) {
ACLMessage msg = null;
synchronized(waitLock) {
Iterator messages = msgQueue.iterator();
while(messages.hasNext()) {
ACLMessage cursor = (ACLMessage)messages.next();
if(pattern.match(cursor)) {
msg = cursor;
msgQueue.remove(cursor);
currentMessage = cursor;
break; // Exit while loop
}
}
}
return msg;
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is blocking and suspends the whole agent until
a message is available in the queue. JADE provides a special
behaviour named <code>ReceiverBehaviour</code> to wait for a
message within a behaviour without suspending all the others and
without wasting CPU time doing busy waiting.
@return A new ACL message, blocking the agent until one is
available.
@see jade.lang.acl.ACLMessage
@see jade.core.behaviours.ReceiverBehaviour
*/
public final ACLMessage blockingReceive() {
ACLMessage msg = null;
while(msg == null) {
msg = blockingReceive(0);
}
return msg;
}
/**
Receives an <b>ACL</b> message from the agent message queue,
waiting at most a specified amount of time.
@param millis The maximum amount of time to wait for the message.
@return A new ACL message, or <code>null</code> if the specified
amount of time passes without any message reception.
*/
public final ACLMessage blockingReceive(long millis) {
ACLMessage msg = receive();
if(msg == null) {
doWait(millis);
msg = receive();
}
return msg;
}
/**
Receives an <b>ACL</b> message matching a given message
template. This method is blocking and suspends the whole agent
until a message is available in the queue. JADE provides a
special behaviour named <code>ReceiverBehaviour</code> to wait
for a specific kind of message within a behaviour without
suspending all the others and without wasting CPU time doing busy
waiting.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, blocking
until such a message is available.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
@see jade.core.behaviours.ReceiverBehaviour
*/
public final ACLMessage blockingReceive(MessageTemplate pattern) {
ACLMessage msg = null;
while(msg == null) {
msg = blockingReceive(pattern, 0);
}
return msg;
}
/**
Receives an <b>ACL</b> message matching a given message template,
waiting at most a specified time.
@param pattern A message template to match received messages
against.
@param millis The amount of time to wait for the message, in
milliseconds.
@return A new ACL message matching the given template, or
<code>null</code> if no suitable message was received within
<code>millis</code> milliseconds.
@see jade.core.Agent#blockingReceive()
*/
public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) {
ACLMessage msg = receive(pattern);
long timeToWait = millis;
while(msg == null) {
long startTime = System.currentTimeMillis();
doWait(timeToWait);
long elapsedTime = System.currentTimeMillis() - startTime;
msg = receive(pattern);
if(millis != 0) {
timeToWait -= elapsedTime;
if(timeToWait <= 0)
break;
}
}
return msg;
}
/**
Puts a received <b>ACL</b> message back into the message
queue. This method can be used from an agent behaviour when it
realizes it read a message of interest for some other
behaviour. The message is put in front of the message queue, so
it will be the first returned by a <code>receive()</code> call.
@see jade.core.Agent#receive()
*/
public final void putBack(ACLMessage msg) {
synchronized(waitLock) {
msgQueue.addFirst(msg);
}
}
/**
@deprecated Builds an ACL message from a character stream. Now
<code>ACLMessage</code> class has this capabilities itself,
through <code>fromText()</code> method.
@see jade.lang.acl.ACLMessage#fromText(Reader r)
*/
public ACLMessage parse(Reader text) {
ACLMessage msg = null;
try {
msg = myParser.parse(text);
}
catch(ParseException pe) {
pe.printStackTrace();
}
catch(TokenMgrError tme) {
tme.printStackTrace();
}
return msg;
}
private ACLMessage FipaRequestMessage(String dest, String replyString) {
ACLMessage request = new ACLMessage("request");
request.setSource(myName);
request.removeAllDests();
request.addDest(dest);
request.setLanguage("SL0");
request.setOntology("fipa-agent-management");
request.setProtocol("fipa-request");
request.setReplyWith(replyString);
return request;
}
private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException {
send(request);
ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(reply.getType().equalsIgnoreCase("agree")) {
reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(!reply.getType().equalsIgnoreCase("inform")) {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
else {
String content = reply.getContent();
return content;
}
}
else {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
}
/**
Register this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void registerWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-registration-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Authenticate this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
<em>This method is currently not implemented.</em>
*/
public void authenticateWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
// FIXME: Not implemented
}
/**
Deregister this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void deregisterWithAMS() throws FIPAException {
String replyString = myName + "-ams-deregistration-" + (new Date()).getTime();
// Get a semi-complete request message
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies the data about this agent kept by Agent Platform
<b>AMS</b>. While this task can be accomplished with regular
message passing according to <b>FIPA</b> protocols, this method
is meant to ease this common duty. Some parameters here are
optional, and <code>null</code> can safely be passed for them.
When a non null parameter is passed, it replaces the value
currently stored inside <b>AMS</b> agent.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void modifyAMSRegistration(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
This method uses Agent Platform <b>ACC</b> agent to forward an
ACL message. Calling this method is exactly the same as calling
<code>send()</code>, only slower, since the message is first sent
to the ACC using a <code>fipa-request</code> standard protocol,
and then bounced to actual destination agent.
@param msg The ACL message to send.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the ACC to indicate some error condition.
@see jade.core.Agent#send(ACLMessage msg)
*/
public void forwardWithACC(ACLMessage msg) throws FIPAException {
String replyString = myName + "-acc-forward-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("acc", replyString);
// Build an ACC action object for the request
AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction();
a.setName(AgentManagementOntology.ACCAction.FORWARD);
a.setArg(msg);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Register this agent with a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to register with.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the registration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-register-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.REGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Deregister this agent from a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to deregister from.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the deregistration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-deregister-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.DEREGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies data about this agent contained within a <b>DF</b>
agent. While this task can be accomplished with regular message
passing according to <b>FIPA</b> protocols, this method is
meant to ease this common duty.
@param dfName The GUID of the <b>DF</b> agent holding the data
to be changed.
@param dfd A <code>DFAgentDescriptor</code> object containing all
new data values; every non null slot value replaces the
corresponding value held inside the <b>DF</b> agent.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.MODIFY);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Searches for data contained within a <b>DF</b> agent. While
this task can be accomplished with regular message passing
according to <b>FIPA</b> protocols, this method is meant to
ease this common duty. Nevertheless, a complete, powerful search
interface is provided; search constraints can be given and
recursive searches are possible. The only shortcoming is that
this method blocks the whole agent until the search terminates. A
special <code>SearchDFBehaviour</code> can be used to perform
<b>DF</b> searches without blocking.
@param dfName The GUID of the <b>DF</b> agent to start search from.
@param dfd A <code>DFAgentDescriptor</code> object containing
data to search for; this parameter is used as a template to match
data against.
@param constraints A <code>Vector</code> that must be filled with
all <code>Constraint</code> objects to apply to the current
search. This can be <code>null</code> if no search constraints
are required.
@return A <code>DFSearchResult</code> object containing all found
<code>DFAgentDescriptor</code> objects matching the given
descriptor, subject to given search constraints for search depth
and result size.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
@see java.util.Vector
@see jade.domain.AgentManagementOntology.Constraint
@see jade.domain.AgentManagementOntology.DFSearchResult
*/
public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException {
String replyString = myName + "-df-search-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction();
a.setName(AgentManagementOntology.DFAction.SEARCH);
a.setActor(dfName);
a.setArg(dfd);
if(constraints == null) {
AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint();
c.setName(AgentManagementOntology.Constraint.DFDEPTH);
c.setFn(AgentManagementOntology.Constraint.EXACTLY);
c.setArg(1);
a.addConstraint(c);
}
else {
// Put constraints into action
Iterator i = constraints.iterator();
while(i.hasNext()) {
AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)i.next();
a.addConstraint(c);
}
}
// Convert it to a String and write it in content field of the request
StringWriter textOut = new StringWriter();
a.toText(textOut);
request.setContent(textOut.toString());
// Send message and collect reply
String content = doFipaRequestClient(request, replyString);
// Extract agent descriptors from reply message
AgentManagementOntology.DFSearchResult found = null;
StringReader textIn = new StringReader(content);
try {
found = AgentManagementOntology.DFSearchResult.fromText(textIn);
}
catch(jade.domain.ParseException jdpe) {
jdpe.printStackTrace();
}
catch(jade.domain.TokenMgrError jdtme) {
jdtme.printStackTrace();
}
return found;
}
// Event handling methods
// Broadcast communication event to registered listeners
private void broadcastEvent(CommEvent event) {
Iterator i = listeners.iterator();
while(i.hasNext()) {
CommListener l = (CommListener)i.next();
l.CommHandle(event);
}
}
// Register a new listener
public final void addCommListener(CommListener l) {
listeners.add(l);
}
// Remove a registered listener
public final void removeCommListener(CommListener l) {
listeners.remove(l);
}
// Notify listeners of the destruction of the current agent
private void notifyDestruction() {
Iterator i = listeners.iterator();
while(i.hasNext()) {
CommListener l = (CommListener)i.next();
l.endSource(myName);
}
}
private void activateBehaviour(Behaviour b) {
Behaviour root = b.root();
blockedBehaviours.remove(root);
b.restart();
myScheduler.add(root);
}
private void activateAllBehaviours() {
// Put all blocked behaviours back in ready queue,
// atomically with respect to the Scheduler object
synchronized(myScheduler) {
while(!blockedBehaviours.isEmpty()) {
Behaviour b = (Behaviour)blockedBehaviours.lastElement();
blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1);
b.restart();
myScheduler.add(b);
}
}
}
/**
Put a received message into the agent message queue. The mesage
is put at the back end of the queue. This method is called by
JADE runtime system when a message arrives, but can also be used
by an agent, and is just the same as sending a message to oneself
(though slightly faster).
@param msg The ACL message to put in the queue.
@see jade.core.Agent#send(ACLMessage msg)
*/
public final void postMessage (ACLMessage msg) {
synchronized(waitLock) {
if(msg != null) msgQueue.addLast(msg);
doWake();
}
}
} |
/*
$Log$
Revision 1.3 1998/11/02 02:06:23 rimassa
Started to add a Behaviour to handle 'inform' messages the AMS sends
when some AgentPlatform event occurs that can be of interest of Remote
Management Agent.
Revision 1.2 1998/11/01 15:02:29 rimassa
Added a Behaviour to register with the AMS as a listener of Agent
Container Event notifications.
Revision 1.1 1998/10/26 00:12:30 rimassa
New domain agent to perform platform administration: this agent has a GUI to
manage the Agent Platform and special access rights to the AMS.
*/
package jade.domain;
// FIXME: For debug only
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import jade.core.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.gui.*;
public class rma extends Agent {
private ACLMessage AMSSubscription = new ACLMessage("subscribe");
private ACLMessage AMSCancellation = new ACLMessage("cancel");
private class AMSListenerBehaviour extends CyclicBehaviour {
private MessageTemplate listenTemplate;
AMSListenerBehaviour() {
MessageTemplate mt1 = MessageTemplate.MatchLanguage("SL");
MessageTemplate mt2 = MessageTemplate.MatchOntology("jade-agent-management");
MessageTemplate mt12 = MessageTemplate.and(mt1, mt2);
mt1 = MessageTemplate.MatchReplyTo("RMA-subscription");
mt2 = MessageTemplate.MatchType("inform");
listenTemplate = MessageTemplate.and(mt1, mt2);
listenTemplate = MessageTemplate.and(listenTemplate, mt12);
}
public void action() {
ACLMessage current = receive(listenTemplate);
if(current != null) {
// Handle inform messages from AMS
current.toText(new BufferedWriter(new OutputStreamWriter(System.out)));
StringReader text = new StringReader(current.getContent());
try {
AgentManagementOntology.AMSEvent amse = AgentManagementOntology.AMSEvent.fromText(text);
}
catch(ParseException pe) {
pe.printStackTrace();
return;
}
catch(TokenMgrError tme) {
tme.printStackTrace();
return;
}
current = null;
}
else
block();
}
} // End of AMSListenerBehaviour
private SequentialBehaviour AMSSubscribe = new SequentialBehaviour();
private AMSMainFrame myGUI = new AMSMainFrame();
public void setup() {
// Fill ACL messages fields
AMSSubscription.setDest("AMS");
AMSSubscription.setLanguage("SL");
AMSSubscription.setOntology("jade-agent-management");
AMSSubscription.setReplyWith("RMA-subscription");
AMSSubscription.setConversationId(myName+'@'+myAddress);
// Please inform me whenever container list changes and send me
// the difference between old and new container lists, complete
// with every AMS agent descriptor
String content = "iota ?x ( :container-list-delta ?x )";
AMSSubscription.setContent(content);
AMSCancellation.setDest("AMS");
AMSCancellation.setLanguage("SL");
AMSCancellation.setOntology("jade-agent-management");
AMSCancellation.setReplyWith("RMA-cancellation");
AMSCancellation.setConversationId(myName+'@'+myAddress);
// No content is needed (cfr. FIPA 97 Part 2 page 26)
// Send 'subscribe' message to the AMS
AMSSubscribe.addBehaviour(new SenderBehaviour(this, AMSSubscription));
// Handle incoming 'inform' messages
AMSSubscribe.addBehaviour(new AMSListenerBehaviour());
// Schedule Behaviour for execution
addBehaviour(AMSSubscribe);
// Show Graphical User Interface
myGUI.ShowCorrect();
}
} |
package hudson.cli;
import static java.util.logging.Level.FINE;
import java.io.Console;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import com.trilead.ssh2.crypto.PEMDecoder;
/**
* Read DSA or RSA key from file(s) asking for password interactively.
*
* @author ogondza
* @since 1.556
*/
public class PrivateKeyProvider {
private List<KeyPair> privateKeys = new ArrayList<KeyPair>();
/**
* Get keys read so far.
*
* @return Possibly empty list. Never null.
*/
public List<KeyPair> getKeys() {
return Collections.unmodifiableList(privateKeys);
}
public boolean hasKeys() {
return !privateKeys.isEmpty();
}
/**
* Read keys from default keyFiles
*
* {@code .ssh/id_rsa}, {@code .ssh/id_dsa} and {@code .ssh/identity}.
*
* @return true if some key was read successfully.
*/
public boolean readFromDefaultLocations() {
final File home = new File(System.getProperty("user.home"));
boolean read = false;
for (String path : new String[] {".ssh/id_rsa", ".ssh/id_dsa", ".ssh/identity"}) {
final File key = new File(home, path);
if (!key.exists()) continue;
try {
readFrom(key);
read = true;
} catch (IOException e) {
LOGGER.log(FINE, "Failed to load " + key, e);
} catch (GeneralSecurityException e) {
LOGGER.log(FINE, "Failed to load " + key, e);
}
}
return read;
}
/**
* Read key from keyFile.
*/
public void readFrom(File keyFile) throws IOException, GeneralSecurityException {
final String password = isPemEncrypted(keyFile)
? askForPasswd(keyFile.getCanonicalPath())
: null
;
privateKeys.add(loadKey(keyFile, password));
}
private static boolean isPemEncrypted(File f) throws IOException{
//simple check if the file is encrypted
return readPemFile(f).contains("4,ENCRYPTED");
}
private static String askForPasswd(String filePath){
Console cons = System.console();
String passwd = null;
if (cons != null){
char[] p = cons.readPassword("%s", "Enter passphrase for " + filePath + ":");
passwd = String.valueOf(p);
}
return passwd;
}
public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException {
return loadKey(readPemFile(f), passwd);
}
private static String readPemFile(File f) throws IOException{
try (InputStream is = Files.newInputStream(f.toPath());
DataInputStream dis = new DataInputStream(is)) {
byte[] bytes = new byte[(int) f.length()];
dis.readFully(bytes);
return new String(bytes);
} catch (InvalidPathException e) {
throw new IOException(e);
}
}
public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException {
Object key = PEMDecoder.decode(pemString.toCharArray(), passwd);
if (key instanceof com.trilead.ssh2.signature.RSAPrivateKey) {
com.trilead.ssh2.signature.RSAPrivateKey x = (com.trilead.ssh2.signature.RSAPrivateKey)key;
return x.toJCEKeyPair();
}
if (key instanceof com.trilead.ssh2.signature.DSAPrivateKey) {
com.trilead.ssh2.signature.DSAPrivateKey x = (com.trilead.ssh2.signature.DSAPrivateKey)key;
KeyFactory kf = KeyFactory.getInstance("DSA");
return new KeyPair(
kf.generatePublic(new DSAPublicKeySpec(x.getY(), x.getP(), x.getQ(), x.getG())),
kf.generatePrivate(new DSAPrivateKeySpec(x.getX(), x.getP(), x.getQ(), x.getG())));
}
throw new UnsupportedOperationException("Unrecognizable key format: " + key);
}
private static final Logger LOGGER = Logger.getLogger(PrivateKeyProvider.class.getName());
} |
package specs;
import com.commercetools.pspadapter.payone.config.PropertyProvider;
import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder;
import com.commercetools.pspadapter.payone.domain.ctp.TypeCacheLoader;
import com.commercetools.pspadapter.payone.mapping.CustomFieldKeys;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.*;
import com.google.common.hash.Hashing;
import com.mashape.unirest.http.Unirest;
import com.neovisionaries.i18n.CountryCode;
import io.sphere.sdk.carts.Cart;
import io.sphere.sdk.carts.CartDraft;
import io.sphere.sdk.carts.CartDraftBuilder;
import io.sphere.sdk.carts.commands.CartCreateCommand;
import io.sphere.sdk.carts.commands.CartUpdateCommand;
import io.sphere.sdk.carts.commands.updateactions.AddLineItem;
import io.sphere.sdk.carts.commands.updateactions.AddPayment;
import io.sphere.sdk.carts.commands.updateactions.SetBillingAddress;
import io.sphere.sdk.carts.commands.updateactions.SetShippingAddress;
import io.sphere.sdk.client.BlockingSphereClient;
import io.sphere.sdk.client.SphereClientFactory;
import io.sphere.sdk.models.Address;
import io.sphere.sdk.orders.Order;
import io.sphere.sdk.orders.OrderFromCartDraft;
import io.sphere.sdk.orders.PaymentState;
import io.sphere.sdk.orders.commands.OrderFromCartCreateCommand;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import io.sphere.sdk.payments.TransactionState;
import io.sphere.sdk.payments.queries.PaymentByIdGet;
import io.sphere.sdk.products.Product;
import io.sphere.sdk.products.queries.ProductQuery;
import io.sphere.sdk.types.CustomFields;
import io.sphere.sdk.types.Type;
import io.sphere.sdk.utils.MoneyImpl;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.DOTALL;
/**
* @author fhaertig
* @since 10.12.15
*/
public abstract class BaseFixture {
private static final Logger LOG = LoggerFactory.getLogger(BaseFixture.class);
protected final MonetaryAmountFormat currencyFormatterDe = MonetaryFormats.getAmountFormat(Locale.GERMANY);
protected static final String EMPTY_STRING = "";
protected static final String NULL_STRING = "null";
protected static final long PAYONE_NOTIFICATION_TIMEOUT = TimeUnit.MINUTES.toMillis(15);
protected static final long RETRY_DELAY = TimeUnit.SECONDS.toMillis(15);
protected static final long INTERMEDIATE_REPORT_DELAY = TimeUnit.MINUTES.toMillis(3);
// looks like heroku may have some lags, so we use 15 seconds to avoid false test fails because of timeouts
protected static final int INTEGRATION_SERVICE_REQUEST_TIMEOUT = 15000;
protected static final Duration CTP_REQUEST_TIMEOUT = Duration.ofMinutes(2);
protected static final Splitter thePaymentNamesSplitter = Splitter.on(", ");
private static final String TEST_DATA_VISA_CREDIT_CARD_NO_3_DS = "TEST_DATA_VISA_CREDIT_CARD_NO_3DS";
private static final String TEST_DATA_VISA_CREDIT_CARD_3_DS = "TEST_DATA_VISA_CREDIT_CARD_3DS";
private static final String TEST_DATA_3_DS_PASSWORD = "TEST_DATA_3_DS_PASSWORD";
private static final String TEST_DATA_SW_BANK_TRANSFER_IBAN = "TEST_DATA_SW_BANK_TRANSFER_IBAN";
private static final String TEST_DATA_SW_BANK_TRANSFER_BIC = "TEST_DATA_SW_BANK_TRANSFER_BIC";
private static final String TEST_DATA_PAYONE_MERCHANT_ID = "TEST_DATA_PAYONE_MERCHANT_ID";
private static final String TEST_DATA_PAYONE_SUBACC_ID = "TEST_DATA_PAYONE_SUBACC_ID";
private static final String TEST_DATA_PAYONE_PORTAL_ID = "TEST_DATA_PAYONE_PORTAL_ID";
private static final String TEST_DATA_PAYONE_KEY = "TEST_DATA_PAYONE_KEY";
private static final Random randomSource = new Random();
/**
* Only for creation of test data
*/
private static BlockingSphereClient ctpClient;
private static URL ctPayoneIntegrationBaseUrl;
private static LoadingCache<String, Type> typeCache;
/**
* maps legible payment names to payment IDs (and vice versa)
*/
private BiMap<String, String> payments = HashBiMap.create();
@BeforeClass
static public void initializeCommercetoolsClient() throws MalformedURLException {
final PropertyProvider propertyProvider = new PropertyProvider();
ctPayoneIntegrationBaseUrl =
new URL(propertyProvider.getMandatoryNonEmptyProperty("CT_PAYONE_INTEGRATION_URL"));
ctpClient = BlockingSphereClient.of(
SphereClientFactory.of().createClient(
propertyProvider.getMandatoryNonEmptyProperty(PropertyProvider.CT_PROJECT_KEY),
propertyProvider.getMandatoryNonEmptyProperty(PropertyProvider.CT_CLIENT_ID),
propertyProvider.getMandatoryNonEmptyProperty(PropertyProvider.CT_CLIENT_SECRET)),
CTP_REQUEST_TIMEOUT
);
typeCache = CacheBuilder.newBuilder().build(new TypeCacheLoader(ctpClient));
}
public String getHandlePaymentUrl(final String paymentId) throws MalformedURLException {
return getServiceUrl("/commercetools/handle/payments/" + paymentId);
}
public String getNotificationUrl() throws MalformedURLException {
return getServiceUrl("/payone/notification");
}
public String getHealthUrl() throws MalformedURLException {
return getServiceUrl("/health");
}
final String getServiceUrl(String suffix) throws MalformedURLException {
return new URL(
ctPayoneIntegrationBaseUrl.getProtocol(),
ctPayoneIntegrationBaseUrl.getHost(),
ctPayoneIntegrationBaseUrl.getPort(),
suffix)
.toExternalForm();
}
public HttpResponse sendGetRequestToUrl(final String url) throws IOException {
return Request.Get(url)
.connectTimeout(INTEGRATION_SERVICE_REQUEST_TIMEOUT)
.execute()
.returnResponse();
}
protected static String getConfigurationParameter(final String configParameterName) {
final String envVariable = System.getenv(configParameterName);
if (!Strings.isNullOrEmpty(envVariable)) {
return envVariable;
}
final String sysProperty = System.getProperty(configParameterName);
if (!Strings.isNullOrEmpty(sysProperty)) {
return sysProperty;
}
throw new RuntimeException(String.format(
"Environment variable required for configuration must not be null or empty: %s",
configParameterName));
}
protected MonetaryAmount createMonetaryAmountFromCent(final Long centAmount, final String currencyCode) {
return MoneyImpl.ofCents(centAmount, currencyCode);
}
protected String createCartAndOrderForPayment(final Payment payment, final String currencyCode) {
return createCartAndOrderForPayment(payment, currencyCode, "TestBuyer", null);
}
protected String createCartAndOrderForPayment(final Payment payment, final String currencyCode, final PaymentState paymentState) {
return createCartAndOrderForPayment(payment, currencyCode, "TestBuyer", paymentState);
}
protected String createCartAndOrderForPayment(final Payment payment, final String currencyCode, final String buyerLastName) {
return createCartAndOrderForPayment(payment, currencyCode, buyerLastName, null);
}
protected String createCartAndOrderForPayment(final Payment payment, final String currencyCode, final String buyerLastName,
final PaymentState paymentState) {
Order order = createAndGetOrder(payment, currencyCode, buyerLastName, paymentState);
return order.getOrderNumber();
}
protected Order createAndGetOrder(Payment payment, String currencyCode) {
return createAndGetOrder(payment, currencyCode, "TestBuyer", null);
}
protected Order createAndGetOrder(Payment payment, String currencyCode, PaymentState paymentState) {
return createAndGetOrder(payment, currencyCode, "TestBuyer", paymentState);
}
protected Order createAndGetOrder(Payment payment, String currencyCode, String buyerLastName, PaymentState paymentState) {
// create cart and order with product
final Product product = ctpClient.executeBlocking(ProductQuery.of()).getResults().get(0);
final CartDraft cardDraft = CartDraftBuilder.of(Monetary.getCurrency(currencyCode)).build();
final Cart cart = ctpClient.executeBlocking(CartUpdateCommand.of(
ctpClient.executeBlocking(CartCreateCommand.of(cardDraft)),
ImmutableList.of(
AddPayment.of(payment),
AddLineItem.of(product.getId(), product.getMasterData().getCurrent().getMasterVariant().getId(), 1),
SetShippingAddress.of(Address.of(CountryCode.DE)),
SetBillingAddress.of(Address.of(CountryCode.DE).withLastName(buyerLastName))
)));
final String orderNumber = getRandomOrderNumber();
return ctpClient.executeBlocking(OrderFromCartCreateCommand.of(
OrderFromCartDraft.of(cart, orderNumber, paymentState)));
}
private static String PSEUDO_CARD_PAN;
/**
* Fetch new or get cached pseudocardpan from Payone service based on supplied test VISA card number
* (see {@link #getTestDataVisaCreditCardNo3Ds()}).
* <p>
* Why <i>synchronized</i>: the card pan is fetched over HTTP POST request from pay1.de site and the operation
* might be slow, so we cache the value. But our tests run concurrently, so to avoid double HTTP request
* to pay1.de we use synchronized: the access to the method is blocked till the response from pay1.de, but it is
* blocked once, all other get access will be fast (when {@code PSEUDO_CARD_PAN} is set).
*/
synchronized static protected String getUnconfirmedVisaPseudoCardPan() {
if (PSEUDO_CARD_PAN == null) {
String cardPanResponse = null;
try {
cardPanResponse = Unirest.post("https://api.pay1.de/post-gateway/")
.fields(ImmutableMap.<String, Object>builder()
.put("request", "3dscheck")
.put("mid", getTestDataPayoneMerchantId())
.put("aid", getTestDataPayoneSubaccId())
.put("portalid", getTestDataPayonePortalId())
.put("key", Hashing.md5().hashString(getTestDataPayoneKey(), Charsets.UTF_8).toString())
.put("mode", "test")
.put("api_version", "3.9")
.put("amount", "2")
.put("currency", "EUR")
.put("clearingtype", "cc")
.put("exiturl", "http:
.put("storecarddata", "yes")
.put("cardexpiredate", "2512")
.put("cardcvc2", "123")
.put("cardtype", "V")
.put("cardpan", getTestDataVisaCreditCardNo3Ds())
.build())
.asString().getBody();
} catch (Throwable e) {
throw new RuntimeException("Error on pseudocardpan fetch", e);
}
Pattern p = Pattern.compile("^.*pseudocardpan\\s*=\\s*(\\d+).*$", CASE_INSENSITIVE | DOTALL);
Matcher m = p.matcher(cardPanResponse);
if (m.matches()) {
assert PSEUDO_CARD_PAN == null : "PSEUDO_CARD_PAN multiple initialization";
PSEUDO_CARD_PAN = m.group(1);
LOG.info("Pseudocardpan fetched successfully");
} else {
throw new RuntimeException(String.format("Unexpected pseudocardpan response: %s", cardPanResponse));
}
}
return PSEUDO_CARD_PAN;
}
protected static String getTestDataVisaCreditCardNo3Ds() {
return getConfigurationParameter(TEST_DATA_VISA_CREDIT_CARD_NO_3_DS);
}
protected static String getTestData3DsPassword() {
return getConfigurationParameter(TEST_DATA_3_DS_PASSWORD);
}
protected static String getVerifiedVisaPseudoCardPan() {
return getConfigurationParameter(TEST_DATA_VISA_CREDIT_CARD_3_DS);
}
protected static String getTestDataSwBankTransferIban() {
return getConfigurationParameter(TEST_DATA_SW_BANK_TRANSFER_IBAN);
}
protected static String getTestDataSwBankTransferBic() {
return getConfigurationParameter(TEST_DATA_SW_BANK_TRANSFER_BIC);
}
private static String getTestDataPayoneMerchantId() {
return getConfigurationParameter(TEST_DATA_PAYONE_MERCHANT_ID);
}
private static String getTestDataPayoneSubaccId() {
return getConfigurationParameter(TEST_DATA_PAYONE_SUBACC_ID);
}
private static String getTestDataPayonePortalId() {
return getConfigurationParameter(TEST_DATA_PAYONE_PORTAL_ID);
}
private static String getTestDataPayoneKey() {
return getConfigurationParameter(TEST_DATA_PAYONE_KEY);
}
protected static String getRandomOrderNumber() {
return String.valueOf(randomSource.nextInt() + System.currentTimeMillis());
}
protected BlockingSphereClient ctpClient() {
return ctpClient;
}
/**
* Gets the latest version of the payment via its legible name - a name that exits only in this test context.
* @param paymentName legible name of the payment
* @return the payment fetched from the commercetools client, can be null!
* @see #fetchPaymentById(String)
*/
protected Payment fetchPaymentByLegibleName(final String paymentName) {
return fetchPaymentById(payments.get(paymentName));
}
/**
* Gets the latest version of the payment via its ID.
* @param paymentId unique ID of the payment
* @return the payment fetched from the commercetools client, can be null!
* @see #fetchPaymentByLegibleName(String)
*/
protected Payment fetchPaymentById(final String paymentId) {
return ctpClient.executeBlocking(PaymentByIdGet.of(
Preconditions.checkNotNull(paymentId, "paymentId must not be null!")));
}
/**
* Gets the ID of the type with name (aka key) {@code typeName}.
* @param typeName the name (key) of a type
* @return the type's ID
* @throws ExecutionException if a checked exception was thrown while loading the value.
*/
protected String typeIdFromTypeName(final String typeName) throws ExecutionException {
return typeCache.get(typeName).getId();
}
public String getTransactionStateByPaymentId(final String paymentId, final String transactionId) {
return getTransactionState(fetchPaymentById(paymentId), transactionId);
}
protected String getTransactionState(final Payment payment, final String transactionId) {
final Optional<Transaction> transaction = payment.getTransactions()
.stream()
.filter(i -> transactionId.equals(i.getId()))
.findFirst();
final TransactionState transactionState = transaction.isPresent() ? transaction.get().getState() : null;
return transactionState != null ? transactionState.toSphereName() : "<UNKNOWN>";
}
public String getIdOfLastTransactionByPaymentId(final String paymentId) {
return getIdOfLastTransaction(fetchPaymentById(paymentId));
}
protected String getIdOfLastTransaction(final Payment payment) {
Preconditions.checkNotNull(payment,
"payment is null. This could be due to a restarting service instance which has not finished cleaning the platform from custom types, payments, orders and carts!");
return Iterables.getLast(payment.getTransactions()).getId();
}
protected String getIdOfFirstTransaction(final Payment payment) {
return Objects.requireNonNull(payment,
"payment is null. This could be due to a restarting service instance which has not finished cleaning the platform from custom types, payments, orders and carts!")
.getTransactions().get(0).getId();
}
protected void registerPaymentWithLegibleName(final String paymentName, final Payment payment) {
Preconditions.checkState(!payments.containsKey(paymentName),
String.format("Legible payment name '%s' already in use for ID '%s'.",
paymentName, payments.get(paymentName)));
Preconditions.checkState(!payments.containsValue(payment.getId()),
String.format("Payment with ID '%s' already known as '%s' instead of '%s'",
payment.getId(), payments.inverse().get(payment.getId()), paymentName));
payments.put(paymentName, payment.getId());
}
protected HttpResponse requestToHandlePaymentByLegibleName(final String paymentName) throws IOException {
Preconditions.checkState(payments.containsKey(paymentName),
String.format("Legible payment name '%s' not mapped to any payment ID.", paymentName));
return Request.Get(getHandlePaymentUrl(payments.get(paymentName)))
.connectTimeout(INTEGRATION_SERVICE_REQUEST_TIMEOUT)
.execute()
.returnResponse();
}
protected String getIdForLegibleName(final String paymentName) {
return payments.get(paymentName);
}
protected String getInteractionRequestCount(final Payment payment,
final String transactionId,
final String requestType) throws ExecutionException {
final String interactionTypeId = typeIdFromTypeName(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST);
return Long.toString(payment.getInterfaceInteractions().stream()
.filter(i -> interactionTypeId.equals(i.getType().getId()))
.filter(i -> transactionId.equals(i.getFieldAsString(CustomFieldKeys.TRANSACTION_ID_FIELD)))
.filter(i -> {
final String requestField = i.getFieldAsString(CustomFieldKeys.REQUEST_FIELD);
return (requestField != null) && requestField.contains("request=" + requestType);
})
.count());
}
protected String getInteractionRequestCountOverAllTransactions(final Payment payment,
final String requestType) throws ExecutionException {
final String interactionTypeId = typeIdFromTypeName(CustomTypeBuilder.PAYONE_INTERACTION_REQUEST);
return Long.toString(payment.getInterfaceInteractions().stream()
.filter(i -> interactionTypeId.equals(i.getType().getId()))
.filter(i -> {
final String requestField = i.getFieldAsString(CustomFieldKeys.REQUEST_FIELD);
return (requestField != null) && requestField.contains("request=" + requestType);
})
.count());
}
protected Optional<CustomFields> getInteractionRedirect(final Payment payment,
final String transactionId) throws ExecutionException {
final String interactionTypeId = typeIdFromTypeName(CustomTypeBuilder.PAYONE_INTERACTION_REDIRECT);
return payment.getInterfaceInteractions().stream()
.filter(i -> interactionTypeId.equals(i.getType().getId()))
.filter(i -> transactionId.equals(i.getFieldAsString(CustomFieldKeys.TRANSACTION_ID_FIELD)))
.filter(i -> {
final String redirectField = i.getFieldAsString(CustomFieldKeys.REDIRECT_URL_FIELD);
return redirectField != null && !redirectField.isEmpty();
})
.findFirst();
}
protected long countPaymentsWithNotificationOfAction(final ImmutableList<String> paymentNames, final String txaction) {
final List<RuntimeException> exceptions = Lists.newArrayList();
final long result = paymentNames.stream().mapToLong(paymentName -> {
final Payment payment = fetchPaymentByLegibleName(paymentName);
try {
return getTotalNotificationCountOfAction(payment, txaction);
} catch (final ExecutionException e) {
LOG.error("Exception: %s", e);
exceptions.add(new RuntimeException(e));
return 0L;
}
}).filter(notifications -> notifications > 0L).count();
if (!exceptions.isEmpty()) {
throw exceptions.get(0);
}
return result;
}
protected long getTotalNotificationCountOfAction(final Payment payment, final String txaction) throws ExecutionException {
final String interactionTypeId = typeIdFromTypeName(CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION);
return payment.getInterfaceInteractions().stream()
.filter(i -> interactionTypeId.equals(i.getType().getId()))
.filter(i -> txaction.equals(i.getFieldAsString(CustomFieldKeys.TX_ACTION_FIELD)))
.filter(i -> {
final String notificationField = i.getFieldAsString(CustomFieldKeys.NOTIFICATION_FIELD);
return (notificationField != null) &&
(notificationField.toLowerCase().contains("transactionstatus=completed")
|| notificationField.toLowerCase().contains("transactionstatus=null"));
})
.count();
}
public boolean customStringFieldIsNull(final String paymentName, final String fieldName) {
final Payment payment = fetchPaymentByLegibleName(paymentName);
return payment.getCustom().getFieldAsString(fieldName) == null;
}
} |
package mobi.hsz.idea.gitignore.util;
import com.intellij.util.containers.ContainerUtil;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Util class to speed up and limit regex operation on the files paths.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 1.3.1
*/
public class MatcherUtil {
/** Stores calculated matching results. */
private static HashMap<Integer, Boolean> cache;
/** Private constructor to prevent creating {@link Icons} instance. */
private MatcherUtil() {
}
/**
* Extracts alphanumeric parts from the regex pattern and checks if any of them is contained in the tested path.
* Looking for the parts speed ups the matching and prevents from running whole regex on the string.
*
* @param matcher to explode
* @param path to check
* @return path matches the pattern
*/
public static boolean match(@Nullable Matcher matcher, @Nullable String path) {
if (matcher == null || path == null) {
return false;
}
if (cache == null) {
cache = ContainerUtil.newHashMap();
}
int hashCode = new HashCodeBuilder().append(matcher.pattern()).append(path).toHashCode();
if (!cache.containsKey(hashCode)) {
final String[] parts = getParts(matcher);
boolean result = false;
if (parts.length == 0 || matchAllParts(parts, path)) {
try {
result = matcher.reset(path).find();
} catch (StringIndexOutOfBoundsException ignored) {
}
}
cache.put(hashCode, result);
}
return cache.get(hashCode);
}
/**
* Checks if given path contains all of the path parts.
*
* @param parts that should be contained in path
* @param path to check
* @return path contains all parts
*/
public static boolean matchAllParts(@Nullable String[] parts, @Nullable String path) {
if (parts == null || path == null) {
return false;
}
int index = -1;
for (String part : parts) {
index = path.indexOf(part, index);
if (index == -1) {
return false;
}
}
return true;
}
/**
* Checks if given path contains any of the path parts.
*
* @param parts that should be contained in path
* @param path to check
* @return path contains any of the parts
*/
public static boolean matchAnyPart(@Nullable String[] parts, @Nullable String path) {
if (parts == null || path == null) {
return false;
}
for (String part : parts) {
if (path.contains(part)) {
return true;
}
}
return false;
}
/**
* Extracts alphanumeric parts from {@link Matcher} pattern.
*
* @param matcher to handle
* @return extracted parts
*/
@NotNull
public static String[] getParts(@Nullable Matcher matcher) {
if (matcher == null) {
return new String[0];
}
return getParts(matcher.pattern());
}
/**
* Extracts alphanumeric parts from {@link Pattern}.
*
* @param pattern to handle
* @return extracted parts
*/
@NotNull
public static String[] getParts(@Nullable Pattern pattern) {
if (pattern == null) {
return new String[0];
}
final List<String> parts = ContainerUtil.newArrayList();
final String sPattern = pattern.toString();
String part = "";
boolean inSquare = false;
for (int i = 0; i < sPattern.length(); i++) {
char ch = sPattern.charAt(i);
if (!inSquare && Character.isLetterOrDigit(ch)) {
part += sPattern.charAt(i);
} else if (!part.isEmpty()) {
parts.add(part);
part = "";
}
inSquare = ch != ']' && ((ch == '[') || inSquare);
}
return parts.toArray(new String[parts.size()]);
}
} |
package org.mwc.cmap.xyplot.views.providers;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.mwc.cmap.xyplot.views.ILocationCalculator;
import org.mwc.cmap.xyplot.views.LocationCalculator;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.Editable;
import MWC.GUI.Shapes.LineShape;
import MWC.GenericData.HiResDate;
import MWC.GenericData.Watchable;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldLocation;
import MWC.TacticalData.Fix;
public class CrossSectionDatasetProvider implements ICrossSectionDatasetProvider
{
private ILocationCalculator _calc;
public CrossSectionDatasetProvider()
{
this(WorldDistance.KM);
}
public CrossSectionDatasetProvider(final int units)
{
_calc = new LocationCalculator(units);
}
@Override
public XYSeries getSeries(final LineShape line, final TrackWrapper wlist,
final HiResDate startT, final HiResDate endT)
{
final Collection<Editable> editables = wlist.getItemsBetween(startT, endT);
Watchable[] wbs = (Watchable[]) editables.toArray(new Watchable[editables.size()]);
return getSeries(line, wlist.getName(), wbs);
}
@Override
public XYSeries getSeries(final LineShape line, final TrackWrapper wlist,
final HiResDate timeT)
{
final Watchable[] wbs = wlist.getNearestTo(timeT);
return getSeries(line, wlist.getName(), wbs);
}
private XYSeries getSeries(final LineShape line, String seriesName, Watchable[] wbs)
{
final XYSeries series = new XYSeries(seriesName);
for(final Watchable wb: wbs)
{
final Double x_coord = new Double(_calc.getDistance(line, wb));
final Double y_coord = new Double(wb.getDepth());
series.add(x_coord, y_coord);
}
return series;
}
static public final class CrossSectionDatasetProviderTest extends junit.framework.TestCase
{
DateFormat _dateFormat = new SimpleDateFormat("dd-mm-yyyy HH:mm");
HiResDate[] _times;
int TIME_ARRAY_SIZE = 7;
TrackWrapper _track;
LineShape _line;
CrossSectionDatasetProvider _testable = new CrossSectionDatasetProvider();
public void setUp() throws ParseException
{
WorldLocation start = new WorldLocation(0, 0, 0);
WorldLocation end = new WorldLocation(0, 1, 0);
_line = new LineShape(start, end);
_times = new HiResDate[TIME_ARRAY_SIZE];
for (int i=0; i<TIME_ARRAY_SIZE; i++)
{
final Date dateVal = _dateFormat.parse("09-09-2013 10:" + i*10);
_times[i] = new HiResDate(dateVal);
}
_track = new TrackWrapper();
int j = 0;
for (double i=0.0; i<=1.2; i+=0.2)
{
final WorldLocation loc = new WorldLocation(0, i, 0);
final Fix fix = new Fix(_times[j], loc, 2, 2);
_track.addFix(new FixWrapper(fix));
j++;
}
}
public void testDiscreteSeries() throws ParseException
{
for (int i=0; i<TIME_ARRAY_SIZE; i++)
{
final XYSeries series = _testable.getSeries(_line, _track, _times[i]);
assertEquals(1, series.getItemCount());
final XYDataItem item = series.getDataItem(0);
assertNotNull(item.getXValue());
assertEquals(0.0, item.getYValue()); //depth is 0
}
}
public void testSnailSeries() throws ParseException
{
for (int i=0; i<TIME_ARRAY_SIZE-1; i++)
{
final XYSeries series = _testable.getSeries(_line, _track, _times[i], _times[i+1]);
assertEquals(2, series.getItemCount());
for (int j=0; j<2; j++)
{
final XYDataItem item = series.getDataItem(j);
assertNotNull(item.getXValue());
assertEquals(0.0, item.getYValue()); //depth is 0
}
}
}
//TODO: tests with holes in data
}
} |
package markehme.factionsplus.listeners;
import markehme.factionsplus.FactionsPlus;
import markehme.factionsplus.MCore.LConf;
import markehme.factionsplus.MCore.FPUConf;
import markehme.factionsplus.extras.FType;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Egg;
import org.bukkit.entity.EnderPearl;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Snowball;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.potion.Potion;
import com.massivecraft.factions.Rel;
import com.massivecraft.factions.entity.BoardColls;
import com.massivecraft.factions.entity.UPlayer;
import com.massivecraft.massivecore.ps.PS;
import com.massivecraft.massivecore.util.Txt;
/**
* The AnimalDamagerListener adds protection for certain mobs
* inside of Faction land.
*
*/
@Deprecated
public class AnimalDamageListener implements Listener {
/**
* Protects mobs from fishing hooks.
*
* @param event
*/
@EventHandler(priority=EventPriority.LOW)
public void onFishingHook(PlayerFishEvent event) {
if(!FPUConf.get(UPlayer.get(event.getPlayer()).getUniverse()).enabled) return; // Universe support
// This will check for damage via a fishing hook
if(event.getCaught() != null) {
UPlayer uPlayer = UPlayer.get(event.getPlayer());
EntityType entity = event.getCaught().getType();
if(
protectEntity(entity)
&& (!uPlayer.isUsingAdminMode())
&& (!FactionsPlus.permission.has(event.getPlayer(), "factionsplus.cankillallmobs"))
&& (!canKillCheck(uPlayer))
) {
uPlayer.msg(Txt.parse(LConf.get().fpCantDamageThisMob));
event.setCancelled(true) ;
}
}
}
/**
* Protects mobs being attacked by players.
*
* @param event
*/
@EventHandler(priority=EventPriority.LOW)
public void onEntityAttacked(EntityDamageByEntityEvent event) {
if(!FPUConf.get(UPlayer.get(event.getDamager()).getUniverse()).enabled) return; // Universe support
// This is to check if the player is damaging an animal
if((event.getDamager() instanceof Player)) {
Player damagingPlayer = (Player) event.getDamager();
UPlayer UDamagingPlayer = UPlayer.get(damagingPlayer);
EntityType entity = event.getEntityType();
if(
protectEntity(entity)
&& (!UDamagingPlayer.isUsingAdminMode())
&& (!FactionsPlus.permission.has(damagingPlayer, "factionsplus.cankillallmobs"))
&& (!canKillCheck(UDamagingPlayer))
) {
// nup, nup. no do that *snaps fingers*
damagingPlayer.sendMessage(Txt.parse(LConf.get().fpCantDamageThisMob));
event.setCancelled(true) ;
}
}
}
@EventHandler(priority=EventPriority.LOW, ignoreCancelled = true)
public void onEntityAttackThing( EntityDamageByEntityEvent event ) {
if(!FPUConf.get(UPlayer.get(event.getDamager()).getUniverse()).enabled) return; // Universe support
// this is to check if the player is attacking with an arrow, etc
Projectile projectile = null;
if(event.getDamager() == null) {
return;
}
if((event.getDamager() instanceof Arrow)) {
projectile = (Arrow) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof Snowball)) {
projectile = (Snowball) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof Potion)) {
projectile = (ThrownPotion) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof ThrownPotion)) {
projectile = (ThrownPotion) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof EnderPearl)) {
projectile = (EnderPearl) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof Egg)) {
projectile = (Egg) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
} else if((event.getDamager() instanceof Fireball)) {
projectile = (Fireball) event.getDamager();
if(!(projectile.getShooter() instanceof Player)) {
return;
}
}
if(projectile != null) {
EntityType entity = event.getEntityType();
Player damagingPlayer = (Player) projectile.getShooter();
UPlayer UDamagingPlayer = UPlayer.get(damagingPlayer);
if(
protectEntity(entity)
&& (!UDamagingPlayer.isUsingAdminMode())
&& (!FactionsPlus.permission.has(damagingPlayer, "factionsplus.cankillallmobs"))
&& (!canKillCheck(UDamagingPlayer))
) {
damagingPlayer.sendMessage(Txt.parse(LConf.get().fpCantDamageThisMob));
event.setCancelled(true);
}
}
}
/**
* Confirms that the entity type needs to be protected
* @param entity
* @return
*/
private boolean protectEntity(EntityType entity) {
// This list is for mobs that don't attack players, and won't attack back.
// If outdated or missing something, please make a pull request!
if(
entity == EntityType.CHICKEN ||
entity == EntityType.COW ||
entity == EntityType.MUSHROOM_COW ||
entity == EntityType.OCELOT ||
entity == EntityType.WOLF ||
entity == EntityType.PIG ||
entity == EntityType.IRON_GOLEM ||
entity == EntityType.BAT ||
entity == EntityType.SNOWMAN ||
entity == EntityType.VILLAGER ||
entity == EntityType.HORSE ||
entity == EntityType.SQUID ||
entity == EntityType.SHEEP
) {
return true;
} else {
return false;
}
}
/**
* This does a check on players location vs. configuration to see if it is allowed
* @param uPlayer
* @return
*/
private boolean canKillCheck(UPlayer uPlayer) {
// If the player is part of WILDERNESS (none) and is in a normal factions land, then deny
if(FType.valueOf( uPlayer.getFaction() ) == FType.WILDERNESS
&& FType.valueOf(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation()))) == FType.FACTION) {
return false;
}
// If we're in a safezone, and protecting safezone passive mobs, then deny
if(FPUConf.get(uPlayer.getUniverse()).protectPassiveMobsSafeZone
&& FType.valueOf(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation()))) == FType.SAFEZONE) {
return false;
}
// Confirm allyMob check
if(!FPUConf.get(uPlayer.getUniverse()).allowFactionKill.get("allyMobs")) {
if(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation())).getRelationTo(uPlayer).equals(Rel.ALLY)) {
return false;
}
}
// Confirm neutralMob check
if(!FPUConf.get(uPlayer.getUniverse()).allowFactionKill.get("neturalMobs")) {
if(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation())).getRelationTo(uPlayer).equals(Rel.ENEMY)) {
return false;
}
}
// Confirm enemyMob check
if(FPUConf.get(uPlayer.getUniverse()).allowFactionKill.get("enemyMobs")) {
if(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation())).getRelationTo(uPlayer).equals(Rel.NEUTRAL) &&
!BoardColls.get().getFactionAt(PS.valueOf( uPlayer.getPlayer().getLocation())).isNone()) {
return false;
}
}
// Confirm truceMob check
if(FPUConf.get(uPlayer.getUniverse()).allowFactionKill.get("truceMobs")) {
if(BoardColls.get().getFactionAt(PS.valueOf(uPlayer.getPlayer().getLocation())).getRelationTo(uPlayer).equals(Rel.TRUCE)) {
return false;
}
}
// No issues - allow it.
return true;
}
} |
package jsaf.provider.windows.system;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.slf4j.cal10n.LocLogger;
import jsaf.Message;
import jsaf.intf.io.IFilesystem;
import jsaf.intf.system.IEnvironment;
import jsaf.intf.windows.identity.IDirectory;
import jsaf.intf.windows.io.IWindowsFilesystem;
import jsaf.intf.windows.powershell.IRunspacePool;
import jsaf.intf.windows.registry.IKey;
import jsaf.intf.windows.registry.IRegistry;
import jsaf.intf.windows.registry.IStringValue;
import jsaf.intf.windows.registry.IValue;
import jsaf.intf.windows.system.IWindowsSession;
import jsaf.intf.windows.wmi.IWmiProvider;
import jsaf.io.fs.AbstractFilesystem;
import jsaf.provider.AbstractSession;
import jsaf.provider.windows.identity.Directory;
import jsaf.provider.windows.io.WindowsFilesystem;
import jsaf.provider.windows.powershell.RunspacePool;
import jsaf.provider.windows.registry.Registry;
import jsaf.provider.windows.wmi.WmiProvider;
/**
* Windows implementation of ISession for local machines, using JACOB for WMI access via COM.
*
* @author David A. Solin
* @version %I% %G%
*/
public class WindowsSession extends AbstractSession implements IWindowsSession {
static {
// Load the JACOB DLL
com.jacob.com.LibraryLoader.loadJacobLibrary();
}
private WmiProvider wmi;
private boolean is64bit = false;
private Registry reg32, reg;
private IWindowsFilesystem fs32;
private Directory directory = null;
private RunspacePool runspaces = null;
private List<String> baseCommand = Arrays.asList("cmd", "/c");
private View accessorView = null;
public WindowsSession(File wsdir) {
super();
this.wsdir = wsdir;
}
protected List<String> getBaseCommand() {
return baseCommand;
}
// Implement ILoggable
@Override
public void setLogger(LocLogger logger) {
super.setLogger(logger);
if (fs32 != null && !fs32.equals(fs)) {
fs32.setLogger(logger);
}
if (wmi != null) {
wmi.setLogger(logger);
}
if (directory != null) {
directory.setLogger(logger);
}
}
// Implement ISession
@Override
public void dispose() {
super.dispose();
if (fs32 instanceof AbstractFilesystem) {
((AbstractFilesystem)fs32).dispose();
}
}
public boolean connect() {
if (env == null) {
try {
env = new Environment(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
is64bit = ((Environment)env).is64bit();
if (is64bit) {
if ("64".equals(System.getProperty("sun.arch.data.model"))) {
accessorView = View._64BIT;
} else {
accessorView = View._32BIT;
StringBuffer cmd = new StringBuffer(System.getenv("SystemRoot")).append("\\SysNative\\cmd.exe");
baseCommand = Arrays.asList(cmd.toString(), "/c");
}
logger.trace(Message.STATUS_WINDOWS_BITNESS, "64");
} else {
accessorView = View._32BIT;
logger.trace(Message.STATUS_WINDOWS_BITNESS, "32");
}
if (runspaces == null) {
runspaces = new RunspacePool(this, 100);
}
if (reg == null) {
try {
reg = new Registry(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
if (!is64bit) reg32 = reg;
}
if (wmi == null) {
wmi = new WmiProvider(this);
}
if (fs == null) {
try {
if (is64bit) {
fs = new WindowsFilesystem(this, View._64BIT, accessorView);
} else {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
fs = fs32;
}
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
return false;
}
}
if (wmi.register()) {
connected = true; // set this now so the IDirectory has access to the machine name
if (directory == null) {
try {
directory = new Directory(this);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
connected = false;
return false;
}
}
return true;
} else {
return false;
}
}
public void disconnect() {
runspaces.shutdown();
wmi.deregister();
connected = false;
}
public Type getType() {
return Type.WINDOWS;
}
@Override
public String getMachineName() {
if (isConnected()) {
try {
return reg.getStringValue(IRegistry.Hive.HKLM, IRegistry.COMPUTERNAME_KEY, IRegistry.COMPUTERNAME_VAL);
} catch (Exception e) {
logger.warn(Message.ERROR_MACHINENAME);
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
return getHostname();
}
// Implement IWindowsSession
public IRunspacePool getRunspacePool() {
return runspaces;
}
public IDirectory getDirectory() {
return directory;
}
public View getNativeView() {
return is64bit ? View._64BIT : View._32BIT;
}
public boolean supports(View view) {
switch(view) {
case _32BIT:
return true;
case _64BIT:
default:
return is64bit;
}
}
public IRegistry getRegistry(View view) {
switch(view) {
case _32BIT:
if (reg32 == null) {
if (getNativeView() == View._32BIT) {
reg32 = reg;
} else {
try {
reg32 = new Registry(this, View._32BIT);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return reg32;
default:
return reg;
}
}
public IWindowsFilesystem getFilesystem(View view) {
switch(view) {
case _32BIT:
if (fs32 == null) {
if (getNativeView() == View._32BIT) {
fs32 = (IWindowsFilesystem)fs;
} else {
try {
fs32 = new WindowsFilesystem(this, View._32BIT, accessorView);
} catch (Exception e) {
logger.warn(Message.getMessage(Message.ERROR_EXCEPTION), e);
}
}
}
return fs32;
default:
return (IWindowsFilesystem)fs;
}
}
public IWmiProvider getWmiProvider() {
return wmi;
}
} |
package com.github.mike10004.xvfbmanagerexample;
import com.github.mike10004.xvfbmanager.XvfbController;
import com.github.mike10004.xvfbmanager.XvfbManager;
import com.github.mike10004.xvfbselenium.WebDriverSupport;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.lang3.tuple.Pair;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import static com.google.common.base.Preconditions.checkArgument;
public class XvfbManagerExample {
public static final String ENV_FIREFOX_BIN = "FIREFOX_BIN";
public static void main(String[] args) throws IOException {
if (args.length < 0 || !browserMap.containsKey(args[0])) {
System.err.format("argument must be one of {%s}%n", Joiner.on(", ").join(browserMap.keySet()));
System.exit(1);
}
browseAndCaptureScreenshot(args[0]);
}
public static void browseAndCaptureScreenshot(String browserKey) throws IOException {
ClientAndServer server = ClientAndServer.startClientAndServer(0);
try {
String host = "localhost", path = "/";
int port = server.getPort();
String html = "<html><head><title>Example</title></head><body><img src=\"cat.jpg\"></body></html>";
byte[] imageBytes = Resources.toByteArray(XvfbManagerExample.class.getResource("/smiling-cat-in-public-domain.jpg"));
server.when(HttpRequest.request(path)).respond(HttpResponse.response(html).withHeader(HttpHeaders.CONTENT_TYPE, MediaType.HTML_UTF_8.toString()));
server.when(HttpRequest.request(path + "cat.jpg")).respond(HttpResponse.response().withBody(imageBytes).withHeader(HttpHeaders.CONTENT_TYPE, MediaType.JPEG.toString()));
URL url = new URL("http", host, port, path);
BufferedImage screenshotImage;
XvfbManager xvfb = new XvfbManager();
try (XvfbController ctrl = xvfb.start()) {
screenshotImage = browse(browserKey, url, ctrl.getDisplay());
}
System.out.format("captured %dx%d screenshot%n", screenshotImage.getWidth(), screenshotImage.getHeight());
File screenshotFile = new File(System.getProperty("user.dir")).toPath().resolve("target").resolve("screenshot-" + System.currentTimeMillis() + ".png").toFile();
ImageIO.write(screenshotImage, "png", screenshotFile);
} finally {
server.stop();
}
}
/**
* Visit a given URL and return a screenshot.
* @param url the url
* @return an image captured by the browser
* @throws IOException
*/
private static BufferedImage browse(String browserKey, URL url, String display) throws IOException {
Pair<Class<? extends WebDriver>, Function<String, ? extends WebDriver>> driverStuff = browserMap.get(browserKey);
checkArgument(driverStuff != null, "unsupported browser: %s", browserKey);
System.out.format("browsing %s on display %s with %s%n", url, display, driverStuff.getLeft());
Class<? extends WebDriver> webDriverClass = driverStuff.getLeft();
WebDriverManager.getInstance(webDriverClass).setup();
WebDriver webDriver = driverStuff.getRight().apply(display);
try {
webDriver.get(url.toString());
byte[] screenshotBytes = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.BYTES);
BufferedImage screenshotImage = ImageIO.read(new ByteArrayInputStream(screenshotBytes));
return screenshotImage;
} finally {
webDriver.quit();
}
}
private static final ImmutableMap<String, Pair<Class<? extends WebDriver>, Function<String, ? extends WebDriver>>> browserMap =
ImmutableMap.<String, Pair<Class<? extends WebDriver>, Function<String, ? extends WebDriver>>>builder()
.put("firefox", Pair.of(org.openqa.selenium.firefox.MarionetteDriver.class, new Function<String, FirefoxDriver>(){
@Override
public FirefoxDriver apply(String display) {
String firefoxBin = System.getenv(ENV_FIREFOX_BIN);
if (firefoxBin != null) {
System.out.format("using firefox binary path from environment variable %s: %s%n", ENV_FIREFOX_BIN, firefoxBin);
return WebDriverSupport.firefoxOnDisplay(display).create(new FirefoxBinary(new File(firefoxBin)), new FirefoxProfile());
} else {
return WebDriverSupport.firefoxOnDisplay(display).create();
}
}
}))
.put("chrome", Pair.of(ChromeDriver.class, new Function<String, ChromeDriver>(){
@Override
public ChromeDriver apply(String display) {
return WebDriverSupport.chromeOnDisplay(display).create();
}
}))
.build();
} |
package net.sourceforge.javydreamercsw.client.ui.nodes;
import com.validation.manager.core.DataBaseManager;
import com.validation.manager.core.db.Requirement;
import com.validation.manager.core.db.Step;
import com.validation.manager.core.db.controller.StepJpaController;
import com.validation.manager.core.server.core.RequirementServer;
import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
/**
*
* @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
*/
class StepChildFactory extends AbstractChildFactory {
private Step step;
public StepChildFactory(Step step) {
this.step = step;
}
@Override
protected boolean createKeys(List<Object> toPopulate) {
List<String> processed = new ArrayList<>();
for (Requirement r : step.getRequirementList()) {
if (!processed.contains(r.getUniqueId().trim())) {
processed.add(r.getUniqueId().trim());
RequirementServer rs = new RequirementServer(r);
toPopulate.add(Collections.max(rs.getVersions(), null));
}
}
return true;
}
@Override
protected Node[] createNodesForKey(Object key) {
return new Node[]{createNodeForKey(key)};
}
@Override
protected Node createNodeForKey(Object key) {
try {
if (key instanceof Requirement) {
Requirement req = (Requirement) key;
return new UIRequirementNode(req, null);
} else {
return null;
}
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}
@Override
protected void updateBean() {
StepJpaController controller
= new StepJpaController(DataBaseManager.getEntityManagerFactory());
step = controller.findStep(step.getStepPK());
}
} |
package de.uka.ipd.sdq.beagle.core.pcmconnection;
import static de.uka.ipd.sdq.beagle.core.testutil.BlackboardSeffElementsMatcher.areEqualRegardingSeffElements;
import static de.uka.ipd.sdq.beagle.core.testutil.ExceptionThrownMatcher.throwsException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import de.uka.ipd.sdq.beagle.core.Blackboard;
import de.uka.ipd.sdq.beagle.core.ExternalCallParameter;
import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement;
import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction;
import de.uka.ipd.sdq.beagle.core.SeffBranch;
import de.uka.ipd.sdq.beagle.core.SeffLoop;
import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression;
import de.uka.ipd.sdq.beagle.core.judge.EvaluableExpressionFitnessFunction;
import de.uka.ipd.sdq.beagle.core.judge.EvaluableExpressionFitnessFunctionBlackboardView;
import de.uka.ipd.sdq.beagle.core.testutil.factories.BlackboardFactory;
import org.eclipse.net4j.util.collection.Pair;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
/**
* Tests for {@link PcmRepositoryBlackboardFactory}.
*
* @author Christoph Michelbach
*/
public class PcmRepositoryBlackboardFactoryTest {
/**
* A factory which creates instances of {@link PcmRepositoryBlackboardFactory}.
*/
private static PcmRepositoryBlackboardFactoryFactory pcmRepositoryBlackboardFactoryFactory =
new PcmRepositoryBlackboardFactoryFactory();
/**
* Pseudo fitness function.
*/
private final EvaluableExpressionFitnessFunction fitnessFunction = new EvaluableExpressionFitnessFunction() {
/**
* Store between (pairs of measurable seff elements and evaluable expressions) and
* doubles.
*/
private final HashMap<Pair<MeasurableSeffElement, EvaluableExpression>, Double> store = new HashMap<>();
@Override
public double gradeFor(final ExternalCallParameter parameter, final EvaluableExpression expression,
final EvaluableExpressionFitnessFunctionBlackboardView blackboard) {
return this.determineValue(parameter, expression);
}
@Override
public double gradeFor(final SeffLoop loop, final EvaluableExpression expression,
final EvaluableExpressionFitnessFunctionBlackboardView blackboard) {
return this.determineValue(loop, expression);
}
@Override
public double gradeFor(final SeffBranch branch, final EvaluableExpression expression,
final EvaluableExpressionFitnessFunctionBlackboardView blackboard) {
return this.determineValue(branch, expression);
}
@Override
public double gradeFor(final ResourceDemandingInternalAction rdia, final EvaluableExpression expression,
final EvaluableExpressionFitnessFunctionBlackboardView blackboard) {
return this.determineValue(rdia, expression);
}
/**
* Determines the fitness of a combination of a {@code MeasurableSeffElement} and
* an {@code EvaluableExpression}.
*
* @param element A {@code MeasurableSeffElement}.
* @param expression An {@code EvaluableExpression}.
* @return The fitness value.
*/
private double determineValue(final MeasurableSeffElement element, final EvaluableExpression expression) {
final Pair<MeasurableSeffElement, EvaluableExpression> pair = new Pair<>(element, expression);
if (this.store.containsKey(pair)) {
return this.store.get(pair);
} else {
final double fitness = Math.pow(Math.random() * 10E5, 3);
this.store.put(pair, fitness);
return fitness;
}
}
};
/**
* Test method for
* {@link PcmRepositoryBlackboardFactory#PcmRepositoryBlackboardFactory(java.util.Set)
* and PcmRepositoryBlackboardFactory#PcmRepositoryBlackboardFactory(String)}. Asserts
* that creation is possible and {@code null} or an empty string or otherwise
* impossible path cannot be passed.
*/
@Test
public void pcmRepositoryBlackboardFactory() {
assertThat(() -> new PcmRepositoryBlackboardFactory((String) null, this.fitnessFunction),
throwsException(NullPointerException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory((File) null, this.fitnessFunction),
throwsException(NullPointerException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory("", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory(".", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory("..", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory("/", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory("/tmp", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
assertThat(() -> new PcmRepositoryBlackboardFactory("\0", this.fitnessFunction),
throwsException(IllegalArgumentException.class));
final File[] impossibleRepositoryFiles = {
new File(""), new File("."), new File(".."), new File("/"), new File("/tmp"), new File("\0")
};
for (File impossibleRepositoryFile : impossibleRepositoryFiles) {
assertThat(() -> new PcmRepositoryBlackboardFactory(impossibleRepositoryFile, this.fitnessFunction),
throwsException(IllegalArgumentException.class));
}
}
/**
* Test method for
* {@link PcmRepositoryBlackboardFactory#getBlackboardForAllElements()}.
*/
@Test
public void getBlackboardForAllElements() {
final PcmRepositoryBlackboardFactory pcmRepositoryBlackboardFactory =
pcmRepositoryBlackboardFactoryFactory.getAppSensorProjectInstance();
final Blackboard result = pcmRepositoryBlackboardFactory.getBlackboardForAllElements();
assertThat(result, is(notNullValue()));
assertThat(result.getAllRdias().size(), is(not(0)));
assertThat(result.getAllSeffBranches().size(), is(not(0)));
assertThat(result.getAllSeffLoops().size(), is(not(0)));
}
/**
* Test method for
* {@link PcmRepositoryBlackboardFactory#getBlackboardForIds(java.util.Collection)}.
*/
@SuppressWarnings({
"unchecked", "rawtypes"
})
@Test
public void getBlackboardForIdsCollectionOfString() {
final PcmRepositoryBlackboardFactory pcmRepositoryBlackboardFactory =
pcmRepositoryBlackboardFactoryFactory.getValidInstance();
final HashSet<String> collection = new HashSet<String>();
collection.add("");
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds(collection),
new BlackboardFactory().getEmpty()), areEqualRegardingSeffElements());
assertThat(() -> pcmRepositoryBlackboardFactory.getBlackboardForIds((String) null),
throwsException(NullPointerException.class));
}
/**
* Test method for
* {@link PcmRepositoryBlackboardFactory#getBlackboardForIds(java.lang.String[])}.
*
*/
@SuppressWarnings({
"unchecked", "rawtypes"
})
@Test
public void getBlackboardForIdsStringArray() {
final PcmRepositoryBlackboardFactory pcmRepositoryBlackboardFactory =
pcmRepositoryBlackboardFactoryFactory.getValidInstance();
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds(""), new BlackboardFactory().getEmpty()),
areEqualRegardingSeffElements());
assertThat(() -> pcmRepositoryBlackboardFactory.getBlackboardForIds((String[]) null),
throwsException(NullPointerException.class));
assertThat(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g"), is(not(nullValue())));
assertThat(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g"),
is(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g")));
assertThat(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g"),
is(not(pcmRepositoryBlackboardFactory.getBlackboardForIds("_FaSO4LnqEeWVlphM5rov7g"))));
assertThat(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g"),
is(not(pcmRepositoryBlackboardFactory.getBlackboardForAllElements())));
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g"),
pcmRepositoryBlackboardFactory.getBlackboardForAllElements()), not(areEqualRegardingSeffElements()));
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds("_SomeIdWhichDosntExistA"),
new BlackboardFactory().getEmpty()), areEqualRegardingSeffElements());
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds("_TooShortId"),
new BlackboardFactory().getEmpty()), areEqualRegardingSeffElements());
assertThat(new Pair(pcmRepositoryBlackboardFactory.getBlackboardForIds("IllegalId"),
new BlackboardFactory().getEmpty()), areEqualRegardingSeffElements());
final Blackboard blackboardForIds =
pcmRepositoryBlackboardFactory.getBlackboardForIds("_6f1a4LnmEeWVlphM5rov7g", "_FaSO4LnqEeWVlphM5rov7g");
assertThat(blackboardForIds.getAllSeffLoops().size(), is(not(0)));
for (SeffLoop seffLoop : blackboardForIds.getAllSeffLoops()) {
// How do i figure out whether this is correct?
seffLoop.getLoopBody().getStartFile();
}
}
@Test
public void appSensorRepositoryTest() {
final PcmRepositoryBlackboardFactory appSensorBlackboardFactory =
pcmRepositoryBlackboardFactoryFactory.getAppSensorProjectInstance();
Blackboard appSensorBlackboard = appSensorBlackboardFactory.getBlackboardForAllElements();
}
} |
package com.armenabrahamyan.main.abstractparsetree.beans;
/**
* Operator class definition (similar to bean, though abstract because of execute method)
* @author armenabrahamyan
*
*/
public abstract class Operator {
private String operatorName;
// This one is a priority
private int precedence;
// Notes whether it is left power binded or not
private boolean leftBinded;
/**
* Create a new operator with priority and power binding
* @param oper
* @param precedence
* @param leftAssoc
*/
public Operator(final String operatorName, int precedence, boolean leftBinded) {
this.operatorName = operatorName;
this.precedence = precedence;
this.leftBinded = leftBinded;
}
public String getOperatorName() {
return operatorName;
}
public int getPrecedence() {
return precedence;
}
public boolean isLeftBinded() {
return leftBinded;
}
public abstract String execute(final Integer a, final Integer b);
public abstract String execute(final Integer a);
} |
package ar.com.fernandospr.wns;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import ar.com.fernandospr.wns.exceptions.WnsException;
import ar.com.fernandospr.wns.model.WnsAbstractNotification;
import ar.com.fernandospr.wns.model.WnsBadge;
import ar.com.fernandospr.wns.model.WnsNotificationResponse;
import ar.com.fernandospr.wns.model.WnsOAuthToken;
import ar.com.fernandospr.wns.model.WnsTile;
import ar.com.fernandospr.wns.model.WnsToast;
import ar.com.fernandospr.wns.model.types.WnsNotificationType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class WnsService {
private static final String SCOPE = "notify.windows.com";
private static final String GRANT_TYPE_CLIENT_CREDENTIALS = "client_credentials";
private static final String AUTHENTICATION_URI = "https://login.live.com/accesstoken.srf";
private String sid;
private String clientSecret;
private WnsOAuthToken token;
private Client client;
/**
* @param sid
* @param clientSecret
* @throws WnsException when authentication fails
*/
public WnsService(String sid, String clientSecret) throws WnsException {
this.sid = sid;
this.clientSecret = clientSecret;
this.client = createClient();
this.token = getAccessToken();
}
// TODO: optional logging
private static Client createClient() {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
client.addFilter(new LoggingFilter(System.out));
return client;
}
protected WnsOAuthToken getAccessToken() throws WnsException {
WebResource webResource = this.client.resource(AUTHENTICATION_URI);
MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
formData.add("grant_type", GRANT_TYPE_CLIENT_CREDENTIALS);
formData.add("client_id", this.sid);
formData.add("client_secret", this.clientSecret);
formData.add("scope", SCOPE);
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, formData);
if (response.getStatus() != 200) {
throw new WnsException("Authentication failed. HTTP error code: " + response.getStatus());
}
return response.getEntity(WnsOAuthToken.class);
}
public WnsNotificationResponse pushTile(String channelUri, WnsTile tile) throws WnsException {
return this.push(channelUri, WnsNotificationType.TILE, tile);
}
public WnsNotificationResponse pushToast(String channelUri, WnsToast toast) throws WnsException {
return this.push(channelUri, WnsNotificationType.TOAST, toast);
}
public WnsNotificationResponse pushBadge(String channelUri, WnsBadge badge) throws WnsException {
return this.push(channelUri, WnsNotificationType.BADGE, badge);
}
// TODO: add push methods with optional request parameters from http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx#send_notification_request
// TODO: add description of response codes to WnsException from http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx#send_notification_response
protected WnsNotificationResponse push(String channelUri, String type, WnsAbstractNotification notification) throws WnsException {
WebResource webResource = this.client.resource(channelUri);
ClientResponse response = webResource.type(MediaType.TEXT_XML)
.header("X-WNS-Type", type)
.header("Authorization", "Bearer " + this.token.access_token)
.post(ClientResponse.class, notification);
WnsNotificationResponse notificationResponse = new WnsNotificationResponse(response.getStatus(), response.getHeaders());
if (notificationResponse.code == 200) {
return notificationResponse;
}
if (notificationResponse.code == 401) {
// Access token may have expired
this.token = getAccessToken();
// Retry
return this.push(channelUri, type, notification);
// TODO: implement retry policy
} else {
throw new WnsException("Push failed. HTTP error code: " + response.getStatus());
}
}
} |
package br.jus.trf2.balcaovirtual;
import java.lang.reflect.Type;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.crivano.swaggerservlet.SwaggerUtils;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import br.jus.cnj.intercomunicacao_2_2.ModalidadePoloProcessual;
import br.jus.cnj.intercomunicacao_2_2.ModalidadeRelacionamentoProcessual;
import br.jus.cnj.intercomunicacao_2_2.ModalidadeRepresentanteProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoAvisoComunicacaoPendente;
import br.jus.cnj.intercomunicacao_2_2.TipoCabecalhoProcesso;
import br.jus.cnj.intercomunicacao_2_2.TipoComunicacaoProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoDocumento;
import br.jus.cnj.intercomunicacao_2_2.TipoParametro;
import br.jus.cnj.intercomunicacao_2_2.TipoParte;
import br.jus.cnj.intercomunicacao_2_2.TipoPessoa;
import br.jus.cnj.intercomunicacao_2_2.TipoPoloProcessual;
import br.jus.cnj.intercomunicacao_2_2.TipoProcessoJudicial;
import br.jus.cnj.intercomunicacao_2_2.TipoQualificacaoPessoa;
import br.jus.cnj.intercomunicacao_2_2.TipoRepresentanteProcessual;
import br.jus.cnj.servico_intercomunicacao_2_2.ServicoIntercomunicacao222;
import br.jus.cnj.servico_intercomunicacao_2_2.ServicoIntercomunicacao222_Service;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.Aviso;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.ListStatus;
import br.jus.trf2.balcaovirtual.IBalcaoVirtual.ProcessoNumeroAvisoIdReceberPostResponse;
import br.jus.trf2.balcaovirtual.SessionsCreatePost.Usuario;
public class SoapMNI {
private static final DateTimeFormatter dtfMNI = DateTimeFormat.forPattern("yyyyMMddHHmmss");
private static final DateTimeFormatter dtfBR = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
// private static final DateTimeFormatter dtfFILE =
// DateTimeFormat.forPattern("yyyy-MM-dd-HH-mm");
private static class ConsultaProcessualExclStrat implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
public boolean shouldSkipField(FieldAttributes f) {
return f.getName().equals("endereco");
}
}
private static class OutroParametroSerializer implements JsonSerializer<List<TipoParametro>> {
@Override
public JsonElement serialize(List<TipoParametro> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject object = new JsonObject();
for (TipoParametro p : src) {
String nome = p.getNome();
String valor = p.getValor();
if (object.has(nome)) {
if (object.get(nome).isJsonArray()) {
object.getAsJsonArray(nome).add(valor);
} else {
JsonArray a = new JsonArray();
a.add(object.get(nome).getAsString());
a.add(valor);
object.add(nome, a);
}
} else
object.addProperty(nome, valor);
}
return object;
}
}
public static String consultarProcesso(String idManif, String orgao, String numProc) throws Exception {
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<TipoProcessoJudicial> processo = new Holder<>();
Map<String, Object> requestContext = ((BindingProvider) client).getRequestContext();
requestContext.put("javax.xml.ws.client.receiveTimeout", "3600000");
requestContext.put("javax.xml.ws.client.connectionTimeout", "5000");
client.consultarProcesso(idManif, null, numProc, null, true, true, true, null, sucesso, mensagem, processo);
if (!sucesso.value)
throw new Exception(mensagem.value);
Type collectionType = new TypeToken<List<TipoParametro>>() {
}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(collectionType, new OutroParametroSerializer())
.setExclusionStrategies(new ConsultaProcessualExclStrat()).create();
return gson.toJson(processo);
}
public static byte[] obterPecaProcessual(String idManif, String orgao, String numProc, String documento)
throws Exception {
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<TipoProcessoJudicial> processo = new Holder<>();
List<String> l = new ArrayList<>();
l.add(documento);
client.consultarProcesso(idManif, null, numProc, null, false, false, false, l, sucesso, mensagem, processo);
if (!sucesso.value)
throw new Exception(mensagem.value);
return processo.value.getDocumento().get(0).getConteudo();
}
public static void consultarAvisosPendentes(String idConsultante, List<Aviso> list, List<ListStatus> status)
throws Exception {
Usuario u = SessionsCreatePost.assertUsuario();
for (String orgao : Utils.getOrgaos().split(",")) {
String system = orgao.toLowerCase();
if (!u.usuarios.containsKey(system))
continue;
URL url = new URL(Utils.getMniWsdlUrl(system));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<List<TipoAvisoComunicacaoPendente>> aviso = new Holder<>();
ListStatus ls = new ListStatus();
ls.system = system;
status.add(ls);
Map<String, Object> requestContext = ((BindingProvider) client).getRequestContext();
requestContext.put("javax.xml.ws.client.receiveTimeout", "3600000");
requestContext.put("javax.xml.ws.client.connectionTimeout", "5000");
try {
client.consultarAvisosPendentes(null, idConsultante, null, null, sucesso, mensagem, aviso);
if (!sucesso.value)
throw new Exception(mensagem.value);
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Erro obtendo a lista de {}", system, ex);
ls.errormsg = SwaggerUtils.messageAsString(ex);
ls.stacktrace = SwaggerUtils.stackAsString(ex);
}
if (aviso != null && aviso.value != null) {
for (TipoAvisoComunicacaoPendente a : aviso.value) {
Aviso i = new Aviso();
switch (a.getTipoComunicacao()) {
case "INT":
i.tipo = "Intimação";
break;
case "CIT":
i.tipo = "Citação";
break;
}
i.processo = a.getProcesso().getNumero();
i.dataaviso = Utils.parsearApoloDataHoraMinuto(a.getDataDisponibilizacao());
i.idaviso = a.getIdAviso();
i.orgao = orgao;
i.unidade = a.getProcesso().getOrgaoJulgador().getCodigoOrgao();
i.unidadenome = a.getProcesso().getOrgaoJulgador().getNomeOrgao();
if (a.getProcesso().getAssunto() != null && a.getProcesso().getAssunto().size() > 0
&& a.getProcesso().getAssunto().get(0) != null
&& a.getProcesso().getAssunto().get(0).getCodigoNacional() != null)
i.assunto = a.getProcesso().getAssunto().get(0).getCodigoNacional().toString();
for (TipoParametro p : a.getProcesso().getOutroParametro()) {
if (p.getNome().equals("tipoOrgaoJulgador"))
i.unidadetipo = p.getValor();
if (p.getNome().equals("dtLimitIntimAut"))
i.datalimiteintimacaoautomatica = Utils.parsearApoloDataHoraMinuto(p.getValor());
if (p.getNome().equals("eventoIntimacao"))
i.eventointimacao = p.getValor();
if (p.getNome().equals("numeroPrazo"))
i.numeroprazo = p.getValor();
if (p.getNome().equals("tipoPrazo"))
i.tipoprazo = p.getValor();
if (p.getNome().equals("multiplicadorPrazo"))
i.multiplicadorprazo = p.getValor();
if (p.getNome().equals("motivoIntimacao"))
i.motivointimacao = p.getValor();
}
i.localidade = a.getProcesso().getCodigoLocalidade();
list.add(i);
}
}
}
}
public static void consultarTeorComunicacao(String idConsultante, String numProc, String idAviso, String orgao,
ProcessoNumeroAvisoIdReceberPostResponse resp) throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
String numProcFormated = Utils.formatarNumeroProcesso(numProc);
String system = orgao.toLowerCase();
URL url = new URL(Utils.getMniWsdlUrl(system));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<List<TipoComunicacaoProcessual>> comunicacao = new Holder<>();
client.consultarTeorComunicacao(idConsultante, idAviso, null, null, sucesso, mensagem, comunicacao);
if (!sucesso.value)
throw new Exception(mensagem.value);
if (comunicacao.value.size() != 1)
throw new Exception("Número de comunicações deve ser exatamente igual a 1");
TipoComunicacaoProcessual c = comunicacao.value.get(0);
if (c.getTipoComunicacao() != null)
switch (c.getTipoComunicacao()) {
case "INT":
resp.tipo = "Intimação";
break;
case "CIT":
resp.tipo = "Citação";
break;
default:
resp.tipo = "Aviso";
}
resp.processo = numProc;
resp.dataaviso = c.getDataReferencia();
resp.idaviso = idAviso;
resp.orgao = orgao;
resp.teor = c.getTeor();
// byte[] pdf = null;
// if (c.getDocumento() != null && c.getDocumento().size() > 0)
// pdf = c.getDocumento().get(0).getConteudo();
DateTime dt = DateTime.parse(c.getDataReferencia(), dtfMNI);
boolean sent = false;
boolean sigilo = c.getNivelSigilo() != null ? c.getNivelSigilo() != 0 : true;
if (email != null) {
email = "renato.crivano@gmail.com";
try {
String assunto = "Balcão Virtual: Confirmação de " + resp.tipo;
String conteudo = "Prezado(a) " + nome + ",\n\nAcusamos a confirmação de " + resp.tipo.toLowerCase()
+ " conforme dados abaixo:" + "\n\nProcesso Número: " + numProcFormated.replace("/", "")
+ "\nData/Hora de Término do Prazo: " + dt.toString(dtfBR) + "\nSigilo: "
+ (sigilo ? "Sim" : "Não") + "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
// String nomeArquivo = numProcFormated + "-" +
// Utils.removeAcento(resp.tipo).toLowerCase() + "-"
// + dt.toString(dtfFILE) + ".pdf";
// if (sigilo)
Correio.enviar(email, assunto, conteudo, null, null, null);
// else
// Correio.enviar(email, assunto, conteudo, nomeArquivo,
// "application/pdf", pdf);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class).warn("*** Processo: " + numProcFormated + " Aviso confirmado: " + resp.idaviso
+ " Por: " + usuario + " Email: " + email + (sent ? "" : " (email não enviado)"));
}
public static String enviarPeticaoIntercorrente(String idManif, String orgao, String numProc, String tpDoc,
int nvlSigilo, String nomePdfs, byte pdf[]) throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
if (nomePdfs == null && pdf == null)
throw new Exception("Não é possível peticionar sem que seja fornecido um PDF");
String numProcFormated = Utils.formatarNumeroProcesso(numProc);
String dataEnvio = new DateTime(new Date()).toString("yyyyMMddHHmmss");
String dirFinal = Utils.getDirFinal();
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
List<TipoDocumento> l = new ArrayList<>();
if (nomePdfs != null) {
for (String nomePdf : nomePdfs.split(",")) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(nvlSigilo == 0 ? 0 : 5);
doc.setTipoDocumento(tpDoc);
Path path = Paths.get(dirFinal + "/" + nomePdf + ".pdf");
byte[] data = Files.readAllBytes(path);
doc.setConteudo(data);
l.add(doc);
}
}
if (pdf != null) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(0);
doc.setTipoDocumento(tpDoc);
doc.setConteudo(pdf);
l.add(doc);
}
TipoCabecalhoProcesso dadosBasicos = new TipoCabecalhoProcesso();
dadosBasicos.setCodigoLocalidade("1");
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<String> protocoloRecebimento = new Holder<>();
Holder<String> dataOperacao = new Holder<>();
Holder<byte[]> recibo = new Holder<>();
Holder<List<TipoParametro>> parametro = new Holder<>();
client.entregarManifestacaoProcessual(idManif, null, numProc, null, l, dataEnvio,
new ArrayList<TipoParametro>(), sucesso, mensagem, protocoloRecebimento, dataOperacao, recibo,
parametro);
if (!sucesso.value)
throw new Exception(mensagem.value);
DateTime dt = DateTime.parse(dataOperacao.value, dtfMNI);
boolean sent = false;
if (email != null) {
try {
String conteudo = "Prezado(a) " + nome
+ ",\n\nAcusamos o recebimento da petição intercorrente conforme dados abaixo:"
+ "\n\nProcesso Número: " + numProcFormated + "\nProtocolo: " + protocoloRecebimento.value
+ "\nData/Hora do Protocolo: " + dt.toString(dtfBR)
+ "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
Correio.enviar(email, "Balcão Virtual: Protocolo de Recebimento", conteudo,
numProcFormated + "-protocolo-" + protocoloRecebimento.value + ".pdf", "application/pdf",
recibo.value);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class)
.warn("*** Processo: " + numProcFormated + " Petição Intercorrente protocolada: "
+ protocoloRecebimento.value + " Por: " + usuario + " Email: " + email
+ (sent ? "" : " (email não enviado)"));
return "Protocolo: " + protocoloRecebimento.value + ", Data: " + dt.toString(dtfBR)
+ (sent ? "" : " (email não enviado)");
}
public static class Parte {
int polo; // 1=Ativo, 2=Passivo
int tipopessoa; // 1=PF, 2=PJ, 3=Entidade, 4=Advogado
String documento;
String nome;
}
public static String enviarPeticaoInicial(String idManif, String orgao, String localidade, String especialidade,
String classe, double valorCausa, String cdas, String pas, int nvlSigilo, boolean justicagratuita,
boolean tutelaantecipada, boolean prioridadeidoso, List<Parte> partes, String nomePdfs, String tpDocPdfs)
throws Exception {
Map<String, Object> jwt = SessionsCreatePost.assertUsuarioAutorizado();
String email = (String) jwt.get("email");
String nome = (String) jwt.get("name");
String usuario = (String) jwt.get("username");
String dataEnvio = new DateTime(new Date()).toString("yyyyMMddHHmmss");
String dirFinal = Utils.getDirFinal();
URL url = new URL(Utils.getMniWsdlUrl(orgao));
ServicoIntercomunicacao222_Service service = new ServicoIntercomunicacao222_Service(url);
ServicoIntercomunicacao222 client = service.getServicoIntercomunicacao222SOAP();
List<TipoDocumento> l = new ArrayList<>();
// String tpDocs[] = tpDocPdfs.split(",");
int i = 0;
String classificacoes[] = tpDocPdfs.split(",");
for (String nomePdf : nomePdfs.split(",")) {
TipoDocumento doc = new TipoDocumento();
doc.setMimetype("application/pdf");
doc.setDataHora(dataEnvio);
doc.setNivelSigilo(nvlSigilo);
// doc.setTipoDocumento(tpDocs[i]);
Path path = Paths.get(dirFinal + "/" + nomePdf + ".pdf");
byte[] data = Files.readAllBytes(path);
doc.setConteudo(data);
TipoParametro classificacao = new TipoParametro();
classificacao.setNome("classificacao");
classificacao.setValor(classificacoes[i]);
doc.getOutroParametro().add(classificacao);
l.add(doc);
i++;
}
TipoCabecalhoProcesso dadosBasicos = new TipoCabecalhoProcesso();
TipoParte tp = null;
for (Parte parte : partes) {
ModalidadePoloProcessual m = parte.polo == 1 ? ModalidadePoloProcessual.AT : ModalidadePoloProcessual.PA;
TipoPoloProcessual tpp = null;
for (TipoPoloProcessual itpp : dadosBasicos.getPolo()) {
if (itpp.getPolo().equals(m)) {
tpp = itpp;
break;
}
}
if (tpp == null) {
tpp = new TipoPoloProcessual();
tpp.setPolo(m);
dadosBasicos.getPolo().add(tpp);
}
TipoQualificacaoPessoa tqp = null;
switch (parte.tipopessoa) {
case 1:
tqp = TipoQualificacaoPessoa.FISICA;
break;
case 2:
tqp = TipoQualificacaoPessoa.JURIDICA;
break;
case 3:
tqp = TipoQualificacaoPessoa.JURIDICA;
break;
case 4:
if (tp == null)
throw new Exception("Não há pessoa para vincular ao advogado");
TipoRepresentanteProcessual rp = new TipoRepresentanteProcessual();
rp.setNome(parte.nome);
rp.setInscricao(Utils.removePontuacao(parte.documento));
rp.setTipoRepresentante(ModalidadeRepresentanteProcessual.A);
// rp.setNumeroDocumentoPrincipal("11111111111");
// rp.setIntimacao(false);
tp.getAdvogado().add(rp);
tqp = TipoQualificacaoPessoa.ORGAOREPRESENTACAO;
continue;
}
tp = new TipoParte();
// if (justicagratuita && tqp == TipoQualificacaoPessoa.FISICA)
// tp.setAssistenciaJudiciaria(true);
tp.setRelacionamentoProcessual(ModalidadeRelacionamentoProcessual.RP);
TipoPessoa pess = new TipoPessoa();
pess.setNome(parte.nome);
pess.setNumeroDocumentoPrincipal(Utils.removePontuacao(parte.documento));
// pess.setCidadeNatural("Rio de Janeiro");
// pess.setEstadoNatural("RJ");
pess.setTipoPessoa(tqp);
tp.setPessoa(pess);
tpp.getParte().add(tp);
}
dadosBasicos.setCodigoLocalidade(localidade);
// dadosBasicos.setClasseProcessual(20);
dadosBasicos.setValorCausa(valorCausa);
List<TipoParametro> parametros = dadosBasicos.getOutroParametro();// new
// ArrayList<TipoParametro>();
// Apolo
String aClasse[] = classe.split("\\|");
dadosBasicos.setClasseProcessual(Integer.parseInt(aClasse[0]));
if (aClasse.length == 2) {
TipoParametro p = new TipoParametro();
p.setNome("CLASSEINTERNA");
p.setValor(aClasse[1]);
parametros.add(p);
}
if (prioridadeidoso) {
dadosBasicos.getPrioridade().add("IDOSO");
}
if (justicagratuita) {
TipoParametro jg = new TipoParametro();
jg.setNome("JUSTICAGRATUITA");
jg.setValor("TRUE");
parametros.add(jg);
}
if (justicagratuita) {
TipoParametro jg = new TipoParametro();
jg.setNome("JUSTICAGRATUITA");
jg.setValor("TRUE");
parametros.add(jg);
}
if (tutelaantecipada) {
TipoParametro tla = new TipoParametro();
tla.setNome("TUTELAANTECIPADA");
tla.setValor("TRUE");
parametros.add(tla);
}
if (cdas != null) {
for (String s : cdas.split(",")) {
String ss = Utils.removePontuacao(s).trim();
if (ss.length() == 0)
continue;
TipoParametro cda = new TipoParametro();
cda.setNome("NUMEROCDA");
cda.setValor(ss);
parametros.add(cda);
}
}
if (pas != null) {
for (String s : pas.split(",")) {
String ss = Utils.removePontuacao(s).trim();
if (ss.length() == 0)
continue;
TipoParametro pa = new TipoParametro();
pa.setNome("NUMEROPROCESSOADMINISTRATIVO");
pa.setValor(ss);
parametros.add(pa);
}
}
Holder<Boolean> sucesso = new Holder<>();
Holder<String> mensagem = new Holder<>();
Holder<String> protocoloRecebimento = new Holder<>();
Holder<String> dataOperacao = new Holder<>();
Holder<byte[]> recibo = new Holder<>();
Holder<List<TipoParametro>> parametro = new Holder<>();
client.entregarManifestacaoProcessual(idManif, null, null, dadosBasicos, l, dataEnvio, parametros, sucesso,
mensagem, protocoloRecebimento, dataOperacao, recibo, parametro);
if (!sucesso.value)
throw new Exception(mensagem.value);
DateTime dt = DateTime.parse(dataOperacao.value, dtfMNI);
boolean sent = false;
String numProcFormated = "?";
if (email != null) {
try {
String conteudo = "Prezado(a) " + nome
+ ",\n\nAcusamos o recebimento da petição inicial conforme dados abaixo:"
+ "\n\nProcesso Autuado Número: " + numProcFormated + "\nProtocolo: "
+ protocoloRecebimento.value + "\nData/Hora do Protocolo: " + dt.toString(dtfBR)
+ "\n\nAtenciosamente,\n\nTribunal Regional Federal da 2a Região";
Correio.enviar(email, "Balcão Virtual: Protocolo de Recebimento", conteudo,
numProcFormated + "-protocolo-" + protocoloRecebimento.value + ".pdf", "application/pdf",
recibo.value);
sent = true;
} catch (Exception ex) {
SwaggerUtils.log(SoapMNI.class).error("Email não enviado", ex);
}
}
SwaggerUtils.log(SoapMNI.class)
.warn("*** Processo: " + numProcFormated + " Petição Inicial protocolada: " + protocoloRecebimento.value
+ " Por: " + usuario + " Email: " + email + (sent ? "" : " (email não enviado)"));
return "Protocolo: " + protocoloRecebimento.value + ", Data: " + dt.toString(dtfBR)
+ (sent ? "" : " (email não enviado)");
}
} |
package checkdep.common;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import jdepend.framework.JavaPackage;
import checkdep.value.depend.Dependencies;
import checkdep.value.depend.Dependency;
import checkdep.value.depend.PackageName;
public class JDependDependency implements Dependency {
private final JavaPackage raw;
public JDependDependency(JavaPackage raw) {
this.raw = raw;
}
@Override
public PackageName getName() {
return new PackageName(raw.getName());
}
@Override
public Set<PackageName> getEfferents() {
Set<PackageName> res = new LinkedHashSet<PackageName>();
@SuppressWarnings("unchecked")
Collection<JavaPackage> efferents = raw.getEfferents();
for (JavaPackage efferent : efferents) {
res.add(new PackageName(efferent.getName()));
}
return res;
}
public static Dependencies toDependencies(Collection<JavaPackage> packages) {
Set<Dependency> res = new LinkedHashSet<Dependency>();
for (JavaPackage item : packages) {
res.add(new JDependDependency(item));
}
return Dependencies.of(res);
}
} |
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.GdxSnippets;
import java.nio.LongBuffer;
/**
* Extension to Gdx.gl30 which adds functions and constants not available to OpenGL ES, and
* therefore not exposed through the libGDX interface.
*/
public final class GL33Ext {
public static final int GL_TEXTURE_BORDER_COLOR = 0x1004;
public static final int GL_POINT = 0x1B00;
public static final int GL_LINE = 0x1B01;
public static final int GL_FILL = 0x1B02;
public static final int GL_CLAMP_TO_BORDER = 0x812D;
public static final int GL_CLIP_DISTANCE0 = 0x3000;
public static final int GL_CLIP_DISTANCE1 = 0x3001;
public static final int GL_CLIP_DISTANCE2 = 0x3002;
public static final int GL_CLIP_DISTANCE3 = 0x3003;
public static final int GL_CLIP_DISTANCE4 = 0x3004;
public static final int GL_CLIP_DISTANCE5 = 0x3005;
public static final int GL_CLIP_DISTANCE6 = 0x3006;
public static final int GL_CLIP_DISTANCE7 = 0x3007;
public static final int GL_INTERNALFORMAT_SUPPORTED = 0x826F;
public static final int GL_INTERNALFORMAT_PREFERRED = 0x8270;
public static void glBlendEquationi(int buffer, int mode) {
if (!Gdx.graphics.supportsExtension("GL_ARB_draw_buffers_blend")) {
GdxSnippets.log.warn("Extension ARB_draw_buffers_blend not supported!");
}
nglBlendEquationi(buffer, mode);
}
public static void glGetInternalFormativ(int target, int internalformat, int pname, LongBuffer params) {
if (!Gdx.graphics.supportsExtension("GL_ARB_internalformat_query2")) {
GdxSnippets.log.warn("Extension ARB_internalformat_query2 not supported!");
}
nglGetInternalFormati64v(target, internalformat, pname, params.capacity(), params);
}
// @off
/*JNI
#include "flextGL.h"
*/
public static native void glBindFragDataLocation(int program, int colorNumber, String name); /*
glBindFragDataLocation(program, colorNumber, name);
*/
private static native void nglBlendEquationi(int buffer, int mode); /*
if (FLEXT_ARB_draw_buffers_blend) {
glpfBlendEquationiARB(buffer, mode);
}
*/
public static native void glDrawElementsBaseVertex(int mode, int count, int type, int indices, int baseVertex); /*
glDrawElementsBaseVertex(mode, count, type, (const void*) ((size_t) indices), baseVertex);
*/
private static native void nglGetInternalFormati64v(int target, int internalformat,
int pname, int bufSize, LongBuffer params); /*
if (FLEXT_ARB_internalformat_query2) {
glGetInternalformati64v(target, internalformat, pname, bufSize, (GLint64*) params);
}
*/
public static native void glPolygonMode(int face, int mode); /*
glPolygonMode(face, mode);
*/
} |
package com.bloatit.model.data;
import java.util.NoSuchElementException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.util.Version;
import org.hibernate.metadata.ClassMetadata;
import com.bloatit.common.PageIterable;
import com.bloatit.model.data.util.SessionManager;
public class DBRequests {
@SuppressWarnings("unchecked")
public static <T> T getById(Class<T> persistant, Integer id) {
return (T) SessionManager.getSessionFactory().getCurrentSession().get(persistant, id);
}
public static <T> PageIterable<T> getAll(Class<T> persistent) {
final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(persistent);
return new QueryCollection<T>("from " + meta.getEntityName());
}
public static <T> int count(Class<T> persistent) {
final ClassMetadata meta = SessionManager.getSessionFactory().getClassMetadata(persistent);
return ((Long) SessionManager.getSessionFactory().getCurrentSession()
.createQuery("select count(*) from " + meta.getEntityName()).uniqueResult()).intValue();
}
public static PageIterable<DaoDemand> searchDemands(String searchStr) {
return search(DaoDemand.class, new String[] { "description.translations.title", "description.translations.text",
"offers.description.translations.title" }, searchStr);
}
/**
* Create a search on the db using Hibernate Search and Lucene
*
* @param <T> is a persistent class (something like Dao...)
* @param persistent is the class object associated with T.
* @param fields is a list of field on which we are doing the search. These
* field are relative to the persistent class.
* @param searchStr is the string we are looking for.
* @return a PageIterable with the search results.
*/
private static <T> PageIterable<T> search(Class<T> persistent, String[] fields, String searchStr) {
MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_29, fields, new StandardAnalyzer(
Version.LUCENE_29));
try {
org.apache.lucene.search.Query query = parser.parse(searchStr);
return new SearchCollection<T>(SessionManager.getCurrentFullTextSession().createFullTextQuery(query, persistent));
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static PageIterable<DaoDemand> DemandsOrderByPopularity() {
return demandsOrderBy("popularity");
}
public static PageIterable<DaoDemand> DemandsOrderByContribution() {
return demandsOrderBy("contribution");
}
public static PageIterable<DaoDemand> DemandsOrderByDate() {
return demandsOrderBy("creationDate");
}
private static PageIterable<DaoDemand> demandsOrderBy(String field) {
return new QueryCollection<DaoDemand>("from DaoDemand where state == PENDING order by " + field);
}
// By kudosable
// by near end
// by date
// by contrib
} |
package com.eqt.tfi.index;
import java.io.IOException;
import org.apache.blur.mapreduce.lib.BaseBlurMapper;
import org.apache.blur.mapreduce.lib.BlurOutputFormat;
import org.apache.blur.mapreduce.lib.BlurRecord;
import org.apache.blur.mapreduce.lib.BlurMutate.MUTATE_TYPE;
import org.apache.blur.thirdparty.thrift_0_9_0.TException;
import org.apache.blur.thrift.BlurClient;
import org.apache.blur.thrift.generated.BlurException;
import org.apache.blur.thrift.generated.ColumnDefinition;
import org.apache.blur.thrift.generated.TableDescriptor;
import org.apache.blur.thrift.generated.Blur.Iface;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/**
* Example MR indexer, will create a table if it doesn't exist, then index into the thing.
* Any files picked up (text files only) will be indexed line for line into blur.
* @author gman
*/
public class TextFileIndexer {
/*
* This mapper will get a single file, so recordID will be line position.
* rowid will be random gibberish since this is an example after all!
*/
public static class TextMapper extends BaseBlurMapper<Text, Text> {
@Override
protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
//grab a handle on the reusable blur record writable
BlurRecord record = _mutate.getRecord();
//clean it out
record.clearColumns();
//set the master/primary key of the blur record. Think of this as a RDBMS PK
record.setRowId(System.currentTimeMillis()+"");
//set the child/secondary key of the record id. Think of this as an RDBMS child tables PK.
record.setRecordId(key.toString());
//set family name, equivalent of RDBMS child table name
record.setFamily("content");
//add column name, equivalent of RDBMS child table column name.
record.addColumn("data", value.toString());
//setup MR output key
_key.set(record.getRowId());
//we will replace what existed before.
_mutate.setMutateType(MUTATE_TYPE.REPLACE);
//send record to reducer for indexing
context.write(_key, _mutate);
//counters are fun.
_recordCounter.increment(1);
_columnCounter.increment(1);
context.progress();
}
}
/**
* @param args input path to index. expects plain text files.
* @throws InterruptedException
* @throws IOException
* @throws ClassNotFoundException
* @throws TException
* @throws BlurException
*/
public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException, BlurException, TException {
GenericOptionsParser p = new GenericOptionsParser(args);
Configuration conf = p.getConfiguration();
String[] otherArgs = p.getRemainingArgs();
//grab a handle to talk to blur, assuming single local instance.
Iface client = BlurClient.getClient("localhost:40010");
//the table we will mess with
String tableName = "textExampleTable";
//ask blur about the table
TableDescriptor td = null;
//if blur says 'what table?'
if(!client.tableList().contains(tableName)) {
//lets make a table.
td = new TableDescriptor();
td.enabled = true; //so we can use it
td.shardCount = 1; //were testing here, just need 1.
td.name = tableName;//what we call this thing
td.readOnly = false;//wont hurt letting us mod it via the client api
//we aren't using this because I assume a single cluster, and blur will default to it.
//td.cluster
//we are not setting this because you set blur.cluster.default.table.uri right?
//td.tableUri
//'this table blur!'
client.createTable(td);
//just for example purposes, this is how to specify how to index a column using a built in blur indexer.
client.addColumnDefinition(tableName,
//this says, family:content, column:data, no sub index, no full text, "text" indexer, no extra props
new ColumnDefinition("content", "data", null, false, "text", null));
} else {
td = client.describe(tableName);
}
Job job = Job.getInstance(conf, "Index Text Data");
job.setJarByClass(TextFileIndexer.class);
Path inputPath = new Path(otherArgs[0]);
job.setInputFormatClass(TextInputFormat.class);
FileInputFormat.addInputPath(job, inputPath);
//This handles the reducer setting, output types, output path normal in a MR job.
BlurOutputFormat.setupJob(job, td);
//blur indexes at the reducer before copying to the final blur location.
BlurOutputFormat.setIndexLocally(job, true);
//Lucene optimize operation triggered when blur copies from local index dir to final dir.
BlurOutputFormat.setOptimizeInFlight(job, true);
job.waitForCompletion(true);
}
} |
package com.gamingmesh.jobs.container;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.CMILib.CMIMaterial;
import com.gamingmesh.jobs.resources.jfep.Parser;
import com.gamingmesh.jobs.stuff.ChatColor;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import java.util.function.BiPredicate;
public class Job {
private EnumMap<ActionType, List<JobInfo>> jobInfo = new EnumMap<>(ActionType.class);
private List<JobPermission> jobPermissions;
private List<JobCommands> jobCommands;
private List<JobConditions> jobConditions;
private HashMap<String, JobItems> jobItems;
private HashMap<String, JobLimitedItems> jobLimitedItems;
private String jobName = "N/A";
private String fullName = "N/A";
// job short name (for use in multiple jobs)
private String jobShortName;
private String description;
private ChatColor jobColour;
private Parser maxExpEquation;
private DisplayMethod displayMethod;
private int maxLevel;
private int vipmaxLevel = 0;
// max number of people allowed with this job on the server.
private Integer maxSlots;
private List<String> CmdOnJoin = new ArrayList<>();
private List<String> CmdOnLeave = new ArrayList<>();
private ItemStack GUIitem;
private Long rejoinCd = 0L;
private int totalPlayers = -1;
private Double bonus = null;
private BoostMultiplier boost = new BoostMultiplier();
private String bossbar;
private Parser moneyEquation, xpEquation, pointsEquation;
private List<String> fDescription = new ArrayList<>();
private List<String> worldBlacklist = new ArrayList<>();
private List<Quest> quests = new ArrayList<>();
private int maxDailyQuests = 1;
private int id = 0;
public Job(String jobName, String fullName, String jobShortName, String description, ChatColor jobColour, Parser maxExpEquation, DisplayMethod displayMethod, int maxLevel,
int vipmaxLevel, Integer maxSlots, List<JobPermission> jobPermissions, List<JobCommands> jobCommands, List<JobConditions> jobConditions, HashMap<String, JobItems> jobItems,
HashMap<String, JobLimitedItems> jobLimitedItems, List<String> CmdOnJoin, List<String> CmdOnLeave, ItemStack GUIitem, String bossbar, Long rejoinCD, List<String> worldBlacklist) {
this.jobName = jobName == null ? "" : jobName;
this.fullName = fullName == null ? "" : fullName;
this.jobShortName = jobShortName;
this.description = description;
this.jobColour = jobColour;
this.maxExpEquation = maxExpEquation;
this.displayMethod = displayMethod;
this.maxLevel = maxLevel;
this.vipmaxLevel = vipmaxLevel;
this.maxSlots = maxSlots;
this.jobPermissions = jobPermissions;
this.jobCommands = jobCommands;
this.jobConditions = jobConditions;
this.jobItems = jobItems;
this.jobLimitedItems = jobLimitedItems;
this.CmdOnJoin = CmdOnJoin;
this.CmdOnLeave = CmdOnLeave;
this.GUIitem = GUIitem;
this.bossbar = bossbar;
this.rejoinCd = rejoinCD;
this.worldBlacklist = worldBlacklist;
}
public void addBoost(CurrencyType type, double Point) {
boost.add(type, Point);
}
public void addBoost(CurrencyType type, double point, int hour, int minute, int second) {
final Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) + hour);
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + minute);
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + second);
long time = cal.getTimeInMillis();
boost.add(type, point, time);
}
public void setBoost(BoostMultiplier BM) {
this.boost = BM;
}
public BoostMultiplier getBoost() {
return boost;
}
public boolean isSame(Job job) {
if (job == null)
return false;
return this.getName().equalsIgnoreCase(job.getName());
}
public int getTotalPlayers() {
if (totalPlayers == -1) {
updateTotalPlayers();
}
return totalPlayers;
}
public void updateTotalPlayers() {
this.totalPlayers = Jobs.getJobsDAO().getTotalPlayerAmountByJobName(this.jobName);
updateBonus();
}
public void updateBonus() {
if (!Jobs.getGCManager().useDynamicPayment)
return;
Parser eq = Jobs.getGCManager().DynamicPaymentEquation;
eq.setVariable("totalworkers", Jobs.getJobsDAO().getTotalPlayers());
eq.setVariable("totaljobs", Jobs.getJobs().size());
eq.setVariable("jobstotalplayers", getTotalPlayers());
double now = eq.getValue();
if (now > Jobs.getGCManager().DynamicPaymentMaxBonus)
now = Jobs.getGCManager().DynamicPaymentMaxBonus;
if (now < Jobs.getGCManager().DynamicPaymentMaxPenalty * -1)
now = Jobs.getGCManager().DynamicPaymentMaxPenalty * -1;
this.bonus = (now / 100D);
}
public double getBonus() {
if (this.bonus == null)
updateBonus();
return this.bonus == null ? 0D : this.bonus;
}
public List<String> getCmdOnJoin() {
return CmdOnJoin;
}
public List<String> getCmdOnLeave() {
return CmdOnLeave;
}
public ItemStack getGuiItem() {
return GUIitem;
}
/**
* Sets job info for action type
* @param type - The action type
* @param info - the job info
*/
public void setJobInfo(ActionType type, List<JobInfo> info) {
jobInfo.put(type, info);
}
/**
* Gets the job info for the particular type
* @param type - The action type
* @return Job info list
*/
public List<JobInfo> getJobInfo(ActionType type) {
return jobInfo.get(type);
}
/**
* Gets the job info list
* @return Job info list
*/
public EnumMap<ActionType, List<JobInfo>> getJobInfoList() {
return jobInfo;
}
public JobInfo getJobInfo(ActionInfo action, int level) {
BiPredicate<JobInfo, ActionInfo> condition = (jobInfo, actionInfo) -> {
return jobInfo.getName().equalsIgnoreCase(action.getNameWithSub()) ||
(jobInfo.getName() + ":" + jobInfo.getMeta()).equalsIgnoreCase(action.getNameWithSub()) ||
jobInfo.getName().equalsIgnoreCase(action.getName());
};
String shortActionName = CMIMaterial.getGeneralMaterialName(action.getName());
for (JobInfo info : getJobInfo(action.getType())) {
if (condition.test(info, action)) {
if (!info.isInLevelRange(level)) {
break;
}
return info;
}
if ((shortActionName + ":ALL").equalsIgnoreCase(info.getName())) {
return info;
}
}
return null;
}
/**
* Get the job name
* @return the job name
*/
public String getName() {
return fullName;
}
/**
* Get the job name from the config
* @return the job name from the config
*/
public String getJobKeyName() {
return jobName;
}
/**
* Get the shortened version of the jobName
* @return the shortened version of the jobName
*/
public String getShortName() {
return jobShortName;
}
/**
* Gets the description
* @return description
*/
public String getDescription() {
return description;
}
/**
* Get the Color of the job for chat
* @return the Color of the job for chat
*/
public ChatColor getChatColor() {
return jobColour;
}
/**
* Get the MaxExpEquation of the job
* @return the MaxExpEquation of the job
*/
public Parser getMaxExpEquation() {
return maxExpEquation;
}
/**
* Function to return the appropriate max exp for this level
* @param level - current level
* @return the correct max exp for this level
*/
public double getMaxExp(Map<String, Double> level) {
for (Map.Entry<String, Double> temp : level.entrySet()) {
maxExpEquation.setVariable(temp.getKey(), temp.getValue());
}
return maxExpEquation.getValue();
}
/**
* Function to get the display method
* @return the display method
*/
public DisplayMethod getDisplayMethod() {
return displayMethod;
}
/**
* Function to return the maximum level
* @return the max level
* @return null - no max level
*/
public int getMaxLevel() {
return maxLevel;
}
public int getMaxLevel(JobsPlayer player) {
if (player == null)
return getMaxLevel();
return player.getMaxJobLevelAllowed(this);
}
public int getMaxLevel(CommandSender sender) {
if (sender == null)
return getMaxLevel();
if (sender instanceof Player) {
JobsPlayer player = Jobs.getPlayerManager().getJobsPlayer((Player) sender);
if (player != null)
return player.getMaxJobLevelAllowed(this);
}
return getMaxLevel() > getVipMaxLevel() ? getMaxLevel() : getVipMaxLevel();
}
/**
* Function to return the maximum level
* @return the max level
* @return null - no max level
*/
public int getVipMaxLevel() {
return vipmaxLevel;
}
/**
* Function to return the maximum slots
* @return the max slots
* @return null - no max slots
*/
public Integer getMaxSlots() {
return maxSlots;
}
public List<JobPermission> getPermissions() {
return Collections.unmodifiableList(jobPermissions);
}
/**
* Get the command nodes for this job
* @return Commands for this job
*/
public List<JobCommands> getCommands() {
return Collections.unmodifiableList(jobCommands);
}
/**
* Get the conditions for this job
* @return Conditions for this job
*/
public List<JobConditions> getConditions() {
return Collections.unmodifiableList(jobConditions);
}
/**
* Get the item nodes for this job
* @return Items for this job
*/
@Deprecated
public HashMap<String, JobItems> getItemBonus() {
if (jobItems == null)
jobItems = new HashMap<String, JobItems>();
return jobItems;
}
@Deprecated
public JobItems getItemBonus(String key) {
return jobItems.get(key.toLowerCase());
}
/**
* Get the limited item nodes for this job
* @return Limited items for this job
*/
public HashMap<String, JobLimitedItems> getLimitedItems() {
return jobLimitedItems;
}
public JobLimitedItems getLimitedItems(String key) {
return jobLimitedItems.get(key.toLowerCase());
}
public String getBossbar() {
return bossbar;
}
public void setBossbar(String bossbar) {
this.bossbar = bossbar;
}
public Parser getMoneyEquation() {
return moneyEquation;
}
public void setMoneyEquation(Parser moneyEquation) {
this.moneyEquation = moneyEquation;
}
public Parser getXpEquation() {
return xpEquation;
}
public void setXpEquation(Parser xpEquation) {
this.xpEquation = xpEquation;
}
public Parser getPointsEquation() {
return pointsEquation;
}
public void setPointsEquation(Parser pointsEquation) {
this.pointsEquation = pointsEquation;
}
public Long getRejoinCd() {
return rejoinCd;
}
public void setRejoinCd(Long rejoinCd) {
this.rejoinCd = rejoinCd;
}
public List<String> getFullDescription() {
return fDescription;
}
public void setFullDescription(List<String> fDescription) {
this.fDescription = fDescription;
}
public List<Quest> getQuests() {
return quests;
}
public Quest getQuest(String name) {
if (name == null || name.trim().isEmpty()) {
return null;
}
for (Quest one : quests) {
if (one.getConfigName().equalsIgnoreCase(name))
return one;
}
return null;
}
public void setQuests(List<Quest> quests) {
this.quests.clear();
this.quests = quests;
}
// public Quest getNextQuest() {
// return getNextQuest(null, null);
public Quest getNextQuest(List<String> excludeQuests, Integer level) {
List<Quest> ls = new ArrayList<>(this.quests);
Collections.shuffle(ls);
int i = 0;
while (true) {
i++;
Random rand = new Random(System.nanoTime());
int target = rand.nextInt(100);
for (Quest one : ls) {
if (one.getChance() >= target)
if (excludeQuests == null || !excludeQuests.contains(one.getConfigName().toLowerCase())) {
if (!one.isInLevelRange(level))
continue;
return one;
}
}
if (i > 20)
return null;
}
}
public int getMaxDailyQuests() {
return maxDailyQuests;
}
public void setMaxDailyQuests(int maxDailyQuests) {
this.maxDailyQuests = maxDailyQuests;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
if (id != 0)
Jobs.getJobsIds().put(id, this);
}
public List<String> getWorldBlacklist() {
return worldBlacklist;
}
public boolean isWorldBlackListed(Entity ent) {
return isWorldBlackListed(null, ent);
}
public boolean isWorldBlackListed(Block block) {
return isWorldBlackListed(block, null);
}
public boolean isWorldBlackListed(Block block, Entity ent) {
if (worldBlacklist.isEmpty())
return false;
if (block != null && worldBlacklist.contains(block.getWorld().getName()))
return true;
if (ent != null && worldBlacklist.contains(ent.getWorld().getName()))
return true;
return false;
}
} |
// WARNING: This code is auto-generated from the BaseCRM API Discovery JSON Schema
package com.getbase.services;
import com.getbase.http.HttpClient;
import com.getbase.models.User;
import com.getbase.serializer.JsonDeserializer;
import com.getbase.utils.Joiner;
import java.util.*;
import static com.getbase.utils.Lists.asList;
import static com.getbase.utils.Precondition.checkArgument;
public class UsersService extends BaseService {
public UsersService(HttpClient httpClient) {
super(httpClient);
}
public List<User> list(Map<String, Object> params) {
String url = "/v2/users";
return JsonDeserializer.deserializeList(this.httpClient.get(url, params).getBody(), User.class);
}
public List<User> list(SearchCriteria criteria) {
return list(criteria.asMap());
}
public User get(long id) {
checkArgument(id > 0, "id must be a valid id");
String url = String.format(Locale.US, "/v2/users/%d", id);
return JsonDeserializer.deserialize(this.httpClient.get(url, null).getBody(), User.class);
}
public User self() {
return JsonDeserializer.deserialize(this.httpClient.get("/v2/users/self", null).getBody(), User.class);
}
public static class SearchCriteria {
private Map<String, Object> queryParams;
public SearchCriteria() {
this.queryParams = new HashMap<String, Object>();
}
public SearchCriteria page(long page) {
queryParams.put("page", page);
return this;
}
public SearchCriteria perPage(long perPage) {
queryParams.put("per_page", perPage);
return this;
}
public SearchCriteria sortBy(String criteria, String order) {
queryParams.put("sort_by", criteria + ":" + order);
return this;
}
public SearchCriteria sortBy(String criteria) {
return sortBy(criteria, "asc");
}
public SearchCriteria ids(List<Long> ids) {
queryParams.put("ids", Joiner.join(",", ids));
return this;
}
public SearchCriteria ids(Long... ids) {
return ids(asList(ids));
}
public SearchCriteria confirmed(boolean confirmed) {
queryParams.put("confirmed", confirmed);
return this;
}
public SearchCriteria email(String email) {
queryParams.put("email", email);
return this;
}
public SearchCriteria name(String name) {
queryParams.put("name", name);
return this;
}
public SearchCriteria role(String role) {
queryParams.put("role", role);
return this;
}
public SearchCriteria status(String status) {
queryParams.put("status", status);
return this;
}
public SearchCriteria zendeskUserIds(List<Long> ids) {
queryParams.put("zendesk_user_ids", Joiner.join(",", ids));
return this;
}
public SearchCriteria zendeskUserIds(Long... ids) {
return zendeskUserIds(asList(ids));
}
public Map<String, Object> asMap() {
return Collections.unmodifiableMap(queryParams);
}
}
} |
package com.github.davidmoten.rtree;
import static com.google.common.base.Optional.absent;
import static com.google.common.base.Optional.of;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.geometry.Rectangle;
import com.github.davidmoten.rx.operators.OperatorBoundedPriorityQueue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
/**
* Immutable in-memory 2D R-Tree with configurable splitter heuristic.
*
* @param <R>
* the entry type
*/
public final class RTree<R> {
private final Optional<? extends Node<R>> root;
private final Context context;
/**
* Benchmarks show that this is a good choice for up to O(10,000) entries
* when using Quadratic splitter (Guttman).
*/
public static final int MAX_CHILDREN_DEFAULT_GUTTMAN = 4;
/**
* Benchmarks show that this is the sweet spot for up to O(10,000) entries
* when using R*-tree heuristics.
*/
public static final int MAX_CHILDREN_DEFAULT_STAR = 10;
private int size;
/**
* Constructor.
*
* @param root
* the root node of the tree if present
* @param context
* options for the R-tree
*/
private RTree(Optional<? extends Node<R>> root, int size, Context context) {
this.root = root;
this.size = size;
this.context = context;
}
/**
* Constructor.
*
* @param root
* the root node of the R-tree
* @param context
* options for the R-tree
*/
private RTree(Node<R> root, int size, Context context) {
this(of(root), size, context);
}
/**
* Constructor.
*
* @param context
* specifies parameters and behaviour for the R-tree
*/
public RTree(Context context) {
this(Optional.<Node<R>> absent(), 0, context);
}
/**
* Returns a new Builder instance for {@link RTree}. Defaults to
* maxChildren=128, minChildren=64, splitter=QuadraticSplitter.
*
* @return a new RTree instance
*/
public static <T> RTree<T> create() {
return new Builder().create();
}
/**
* The tree is scanned for depth and the depth returned. This involves
* recursing down to the leaf level of the tree to get the current depth.
* Should be <code>log(n)</code> in complexity.
*
* @return
*/
public int calculateDepth() {
return calculateDepth(root);
}
private static <R> int calculateDepth(Optional<? extends Node<R>> root) {
if (!root.isPresent())
return 0;
else
return calculateDepth(root.get(), 0);
}
private static <R> int calculateDepth(Node<R> node, int depth) {
if (node instanceof Leaf)
return depth + 1;
else
return calculateDepth(((NonLeaf<R>) node).children().get(0), depth + 1);
}
public static Builder minChildren(int minChildren) {
return new Builder().minChildren(minChildren);
}
/**
* Sets the max number of children in an R-tree node.
*
* @param maxChildren
* max number of children in an R-tree node
* @return builder
*/
public static Builder maxChildren(int maxChildren) {
return new Builder().maxChildren(maxChildren);
}
/**
* Sets the {@link Splitter} to use when maxChildren is reached.
*
* @param splitter
* the splitter algorithm to use
* @return builder
*/
public static Builder splitter(Splitter splitter) {
return new Builder().splitter(splitter);
}
/**
* Sets the node {@link Selector} which decides which branches to follow
* when inserting or searching.
*
* @param selector
* @return builder
*/
public static Builder selector(Selector selector) {
return new Builder().selector(selector);
}
/**
* Sets the splitter to {@link SplitterRStar} and selector to
* {@link SelectorRStar} and defaults to minChildren=10.
*
* @return builder
*/
public static Builder star() {
return new Builder().star();
}
/**
* RTree Builder.
*/
public static class Builder {
private static final double DEFAULT_FILLING_FACTOR = 0.4;
private Optional<Integer> maxChildren = absent();
private Optional<Integer> minChildren = absent();
private Splitter splitter = new SplitterQuadratic();
private Selector selector = new SelectorMinimalAreaIncrease();
private boolean star = false;
private Builder() {
}
public Builder minChildren(int minChildren) {
this.minChildren = of(minChildren);
return this;
}
/**
* Sets the max number of children in an R-tree node.
*
* @param maxChildren
* max number of children in R-tree node.
* @return builder
*/
public Builder maxChildren(int maxChildren) {
this.maxChildren = of(maxChildren);
return this;
}
/**
* Sets the {@link Splitter} to use when maxChildren is reached.
*
* @param splitter
* node splitting method to use
* @return builder
*/
public Builder splitter(Splitter splitter) {
this.splitter = splitter;
return this;
}
/**
* Sets the node {@link Selector} which decides which branches to follow
* when inserting or searching.
*
* @param selector
* @return builder
*/
public <T> Builder selector(Selector selector) {
this.selector = selector;
return this;
}
/**
* Sets the splitter to {@link SplitterRStar} and selector to
* {@link SelectorRStar} and defaults to minChildren=10.
*
* @return builder
*/
public Builder star() {
selector = new SelectorRStar();
splitter = new SplitterRStar();
star = true;
return this;
}
/**
* Builds the {@link RTree}.
*
* @param <S>
* the entry type
* @return RTree
*/
public <S> RTree<S> create() {
if (!maxChildren.isPresent())
if (star)
maxChildren = of(MAX_CHILDREN_DEFAULT_STAR);
else
maxChildren = of(MAX_CHILDREN_DEFAULT_GUTTMAN);
if (!minChildren.isPresent())
minChildren = of((int) Math.round(maxChildren.get() * DEFAULT_FILLING_FACTOR));
return new RTree<S>(new Context(minChildren.get(), maxChildren.get(), selector,
splitter));
}
}
/**
* Adds an entry to the R-tree.
*
* @param entry
* item to add to the R-tree.
* @return a new immutable R-tree including the new entry
*/
@SuppressWarnings("unchecked")
public RTree<R> add(Entry<R> entry) {
if (root.isPresent()) {
List<Node<R>> nodes = root.get().add(entry);
Node<R> node;
if (nodes.size() == 1)
node = nodes.get(0);
else {
node = new NonLeaf<R>(nodes, context);
}
return new RTree<R>(node, size + 1, context);
} else
return new RTree<R>(new Leaf<R>(Lists.newArrayList(entry), context), size + 1, context);
}
/**
* Adds an entry comprised of the given value and Geometry.
*
* @param value
* the value of the {@link Entry} to be added
* @param geometry
* the geometry of the {@link Entry} to be added
* @return a new immutable R-tree including the new entry
*/
public RTree<R> add(R value, Geometry geometry) {
return add(Entry.entry(value, geometry));
}
/**
* Returns a new R-tree with the current entries and the additional entries
* supplied as a parameter.
*
* @param entries
* entries to add
* @return R-tree with entries added
*/
public RTree<R> add(Iterable<Entry<R>> entries) {
RTree<R> tree = this;
for (Entry<R> entry : entries)
tree = tree.add(entry);
return tree;
}
public Observable<RTree<R>> add(Observable<Entry<R>> entries) {
return entries.scan(this, new Func2<RTree<R>, Entry<R>, RTree<R>>() {
@Override
public RTree<R> call(RTree<R> tree, Entry<R> entry) {
return tree.add(entry);
}
});
}
public Observable<RTree<R>> delete(Observable<Entry<R>> entries, final boolean all) {
return entries.scan(this, new Func2<RTree<R>, Entry<R>, RTree<R>>() {
@Override
public RTree<R> call(RTree<R> tree, Entry<R> entry) {
return tree.delete(entry, all);
}
});
}
/**
* Returns a new R-tree with the given entries deleted.
*
* @param entries
* entries to delete
* @return R-tree with entries deleted
*/
public RTree<R> delete(Iterable<Entry<R>> entries, boolean all) {
RTree<R> tree = this;
for (Entry<R> entry : entries)
tree = tree.delete(entry, all);
return tree;
}
/**
* Delete one entry comprised of the given value and Geometry. This method
* has no effect if the entry is not present. The entry must match on both
* value and geometry to be deleted.
*
* @param value
* the value of the {@link Entry} to be deleted
* @param geometry
* the geometry of the {@link Entry} to be deleted
* @return a new immutable R-tree without one instance of the specified
* entry
*/
public RTree<R> delete(R value, Geometry geometry, boolean all) {
return delete(Entry.entry(value, geometry), all);
}
public RTree<R> delete(R value, Geometry geometry) {
return delete(Entry.entry(value, geometry), false);
}
/**
* Delete one entry if it exists. If multiple copies of the entry are in the
* R-tree only one will be deleted. The entry must match on both value and
* geometry to be deleted.
*
* @param entry
* the {@link Entry} to be deleted
* @return a new immutable R-tree without one instance of the specified
* entry
*/
public RTree<R> delete(Entry<R> entry, boolean all) {
if (root.isPresent()) {
NodeAndEntries<R> nodeAndEntries = root.get().delete(entry, all);
if (nodeAndEntries.node().isPresent() && nodeAndEntries.node().get() == root.get())
return this;
else
return new RTree<R>(nodeAndEntries.node(), size - nodeAndEntries.countDeleted()
- nodeAndEntries.entriesToAdd().size(), context).add(nodeAndEntries
.entriesToAdd());
} else
return this;
}
public RTree<R> delete(Entry<R> entry) {
return delete(entry, false);
}
public RTree<R> delete(Iterable<Entry<R>> entries) {
RTree<R> tree = this;
for (Entry<R> entry : entries)
tree = tree.delete(entry);
return tree;
}
/**
* <p>
* Returns an Observable sequence of {@link Entry} that satisfy the given
* condition. Note that this method is well-behaved only if:
* </p>
*
* <code>condition(g) is true for {@link Geometry} g implies condition(r) is true for the minimum bounding rectangles of the ancestor nodes</code>
*
* <p>
* <code>distance(g) < sD</code> is an example of such a condition.
* </p>
*
* @param condition
* return Entries whose geometry satisfies the given condition
* @return sequence of matching entries
*/
@VisibleForTesting
Observable<Entry<R>> search(Func1<? super Geometry, Boolean> condition) {
if (root.isPresent())
return Observable.create(new OnSubscribeSearch<R>(root.get(), condition));
else
return Observable.empty();
}
/**
* Returns a predicate function that indicates if {@link Geometry}
* intersects with a given rectangle.
*
* @param r
* the rectangle to check intersection with
* @return whether the geometry and the rectangle intersect
*/
public static Func1<Geometry, Boolean> intersects(final Rectangle r) {
return new Func1<Geometry, Boolean>() {
@Override
public Boolean call(Geometry g) {
return g.intersects(r);
}
};
}
/**
* Returns the always true predicate. See {@link RTree#entries()} for
* example use.
*/
private static final Func1<Geometry, Boolean> ALWAYS_TRUE = new Func1<Geometry, Boolean>() {
@Override
public Boolean call(Geometry rectangle) {
return true;
}
};
/**
* Returns an {@link Observable} sequence of all {@link Entry}s in the
* R-tree whose minimum bounding rectangle intersects with the given
* rectangle.
*
* @param r
* rectangle to check intersection with the entry mbr
* @return entries that intersect with the rectangle r
*/
public Observable<Entry<R>> search(final Rectangle r) {
return search(intersects(r));
}
/**
* Returns an {@link Observable} sequence of all {@link Entry}s in the
* R-tree whose minimum bounding rectangles are within maxDistance from the
* given rectangle.
*
* @param r
* rectangle to measure distance from
* @param maxDistance
* entries returned must be within this distance from rectangle r
* @return the sequence of matching entries
*/
public Observable<Entry<R>> search(final Rectangle r, final double maxDistance) {
return search(new Func1<Geometry, Boolean>() {
@Override
public Boolean call(Geometry g) {
return g.distance(r) < maxDistance;
}
});
}
/**
* Returns the nearest k entries (k=maxCount) to the given rectangle where
* the entries are within a given maximum distance from the rectangle.
*
* @param r
* rectangle
* @param maxDistance
* max distance of returned entries from the rectangle
* @param maxCount
* max number of entries to return
* @return nearest entries to maxCount, not in any particular order
*/
public Observable<Entry<R>> nearest(final Rectangle r, final double maxDistance, int maxCount) {
return search(r, maxDistance).lift(
new OperatorBoundedPriorityQueue<Entry<R>>(maxCount, Comparators
.<R> ascendingDistance(r)));
}
/**
* Returns all entries in the tree as an {@link Observable} sequence.
*
* @return all entries in the R-tree
*/
public Observable<Entry<R>> entries() {
return search(ALWAYS_TRUE);
}
/**
* Returns a {@link Visualizer} for an image of given width and height and
* restricted to the given view of the coordinates. The points in the view
* are scaled to match the aspect ratio defined by the width and height.
*
* @param width
* of the image in pixels
* @param height
* of the image in pixels
* @param view
* using the coordinate system of the entries
* @return visualizer
*/
public Visualizer visualize(int width, int height, Rectangle view) {
return new Visualizer(this, width, height, view);
}
/**
* Returns a {@link Visualizer} for an image of given width and height and
* restricted to the the smallest view that fully contains the coordinates.
* The points in the view are scaled to match the aspect ratio defined by
* the width and height.
*
* @param width
* of the image in pixels
* @param height
* of the image in pixels
* @return visualizer
*/
public Visualizer visualize(int width, int height) {
return visualize(width, height, calculateMaxView(this));
}
private Rectangle calculateMaxView(RTree<R> tree) {
return tree
.entries()
.reduce(Optional.<Rectangle> absent(),
new Func2<Optional<Rectangle>, Entry<R>, Optional<Rectangle>>() {
@Override
public Optional<Rectangle> call(Optional<Rectangle> r, Entry<R> entry) {
if (r.isPresent())
return of(r.get().add(entry.geometry().mbr()));
else
return of(entry.geometry().mbr());
}
}).toBlocking().single().or(new Rectangle(0, 0, 0, 0));
}
Optional<? extends Node<R>> root() {
return root;
}
/**
* Returns true if and only if the R-tree is empty of entries.
*
* @return is R-tree empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the number of entries in the RTree.
*
* @return the number of entries
*/
public int size() {
return size;
}
/**
* Returns a {@link Context} containing the configuration of the RTree at
* the time of instantiation.
*
* @return the configuration of the RTree prior to instantiation
*/
public Context context() {
return context;
}
} |
package com.humegatech.inliner;
import java.nio.charset.Charset;
import org.apache.commons.lang.StringUtils;
import com.phloc.css.ECSSVersion;
import com.phloc.css.ICSSWriterSettings;
import com.phloc.css.decl.CSSDeclaration;
import com.phloc.css.decl.CSSSelector;
import com.phloc.css.decl.CSSStyleRule;
import com.phloc.css.decl.CascadingStyleSheet;
import com.phloc.css.reader.CSSReader;
import com.phloc.css.writer.CSSWriterSettings;
public class CssInliner {
private static final Charset CHARSET = Charset.forName("UTF-8");
private static final ECSSVersion CSS_VERSION = ECSSVersion.CSS30;
// Using 0, but value doesn't matter for us since we're not indenting (or
// supporting indented CSS yet)
private static final int INDENT_LEVEL = 0;
// list of elements -- probably move this out to another class eventually
// and turn into enum
private static final String CLASS_SELECTOR = ".";
private static final String ID_SELECTOR = "
/*
* Passing true for the second parameter causes the writer to strip all
* whitespace from the output: perfect for inlining
*/
private static final ICSSWriterSettings WRITER_SETTINGS = new CSSWriterSettings(ECSSVersion.CSS30, true);
/**
* Will take CSS and a class selector and will produce the css inlined
*
* @param css
* CSS
* @param cssClassSelector
* class for which to inline the css
* @return String representing inlined css
*/
public static String inlineCssClass(final String css, final String cssClassSelector) {
final String classDeclarations = getDeclarationsForClassSelector(cssClassSelector, css);
return (StringUtils.isNotBlank(classDeclarations) ? classDeclarations : null);
}
/**
* Will take CSS and an id selector and will produce a tag the css inlined
*
* @param css
* CSS
* @param cssIdSelector
* id for which to inline the css
* @return String representing inlined css
*/
public static String inlineCssId(final String css, final String cssIdSelector) {
final String idDeclarations = getDeclarationsForIdSelector(cssIdSelector, css);
return (StringUtils.isNotBlank(idDeclarations) ? idDeclarations : "");
}
protected static CascadingStyleSheet parseCss(final String css) {
final CascadingStyleSheet aCss = CSSReader.readFromString(css, CHARSET, CSS_VERSION);
return aCss;
}
/**
* Return the declarations for a CSS class selector as a String suitable for
* inlining (newlines, extra spaces, etc. removed). Assumes '.' starts class
* selector name so will append it if missing.
*
* @param classSelectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
protected static String getDeclarationsForClassSelector(final String classSelectorName, final String css) {
final String localClassSelectorName = formatSelector(CLASS_SELECTOR, classSelectorName);
return getDeclarations(localClassSelectorName, css);
}
/**
* Return the declarations for a CSS id selector as a String suitable for
* inlining (newlines, extra spaces, etc. removed). Assumes '#' starts id
* selector name so will append it if missing.
*
* @param idSelectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
protected static String getDeclarationsForIdSelector(final String idSelectorName, final String css) {
final String localIdSelectorName = formatSelector(ID_SELECTOR, idSelectorName);
return getDeclarations(localIdSelectorName, css);
}
/**
* Return the declarations for a CSS inlining (newlines, extra spaces, etc. removed).
*
* @param selectorName
* CSS selector element name
* @param css
* CSS document
* @return declarations for selector stripped of whitespace
*/
private static String getDeclarations(final String selectorName, final String css) {
String declarationString = "";
for (final CSSStyleRule styleRule : parseCss(css).getAllStyleRules()) {
for (final CSSSelector selector : styleRule.getAllSelectors()) {
if (selector.getAsCSSString(WRITER_SETTINGS, INDENT_LEVEL).equalsIgnoreCase(selectorName)) {
for (final CSSDeclaration declaration : styleRule.getAllDeclarations()) {
declarationString += declaration.getAsCSSString(WRITER_SETTINGS, INDENT_LEVEL) + ";";
}
break;
}
}
}
return declarationString;
}
private static String formatSelector(final String type, final String selectorName) {
return selectorName.startsWith(type) ? selectorName : type + selectorName;
}
} |
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.io;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ReflectPermission;
import java.util.Date;
import java.util.Map;
import com.google.common.collect.Maps;
import static com.threerings.NaryaLog.log;
/**
* Used to read and write a single field of a {@link Streamable} instance.
*/
public abstract class FieldMarshaller
{
public FieldMarshaller ()
{
this(null);
}
public FieldMarshaller (String type)
{
_type = type;
}
/**
* Reads the contents of the supplied field from the supplied stream and sets it in the
* supplied object.
*/
public abstract void readField (Field field, Object target, ObjectInputStream in)
throws Exception;
/**
* Writes the contents of the supplied field in the supplied object to the supplied stream.
*/
public abstract void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception;
@Override
public String toString ()
{
if (_type != null) {
return "FieldMarshaller " + _type;
}
return super.toString();
}
protected final String _type;
/**
* Returns a field marshaller appropriate for the supplied field or null if no marshaller
* exists for the type contained by the field in question.
*/
public static FieldMarshaller getFieldMarshaller (Field field)
{
if (_marshallers == null) {
// multiple threads may attempt to create the stock marshallers, but they'll just do
// extra work and _marshallers will only ever contain a fully populated table
_marshallers = createMarshallers();
}
// if necessary (we're running in a sandbox), look for custom field accessors
if (useFieldAccessors()) {
Method reader = null, writer = null;
try {
reader = field.getDeclaringClass().getMethod(
getReaderMethodName(field.getName()), READER_ARGS);
} catch (NoSuchMethodException nsme) {
// no problem
}
try {
writer = field.getDeclaringClass().getMethod(
getWriterMethodName(field.getName()), WRITER_ARGS);
} catch (NoSuchMethodException nsme) {
// no problem
}
if (reader != null && writer != null) {
return new MethodFieldMarshaller(reader, writer);
}
if ((reader == null && writer != null) || (writer == null && reader != null)) {
log.warning("Class contains one but not both custom field reader and writer",
"class", field.getDeclaringClass().getName(), "field", field.getName(),
"reader", reader, "writer", writer);
// fall through to using reflection on the fields...
}
}
Class<?> ftype = field.getType();
// use the intern marshaller for pooled strings
if (ftype == String.class && field.isAnnotationPresent(Intern.class)) {
return _internMarshaller;
}
// if we have an exact match, use that
FieldMarshaller fm = _marshallers.get(ftype);
if (fm == null) {
Class<?> collClass = Streamer.getCollectionClass(ftype);
if (collClass != null && !collClass.equals(ftype)) {
log.warning("Specific field types are discouraged " +
"for Iterables/Collections and Maps. The implementation type may not be " +
"recreated on the other side.",
"class", field.getDeclaringClass(), "field", field.getName(),
"type", ftype, "shouldBe", collClass);
fm = _marshallers.get(collClass);
}
// otherwise if the class is a pure interface or streamable,
// use the streamable marshaller
if (fm == null && (ftype.isInterface() || Streamer.isStreamable(ftype))) {
fm = _marshallers.get(Streamable.class);
}
}
return fm;
}
/**
* Returns the name of the custom reader method which will be used if it exists to stream a
* field with the supplied name.
*/
public static final String getReaderMethodName (String field)
{
return "readField_" + field;
}
/**
* Returns the name of the custom writer method which will be used if it exists to stream a
* field with the supplied name.
*/
public static final String getWriterMethodName (String field)
{
return "writeField_" + field;
}
/**
* Returns true if we should use the generated field marshaller methods that allow us to work
* around our inability to read and write protected and private fields of a {@link Streamable}.
*/
protected static boolean useFieldAccessors ()
{
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(new ReflectPermission("suppressAccessChecks"));
}
return false;
} catch (SecurityException se) {
return true;
}
}
/**
* Used to marshall and unmarshall classes for which we have a basic {@link Streamer}.
*/
protected static class StreamerMarshaller extends FieldMarshaller
{
public StreamerMarshaller (Streamer streamer)
{
_streamer = streamer;
}
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception
{
if (in.readBoolean()) {
Object value = _streamer.createObject(in);
_streamer.readObject(value, in, true);
field.set(target, value);
} else {
field.set(target, null);
}
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception
{
Object value = field.get(source);
if (value == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
_streamer.writeObject(value, out, true);
}
}
@Override
public String toString ()
{
return "StreamerMarshaller:" + _streamer.toString();
}
/** The streamer we use to read and write our field. */
protected Streamer _streamer;
}
/**
* Uses custom accessor methods to read and write a field.
*/
protected static class MethodFieldMarshaller extends FieldMarshaller
{
public MethodFieldMarshaller (Method reader, Method writer)
{
_reader = reader;
_writer = writer;
}
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception
{
_reader.invoke(target, in);
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception
{
_writer.invoke(source, out);
}
protected Method _reader, _writer;
}
/**
* Creates and returns a mapping for all known field marshaller types.
*/
protected static Map<Class<?>, FieldMarshaller> createMarshallers ()
{
Map<Class<?>, FieldMarshaller> marshallers = Maps.newHashMap();
// create a generic marshaller for streamable instances
FieldMarshaller gmarsh = new FieldMarshaller("Generic") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, in.readObject());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeObject(field.get(source));
}
};
marshallers.put(Streamable.class, gmarsh);
// use the same generic marshaller for fields declared as Object with the expectation that
// they will contain only primitive types or Streamables; the runtime will fail
// informatively if we attempt to store non-Streamable objects in that field
marshallers.put(Object.class, gmarsh);
// create marshallers for the primitive types
marshallers.put(Boolean.TYPE, new FieldMarshaller("boolean") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setBoolean(target, in.readBoolean());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeBoolean(field.getBoolean(source));
}
});
marshallers.put(Byte.TYPE, new FieldMarshaller("byte") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setByte(target, in.readByte());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeByte(field.getByte(source));
}
});
marshallers.put(Character.TYPE, new FieldMarshaller("char") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setChar(target, in.readChar());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeChar(field.getChar(source));
}
});
marshallers.put(Short.TYPE, new FieldMarshaller("short") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setShort(target, in.readShort());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeShort(field.getShort(source));
}
});
marshallers.put(Integer.TYPE, new FieldMarshaller("int") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setInt(target, in.readInt());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeInt(field.getInt(source));
}
});
marshallers.put(Long.TYPE, new FieldMarshaller("long") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setLong(target, in.readLong());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeLong(field.getLong(source));
}
});
marshallers.put(Float.TYPE, new FieldMarshaller("float") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setFloat(target, in.readFloat());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeFloat(field.getFloat(source));
}
});
marshallers.put(Double.TYPE, new FieldMarshaller("double") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.setDouble(target, in.readDouble());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeDouble(field.getDouble(source));
}
});
marshallers.put(Date.class, new FieldMarshaller("Date") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, new Date(in.readLong()));
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeLong(((Date)field.get(source)).getTime());
}
});
// create field marshallers for all of the basic types
for (Map.Entry<Class<?>,Streamer> entry : BasicStreamers.BSTREAMERS.entrySet()) {
marshallers.put(entry.getKey(), new StreamerMarshaller(entry.getValue()));
}
// create the field marshaller for pooled strings
_internMarshaller = new FieldMarshaller("intern") {
@Override
public void readField (Field field, Object target, ObjectInputStream in)
throws Exception {
field.set(target, in.readIntern());
}
@Override
public void writeField (Field field, Object source, ObjectOutputStream out)
throws Exception {
out.writeIntern((String)field.get(source));
}
};
return marshallers;
}
/** Contains a mapping from field type to field marshaller instance for that type. */
protected static Map<Class<?>, FieldMarshaller> _marshallers;
/** The field marshaller for pooled strings. */
protected static FieldMarshaller _internMarshaller;
/** Defines the signature to a custom field reader method. */
protected static final Class<?>[] READER_ARGS = { ObjectInputStream.class };
/** Defines the signature to a custom field writer method. */
protected static final Class<?>[] WRITER_ARGS = { ObjectOutputStream.class };
} |
package cz.muni.fi.mias.indexing;
import cz.muni.fi.mias.PayloadSimilarity;
import cz.muni.fi.mias.Settings;
import cz.muni.fi.mias.indexing.doc.FileExtDocumentHandler;
import cz.muni.fi.mias.math.MathTokenizer;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/**
* Indexing class responsible for adding, updating and deleting files from index,
* creating, deleting whole index, printing statistics.
*
* @author Martin Liska
* @since 14.5.2010
*/
public class Indexing {
private static final Logger LOG = Logger.getLogger(Indexing.class.getName());
private File indexDir;
private Analyzer analyzer = new StandardAnalyzer();
private long docLimit = Settings.getDocLimit();
private long count = 0;
private long progress = 0;
private long fileProgress = 0;
private String storage;
private Date startTime;
/**
* Constructor creates Indexing instance. Directory with the index is taken from the Settings.
*
*/
public Indexing() {
this.indexDir = new File(Settings.getIndexDir());
}
/**
* Indexes files located in given input path.
* @param path Path to the documents directory. Can be a single file as well.
* @param rootDir A path in the @path parameter which is a root directory for the document storage. It determines the relative path
* the files will be index with.
*/
public void indexFiles(String path, String rootDir) {
storage = rootDir;
if (!storage.endsWith(File.separator)) {
storage += File.separator;
}
final File docDir = new File(path);
if (!docDir.exists() || !docDir.canRead()) {
LOG.severe("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path");
System.exit(1);
}
try {
startTime = new Date();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_45, analyzer);
PayloadSimilarity ps = new PayloadSimilarity();
ps.setDiscountOverlaps(false);
config.setSimilarity(ps);
config.setIndexDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir), config);
LOG.info("Getting list of documents to index.");
List<File> files = getDocs(docDir);
countFiles(files);
LOG.info("Number of documents to index is "+count);
indexDocsThreaded(files, writer);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private List<File> getDocs(File file) throws IOException {
List<File> result = new ArrayList<File>();
getDocs(result, file);
return result;
}
private List<File> getDocs(List<File> fileList, File file) {
if (file.canRead()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
getDocs(fileList, files[i]);
}
}
} else {
if (fileList.size() == docLimit) {
return fileList;
} else if (isFileIndexable(file)){
fileList.add(file);
}
}
}
return fileList;
}
private void indexDocsThreaded(List<File> files, IndexWriter writer) {
try {
Iterator<File> it = files.iterator();
ExecutorService executor = Executors.newFixedThreadPool(Settings.getNumThreads());
Future[] tasks = new Future[Settings.getNumThreads()];
int running = 0;
while (it.hasNext() || running > 0) {
for (int i = 0; i < tasks.length; i++) {
if (tasks[i] == null && it.hasNext()) {
File f = it.next();
String path = resolvePath(f);
Callable callable = new FileExtDocumentHandler(f, path);
FutureTask ft = new FutureTask(callable);
tasks[i] = ft;
executor.execute(ft);
running++;
} else if (tasks[i] != null && tasks[i].isDone()) {
List<Document> docs = (List<Document>) tasks[i].get();
running
tasks[i] = null;
for (Document doc : docs) {
if (doc != null) {
if (progress % 10000 == 0) {
printTimes();
writer.commit();
}
try {
LOG.info("adding to index " + doc.get("path") + " docId=" + doc.get("id"));
writer.updateDocument(new Term("id", doc.get("id")), doc);
LOG.info("Documents indexed: " + (++progress));
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Document '" + doc.get("path") + "' indexing failed: " + ex.getMessage(), ex);
}
}
}
LOG.info("File progress: " + (++fileProgress) + " of " + count + " done...");
}
}
}
printTimes();
executor.shutdown();
} catch (IOException ex) {
Logger.getLogger(Indexing.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(Indexing.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Indexing.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Optimizes the index.
*/
public void optimize() {
try {
startTime = new Date();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
config.setIndexDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir), config);
// writer.optimize();
writer.close();
Date end = new Date();
System.out.println("Optimizing time: "+ (end.getTime()-startTime.getTime())+" ms");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* Deletes whole current index directory
*/
public void deleteIndexDir() {
deleteDir(indexDir);
}
private void deleteDir(File f) {
if (f.exists()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDir(files[i]);
} else {
files[i].delete();
}
}
f.delete();
}
}
/**
* Deletes files located in given path from the index
*
* @param path Path of the files to be deleted
*/
public void deleteFiles(String path) {
final File docDir = new File(path);
if (!docDir.exists() || !docDir.canRead()) {
System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path");
System.exit(1);
}
try {
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
config.setIndexDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
IndexWriter writer = new IndexWriter(FSDirectory.open(indexDir), config);
deleteDocs(writer, docDir);
writer.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
private void deleteDocs(IndexWriter writer, File file) throws IOException {
if (file.canRead()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
deleteDocs(writer, files[i]);
}
}
} else {
System.out.println("deleting " + file.getAbsolutePath());
writer.deleteDocuments(new Term("path",resolvePath(file)));
}
}
}
/**
* Prints statistic about the current index
*/
public void getStats() {
String stats = "\nIndex statistics: \n\n";
DirectoryReader ir = null;
try {
ir = DirectoryReader.open(FSDirectory.open(indexDir));
stats += "Index directory: "+indexDir.getAbsolutePath() + "\n";
stats += "Number of indexed documents: " + ir.numDocs() + "\n";
long fileSize = 0;
for (int i = 0; i < ir.numDocs(); i++) {
Document doc = ir.document(i);
if (doc.getField("filesize")!=null) {
String size = doc.getField("filesize").stringValue();
fileSize += Long.valueOf(size);
}
}
long indexSize = 0;
File[] files = indexDir.listFiles();
for (File f : files) {
indexSize += f.length();
}
stats += "Index size: " + indexSize + " bytes \n";
stats += "Approximated size of indexed files: " + fileSize + " bytes \n";
System.out.println(stats);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (ir!=null) {
try {
ir.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
private String resolvePath(File file) throws IOException {
String path = file.getCanonicalPath();
return path.substring(storage.length());
}
private long getCpuTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long result = 0;
if (bean.isThreadCpuTimeSupported()) {
final long[] ids = bean.getAllThreadIds();
for (long id : ids) {
result += bean.getThreadCpuTime(id) / 1000000;
}
}
return result;
}
private long getUserTime() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long result = 0;
if (bean.isThreadCpuTimeSupported()) {
final long[] ids = bean.getAllThreadIds();
for (long id : ids) {
result += bean.getThreadUserTime(id) / 1000000;
}
}
return result;
}
private void printTimes() {
Date intermediate = new Date();
System.out.println("
System.out.println();
System.out.println(progress + " DONE in total time " + (intermediate.getTime() - startTime.getTime()) + " ms,");
System.out.println("CPU time " + (getCpuTime()) + " ms");
System.out.println("user time " + (getUserTime()) + " ms");
MathTokenizer.printFormulaeCount();
System.out.println();
}
private boolean isFileIndexable(File file) {
String path = file.getAbsolutePath();
String ext = path.substring(path.lastIndexOf(".") + 1);
if (ext.equals("html") || ext.equals("xhtml") || ext.equals("zip")) {
return true;
}
return false;
}
private void countFiles(List<File> files) {
if (docLimit > 0) {
count = Math.min(files.size(), docLimit);
} else {
count = files.size();
}
}
} |
package de.epiceric.shopchest.utils;
import de.epiceric.shopchest.ShopChest;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import javax.xml.bind.DatatypeConverter;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
public class Utils {
/**
* Gets the amount of items in an inventory
*
* @param inventory The inventory, in which the items are counted
* @param itemStack The items to count
* @return Amount of given items in the given inventory
*/
public static int getAmount(Inventory inventory, ItemStack itemStack) {
int amount = 0;
ArrayList<ItemStack> inventoryItems = new ArrayList<>();
if (inventory instanceof PlayerInventory) {
if (getMajorVersion() >= 9) {
inventoryItems.add(inventory.getItem(40));
}
for (int i = 0; i < 36; i++) {
inventoryItems.add(inventory.getItem(i));
}
} else {
for (int i = 0; i < inventory.getSize(); i++) {
inventoryItems.add(inventory.getItem(i));
}
}
for (ItemStack item : inventoryItems) {
if (item != null) {
if (item.isSimilar(itemStack)) {
amount += item.getAmount();
}
}
}
return amount;
}
/**
* Get the amount of the given item, that fits in the given inventory
*
* @param inventory Inventory, where to search for free space
* @param itemStack Item, of which the amount that fits in the inventory should be returned
* @return Amount of the given item, that fits in the given inventory
*/
public static int getFreeSpaceForItem(Inventory inventory, ItemStack itemStack) {
HashMap<Integer, Integer> slotFree = new HashMap<>();
if (inventory instanceof PlayerInventory) {
for (int i = 0; i < 36; i++) {
ItemStack item = inventory.getItem(i);
if (item == null) {
slotFree.put(i, itemStack.getMaxStackSize());
} else {
if (item.isSimilar(itemStack)) {
int amountInSlot = item.getAmount();
int amountToFullStack = itemStack.getMaxStackSize() - amountInSlot;
slotFree.put(i, amountToFullStack);
}
}
}
if (getMajorVersion() >= 9) {
ItemStack item = inventory.getItem(40);
if (item == null) {
slotFree.put(40, itemStack.getMaxStackSize());
} else {
if (item.isSimilar(itemStack)) {
int amountInSlot = item.getAmount();
int amountToFullStack = itemStack.getMaxStackSize() - amountInSlot;
slotFree.put(40, amountToFullStack);
}
}
}
} else {
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack item = inventory.getItem(i);
if (item == null) {
slotFree.put(i, itemStack.getMaxStackSize());
} else {
if (item.isSimilar(itemStack)) {
int amountInSlot = item.getAmount();
int amountToFullStack = itemStack.getMaxStackSize() - amountInSlot;
slotFree.put(i, amountToFullStack);
}
}
}
}
int freeAmount = 0;
for (int value : slotFree.values()) {
freeAmount += value;
}
return freeAmount;
}
/**
* @param p Player whose item in his main hand should be returned
* @return {@link ItemStack} in his main hand, or {@code null} if he doesn't hold one
*/
public static ItemStack getItemInMainHand(Player p) {
if (getMajorVersion() < 9) {
if (p.getItemInHand().getType() == Material.AIR)
return null;
else
return p.getItemInHand();
} else {
if (p.getInventory().getItemInMainHand().getType() == Material.AIR)
return null;
else
return p.getInventory().getItemInMainHand();
}
}
/**
* @param p Player whose item in his off hand should be returned
* @return {@link ItemStack} in his off hand, or {@code null} if he doesn't hold one or the server version is below 1.9
*/
public static ItemStack getItemInOffHand(Player p) {
if (getMajorVersion() < 9) {
return null;
} else {
if (p.getInventory().getItemInOffHand().getType() == Material.AIR)
return null;
else
return p.getInventory().getItemInOffHand();
}
}
/**
* @param p Player whose item in his hand should be returned
* @return Item in his main hand, or the item in his off if he doesn't have one in this main hand, or {@code null}
* if he doesn't have one in both hands
*/
public static ItemStack getPreferredItemInHand(Player p) {
if (getMajorVersion() < 9) {
return getItemInMainHand(p);
} else {
if (getItemInMainHand(p) != null)
return getItemInMainHand(p);
else
return getItemInOffHand(p);
}
}
/**
* @param className Name of the class
* @return Class in {@code net.minecraft.server.[VERSION]} package with the specified name or {@code null} if the class was not found
*/
public static Class<?> getNMSClass(String className) {
try {
return Class.forName("net.minecraft.server." + getServerVersion() + "." + className);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* @param className Name of the class
* @return Class in {@code org.bukkit.craftbukkit.[VERSION]} package with the specified name or {@code null} if the class was not found
*/
public static Class<?> getCraftClass(String className) {
try {
return Class.forName("org.bukkit.craftbukkit." + getServerVersion() + "." + className);
} catch (ClassNotFoundException e) {
return null;
}
}
/**
* Send a packet to a player
* @param packet Packet to send
* @param player Player to which the packet should be sent
* @return {@code true} if the packet was sent, or {@code false} if an exception was thrown
*/
public static boolean sendPacket(ShopChest plugin, Object packet, Player player) {
try {
if (packet == null) {
plugin.debug("Failed to send packet: Packet is null");
return false;
}
Class<?> packetClass = getNMSClass("Packet");
if (packetClass == null) {
plugin.debug("Failed to send packet: Could not find Packet class");
return false;
}
Object nmsPlayer = player.getClass().getMethod("getHandle").invoke(player);
Object playerConnection = nmsPlayer.getClass().getField("playerConnection").get(nmsPlayer);
playerConnection.getClass().getMethod("sendPacket", packetClass).invoke(playerConnection, packet);
return true;
} catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException | InvocationTargetException e) {
plugin.getLogger().severe("Failed to send packet " + packet.getClass().getName());
plugin.debug("Failed to send packet " + packet.getClass().getName());
plugin.debug(e);
return false;
}
}
/**
* @return The current server version with revision number (e.g. v1_9_R2, v1_10_R1)
*/
public static String getServerVersion() {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
/**
* @return The major version of the server (e.g. <i>9</i> for 1.9.2, <i>10</i> for 1.10)
*/
public static int getMajorVersion() {
return Integer.valueOf(getServerVersion().split("_")[1]);
}
/**
* Checks if a given String is a UUID
* @param string String to check
* @return Whether the string is a UUID
*/
public static boolean isUUID(String string) {
return string.matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}");
}
/**
* Encodes an {@link ItemStack} in a Base64 String
* @param itemStack {@link ItemStack} to encode
* @return Base64 encoded String
*/
public static String encode(ItemStack itemStack) {
YamlConfiguration config = new YamlConfiguration();
config.set("i", itemStack);
return DatatypeConverter.printBase64Binary(config.saveToString().getBytes(StandardCharsets.UTF_8));
}
/**
* Decodes an {@link ItemStack} from a Base64 String
* @param string Base64 encoded String to decode
* @return Decoded {@link ItemStack}
*/
public static ItemStack decode(String string) {
YamlConfiguration config = new YamlConfiguration();
try {
config.loadFromString(new String(DatatypeConverter.parseBase64Binary(string), StandardCharsets.UTF_8));
} catch (IllegalArgumentException | InvalidConfigurationException e) {
e.printStackTrace();
return null;
}
return config.getItemStack("i", null);
}
} |
package de.prob2.ui.dynamic.dotty;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import de.prob.animator.command.GetAllDotCommands;
import de.prob.animator.command.GetSvgForVisualizationCommand;
import de.prob.animator.domainobjects.ClassicalB;
import de.prob.animator.domainobjects.DynamicCommandItem;
import de.prob.animator.domainobjects.EvaluationException;
import de.prob.animator.domainobjects.FormulaExpand;
import de.prob.animator.domainobjects.IEvalElement;
import de.prob.exception.ProBError;
import de.prob.statespace.Trace;
import de.prob2.ui.dynamic.DynamicCommandStage;
import de.prob2.ui.helpsystem.HelpButton;
import de.prob2.ui.internal.StageManager;
import de.prob2.ui.preferences.GlobalPreferences;
import de.prob2.ui.preferences.PreferencesHandler;
import de.prob2.ui.preferences.ProBPreferences;
import de.prob2.ui.prob2fx.CurrentProject;
import de.prob2.ui.prob2fx.CurrentTrace;
import de.prob2.ui.project.MachineLoader;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.geometry.Orientation;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class DotView extends DynamicCommandStage {
private static final Logger LOGGER = LoggerFactory.getLogger(DotView.class);
@FXML
private WebView dotView;
@FXML
private Button zoomOutButton;
@FXML
private Button zoomInButton;
@FXML
private HBox zoomBox;
@FXML
private HelpButton helpButton;
private double oldMousePositionX = -1;
private double oldMousePositionY = -1;
private double dragFactor = 0.83;
@Inject
public DotView(final StageManager stageManager, final CurrentTrace currentTrace,
final CurrentProject currentProject, final ProBPreferences globalProBPrefs,
final GlobalPreferences globalPreferences,
final MachineLoader machineLoader, final PreferencesHandler preferencesHandler,
final ResourceBundle bundle, final Injector injector) {
super(stageManager, currentTrace, currentProject, globalProBPrefs, globalPreferences, machineLoader, preferencesHandler, bundle, injector);
stageManager.loadFXML(this, "dot_view.fxml");
}
@FXML
@Override
public void initialize() {
super.initialize();
helpButton.setHelpContent(this.getClass());
initializeZooming();
}
private void initializeZooming() {
dotView.setOnMouseMoved(e -> {
oldMousePositionX = e.getSceneX();
oldMousePositionY = e.getSceneY();
});
dotView.setOnMouseDragged(e -> {
pane.setHvalue(pane.getHvalue() + (-e.getSceneX() + oldMousePositionX) / (pane.getWidth() * dragFactor));
pane.setVvalue(pane.getVvalue() + (-e.getSceneY() + oldMousePositionY) / (pane.getHeight() * dragFactor));
oldMousePositionX = e.getSceneX();
oldMousePositionY = e.getSceneY();
});
dotView.setOnMouseMoved(e -> dotView.setCursor(Cursor.HAND));
dotView.setOnMouseDragged(e -> dotView.setCursor(Cursor.MOVE));
}
@Override
protected void fillCommands() {
super.fillCommands(new GetAllDotCommands(currentTrace.getCurrentState()));
}
@Override
protected void visualize(DynamicCommandItem item) {
if (!item.isAvailable()) {
return;
}
List<IEvalElement> formulas = Collections.synchronizedList(new ArrayList<>());
interrupt();
Thread thread = new Thread(() -> {
Platform.runLater(()-> statusBar.setText(bundle.getString("statusbar.loadStatus.loading")));
try {
Trace trace = currentTrace.get();
if(trace == null) {
Platform.runLater(this::reset);
currentThread.set(null);
return;
}
final String text = getSvgForDotCommand(trace, item, formulas);
if(!Thread.currentThread().isInterrupted()) {
loadGraph(text);
}
} catch (IOException | UncheckedIOException | ProBError | EvaluationException e) {
LOGGER.error("Graph visualization failed", e);
currentThread.set(null);
Platform.runLater(() -> {
stageManager.makeExceptionAlert(e, "dotty.alerts.visualisationError.content").show();
dotView.getEngine().loadContent("");
statusBar.setText("");
});
}
}, "Graph Visualizer");
currentThread.set(thread);
thread.start();
}
private String getSvgForDotCommand(final Trace trace, final DynamicCommandItem item, final List<IEvalElement> formulas) throws IOException {
if (item.getArity() > 0) {
formulas.add(new ClassicalB(taFormula.getText(), FormulaExpand.EXPAND));
}
final Path path = Files.createTempFile("prob2-ui-dot", ".svg");
GetSvgForVisualizationCommand cmd = new GetSvgForVisualizationCommand(trace.getCurrentState(), item, path.toFile(), formulas);
trace.getStateSpace().execute(cmd);
final String text;
try (final Stream<String> lines = Files.lines(path)) {
text = lines.collect(Collectors.joining("\n"));
}
Files.delete(path);
return text;
}
private void loadGraph(final String svg) {
Thread thread = Thread.currentThread();
Platform.runLater(() -> {
if (!thread.isInterrupted()) {
/*
* FIXME: Fix rendering problem in JavaFX WebView
*/
dotView.getEngine().loadContent("<center>" + svg.replaceAll("font-size=\"12.00\"", "font-size=\"10.00\"") + "</center>");
statusBar.setText("");
}
currentThread.set(null);
});
}
@FXML
private void defaultSize() {
dotView.setZoom(1);
}
@FXML
private void zoomIn() {
zoomByFactor(1.15);
adjustScroll();
}
@FXML
private void zoomOut() {
zoomByFactor(0.85);
adjustScroll();
}
private void zoomByFactor(double factor) {
dotView.setZoom(dotView.getZoom() * factor);
dragFactor *= factor;
}
private void adjustScroll() {
Set<Node> nodes = pane.lookupAll(".scroll-bar");
double x = 0.0;
double y = 0.0;
for (final Node node : nodes) {
if (node instanceof ScrollBar) {
ScrollBar sb = (ScrollBar) node;
if (sb.getOrientation() == Orientation.VERTICAL) {
x = sb.getPrefHeight() / 2;
} else {
y = sb.getPrefWidth() / 2;
}
}
}
dotView.getEngine().executeScript("window.scrollBy(" + x + "," + y + ")");
}
@Override
protected void reset() {
dotView.getEngine().loadContent("");
statusBar.setText("");
}
} |
package de.voidplus.soundcloud;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import com.google.gson.Gson;
import com.soundcloud.api.ApiWrapper;
import com.soundcloud.api.Endpoints;
import com.soundcloud.api.Http;
import com.soundcloud.api.Params;
import com.soundcloud.api.Request;
import com.soundcloud.api.Token;
public class SoundCloud {
public static final String VERSION = "0.1.5";
private enum Type {
USER,
TRACK,
PLAYLIST,
COMMENT,
GROUP
}
private enum Rest {
GET,
PUT,
POST,
DELETE
}
protected final String app_client_id;
protected final String app_client_secret;
protected Token token;
protected ApiWrapper wrapper;
protected JSONParser parser;
protected Gson gson;
/**
* Constructor of the SoundCloud wrapper, which creates the API wrapper and generates the Access Token.
*
* @param _app_client_id Application Client ID
* @param _app_client_secret Application Client Secret
* @param _login_name SoundCloud Login Name
* @param _login_password SoundCloud Login Pass
*/
public SoundCloud( String _app_client_id, String _app_client_secret )
{
this.app_client_id = _app_client_id;
this.app_client_secret = _app_client_secret;
this.parser = new JSONParser();
this.gson = new Gson();
wrapper = new ApiWrapper(app_client_id, app_client_secret, null, null);
wrapper.setToken(null);
wrapper.setDefaultContentType("application/json");
}
/**
* Constructor of the SoundCloud wrapper, which creates the API wrapper and generates the Access Token.
*
* @param _app_client_id Application Client ID
* @param _app_client_secret Application Client Secret
*/
public SoundCloud( String _app_client_id, String _app_client_secret, String _login_name, String _login_password )
{
this(_app_client_id, _app_client_secret);
this.login(_login_name, _login_password);
}
/**
* Login to get a valid token.
*
* @param _login_name SoundCloud Login Name
* @param _login_password SoundCloud Login Pass
* @return
*/
public boolean login( String _login_name, String _login_password ){
try {
this.token = wrapper.login(_login_name, _login_password, Token.SCOPE_NON_EXPIRING);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* The core of the library.
*
* @param api
* @param rest
* @param value
* @param filters
* @return
*/
private <T> T api(String api, Rest rest, Object value, String[] filters)
{
if (api.length() > 0) {
if (api.startsWith("/") == false) {
api = "/" + api;
}
if (api.charAt(api.length() - 1) == '/') {
api = api.substring(0, api.length() - 1);
}
api = api.replace(".format", ".json").replace(".xml", ".json");
if (api.indexOf(".json") == -1) {
api += ".json";
}
} else {
return null;
}
Type type = null;
if (
api.matches("^/me.json") ||
api.matches("^/me/(followings(/[0-9]+)?|followers(/[0-9]+)?).json") ||
api.matches("^/users(/[0-9]+)?.json") ||
api.matches("^/users/([0-9]+)/(followings|followers).json") ||
api.matches("^/groups/([0-9]+)/(users|moderators|members|contributors).json")
){
type = Type.USER;
} else if(
api.matches("^/tracks(/[0-9]+)?.json") ||
api.matches("^/me/(tracks|favorites)(/[0-9]+)?.json") ||
api.matches("^/users/([0-9]+)/(tracks|favorites).json")
){
type = Type.TRACK;
} else if(
api.matches("^/playlists(/[0-9]+)?.json") ||
api.matches("^/me/playlists.json") ||
api.matches("^/users/([0-9]+)/playlists.json") ||
api.matches("^/groups/([0-9]+)/tracks.json")
){
type = Type.PLAYLIST;
} else if(
api.matches("^/comments/([0-9]+).json") ||
api.matches("^/me/comments.json") ||
api.matches("^/tracks/([0-9]+)/comments.json")
){
type = Type.COMMENT;
} else if(
api.matches("^/groups(/[0-9]+)?.json") ||
api.matches("^/me/groups.json") ||
api.matches("^/users/([0-9]+)/groups.json")
){
type = Type.GROUP;
}
if (type == null) {
return null;
}
if (filters != null) {
if (filters.length > 0 && filters.length % 2 == 0) {
api += "?";
for (int i = 0, l = filters.length; i < l; i += 2) {
if (i != 0) {
api += "&";
}
api += (filters[i] + "=" + filters[i + 1]);
}
if(this.token == null){
api += ("&consumer_key="+this.app_client_id);
}
}
} else {
api += "?consumer_key="+this.app_client_id;
}
try {
Request resource;
HttpResponse response;
String klass, content;
switch(rest){
case GET:
response = wrapper.get(Request.to(api));
if(response.getStatusLine().getStatusCode()==303){ // recursive better?
// System.out.println( "303: "+response.getFirstHeader("Location").getValue() );
api = (String)(response.getFirstHeader("Location").getValue()+".json").replace("https://api.soundcloud.com","");
response = wrapper.get( Request.to(api) );
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String json = (String)(Http.formatJSON(Http.getString(response))).trim();
if (json.startsWith("[") && json.endsWith("]")) {
JSONArray data = (JSONArray) parser.parse(json);
if (data.size() > 0) {
switch(type){
case USER:
ArrayList<User> users = new ArrayList<User>();
for (int i = 0, l = data.size(); i < l; i++) {
String tuple = data.get(i).toString();
User user = gson.fromJson(tuple, User.class);
users.add(user);
}
return (T) users;
case TRACK:
ArrayList<Track> tracks = new ArrayList<Track>();
for (int i = 0, l = data.size(); i < l; i++) {
String tuple = data.get(i).toString();
Track track = gson.fromJson(tuple, Track.class);
track.setSoundCloud(this);
tracks.add(track);
}
return (T) tracks;
case PLAYLIST:
ArrayList<Playlist> playlists = new ArrayList<Playlist>();
for (int i = 0, l = data.size(); i < l; i++) {
String tuple = data.get(i).toString();
Playlist playlist = gson.fromJson(tuple, Playlist.class);
playlists.add(playlist);
}
return (T) playlists;
case COMMENT:
ArrayList<Comment> comments = new ArrayList<Comment>();
for (int i = 0, l = data.size(); i < l; i++) {
String tuple = data.get(i).toString();
Comment comment = gson.fromJson(tuple, Comment.class);
comments.add(comment);
}
return (T) comments;
case GROUP:
ArrayList<Group> groups = new ArrayList<Group>();
for (int i = 0, l = data.size(); i < l; i++) {
String tuple = data.get(i).toString();
Group group = gson.fromJson(tuple, Group.class);
groups.add(group);
}
return (T) groups;
default: return null;
}
}
} else {
switch(type){
case USER:
User user = gson.fromJson(json, User.class);
return (T) user;
case TRACK:
Track track = gson.fromJson(json, Track.class);
track.setSoundCloud(this);
return (T) track;
case PLAYLIST:
Playlist playlist = gson.fromJson(json, Playlist.class);
return (T) playlist;
case COMMENT:
Comment comment = gson.fromJson(json, Comment.class);
return (T) comment;
case GROUP:
Group group = gson.fromJson(json, Group.class);
return (T) group;
default: return null;
}
}
} else {
System.err.println("Invalid status received: " + response.getStatusLine());
}
break;
case POST:
klass = value.getClass().getName();
klass = klass.substring((klass.lastIndexOf('.')+1));
if(klass.equals("Track")){
Track track = ((Track)value);
resource = Request.to(Endpoints.TRACKS)
.add(Params.Track.TITLE,track.getTitle())
.add(Params.Track.TAG_LIST,track.getTagList())
.withFile(Params.Track.ASSET_DATA,new File(track.asset_data));
} else if(klass.equals("Comment")){
content = gson.toJson(value);
content = "{\"comment\":"+content+"}";
resource = Request.to(api.replace(".json",""))
.withContent(content, "application/json");
} else {
return null;
}
response = wrapper.post(resource);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
String json = (String)(Http.formatJSON(Http.getString(response))).trim();
switch(type){
case TRACK:
Track track = gson.fromJson(json, Track.class);
track.setSoundCloud(this);
return (T) track;
case COMMENT:
Comment comment = gson.fromJson(json, Comment.class);
return (T) comment;
default: return null;
}
} else {
System.err.println("Invalid status received: " + response.getStatusLine());
}
break;
case PUT:
if( value!=null ){
klass = value.getClass().getName();
klass = klass.substring((klass.lastIndexOf('.')+1));
content = gson.toJson(value);
if(klass.equals("User")){
content = "{\"user\":"+content+"}";
} else if(klass.equals("Track")){
content = "{\"track\":"+content+"}";
} else {
return null;
}
resource = Request.to(api.replace(".json","")).withContent(content, "application/json");
} else {
resource = Request.to(api.replace(".json",""));
}
response = wrapper.put(resource);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String json = (String)(Http.formatJSON(Http.getString(response))).trim();
switch(type){
case USER:
User user = gson.fromJson(json, User.class);
return (T) user;
case TRACK:
Track track = gson.fromJson(json, Track.class);
track.setSoundCloud(this);
return (T) track;
default: return null;
}
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
return (T) new Boolean(true);
} else{
System.err.println("Invalid status received: " + response.getStatusLine());
}
break;
case DELETE:
response = wrapper.delete( Request.to(api) );
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return (T) new Boolean(true);
}
return (T) new Boolean(false);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* API access to GET (REST) data.
*
* @param api
* @return
*/
public <T> T get(String api) {
return this.api(api, Rest.GET, null, null);
}
/**
* API access with filters to GET (REST) data.
*
* @param api
* @param filters
* @return
*/
public <T> T get(String api, String[] filters) {
return this.api(api, Rest.GET, null, filters);
}
/**
* API access to POST (REST) new data.
*
* @param api
* @return
*/
public <T> T post(String api, Object value){
return this.api(api, Rest.POST, value, null);
}
/**
* API access to PUT (REST) new data.
*
* @param api
* @return
*/
public <T> T put(String api){
return this.api(api, Rest.PUT, null, null);
}
/**
* API access to PUT (REST) new data.
*
* @param api
* @return
*/
public <T> T put(String api, Object value){
return this.api(api, Rest.PUT, value, null);
}
/**
* API access to DELETE (REST) data.
*
* @param api
* @return
*/
public Boolean delete(String api){
return (Boolean) this.api(api, Rest.DELETE, null, null);
}
/**
* Get data about you.
*
* @return
*/
public User getMe(){
return this.get("me");
}
/**
* Get your followings.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<User> getMeFollowings(Integer offset, Integer limit){
return this.get("me/followings", new String[]{
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 followings.
*
* @return
*/
public ArrayList<User> getMeFollowings(){
return this.getMeFollowings(0, 50);
}
/**
* Get a specific following.
*
* @param contact_id
* @return
*/
public User getMeFollowing(Integer contact_id){
return this.get("me/followings/"+Integer.toString(contact_id));
}
/**
* Get your followers.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<User> getMeFollowers(Integer offset, Integer limit){
return this.get("me/followers", new String[]{
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 followers.
*
* @return
*/
public ArrayList<User> getMeFollowers(){
return this.getMeFollowers(0, 50);
}
/**
* Get a specific follower.
*
* @param contact_id
* @return
*/
public User getMeFollower(Integer contact_id){
return this.get("me/followers/"+Integer.toString(contact_id));
}
/**
* Get your favorite tracks.
*
* @param limit
* @param offset
* @return
*/
public ArrayList<Track> getMeFavorites(Integer offset, Integer limit){
return this.get("me/favorites", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 favorite tracks.
*
* @return
*/
public ArrayList<Track> getMeFavorites(){
return this.getMeFavorites(0,50);
}
/**
* Get your last tracks.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<Track> getMeTracks(Integer offset, Integer limit){
return this.get("me/tracks", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 tracks.
*
* @return
*/
public ArrayList<Track> getMeTracks(){
return this.getMeTracks(0, 50);
}
/**
* Get your playlists.
*
* @return
*/
public ArrayList<Playlist> getMePlaylists(Integer offset, Integer limit){
return this.get("me/playlists", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 playlists.
*
* @return
*/
public ArrayList<Playlist> getMePlaylists(){
return this.getMePlaylists(0,50);
}
/**
* Get your groups.
*
* @return
*/
public ArrayList<Group> getMeGroups(Integer offset, Integer limit){
return this.get("me/groups", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 groups.
*
* @return
*/
public ArrayList<Group> getMeGroups(){
return this.getMeGroups(0,50);
}
/**
* Get your comments.
*
* @return
*/
public ArrayList<Comment> getMeComments(Integer offset, Integer limit){
return this.get("me/comments", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get your last 50 comments.
*
* @return
*/
public ArrayList<Comment> getMeComments(){
return this.getMeComments(0, 50);
}
/**
* Get comments from specific track.
*
* @param track_id
* @return
*/
public ArrayList<Comment> getCommentsFromTrack(Integer track_id){
return this.get("tracks/"+Integer.toString(track_id)+"/comments");
}
/**
* Get a specific playlist.
*
* @param id
* @return
*/
public Playlist getPlaylist(Integer playlist_id){
return this.get("playlists/"+Integer.toString(playlist_id));
}
/**
* Get last playlists.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<Playlist> getPlaylists(Integer offset, Integer limit){
return this.get("playlists", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get last 50 playlists.
*
* @return
*/
public ArrayList<Playlist> getPlaylists(){
return this.getPlaylists(0, 50);
}
/**
* Get a specific user.
*
* @param id
* @return
*/
public User getUser(Integer contact_id){
return this.get("users/"+Integer.toString(contact_id));
}
/**
* Get last users.
*
* @param limit
* @param offset
* @return
*/
public ArrayList<User> getUsers(Integer offset, Integer limit){
return this.get("users", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get last users.
*
* @return
*/
public ArrayList<User> getUsers(){
return this.getUsers(0,50);
}
/**
* Simple user search.
*
* @param username
* @return
*/
public ArrayList<User> findUser(String username){
return this.get("users", new String[]{
"q",username
});
}
/**
* Get a specific track.
*
* @param id
* @return
*/
public Track getTrack(Integer track_id){
return this.get("tracks/"+Integer.toString(track_id));
}
/**
* Get last tracks.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<Track> getTracks(Integer offset, Integer limit){
return this.get("tracks", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get last 50 tracks.
*
* @return
*/
public ArrayList<Track> getTracks(){
return this.getTracks(0, 50);
}
/**
* Get tracks from specific group.
*
* @param group_id
* @return
*/
public ArrayList<Track> getTracksFromGroup(Integer group_id){
return this.get("groups/"+Integer.toString(group_id)+"/tracks");
}
/**
* Simple track search.
*
* @param title
* @return
*/
public ArrayList<Track> findTrack(String title){
return this.get("tracks", new String[]{
"q",title
});
}
/**
* Get a specific group.
*
* @param id
* @return
*/
public Group getGroup(Integer id){
return this.get("groups/"+Integer.toString(id));
}
/**
* Get last groups.
*
* @param offset
* @param limit
* @return
*/
public ArrayList<Group> getGroups(Integer offset, Integer limit){
return this.get("groups", new String[]{
"order","created_at",
"limit",Integer.toString(limit),
"offset",Integer.toString(offset)
});
}
/**
* Get last 50 groups.
*
* @return
*/
public ArrayList<Group> getGroups(){
return this.getGroups(0, 50);
}
/**
* Simple user search.
*
* @param name
* @return
*/
public ArrayList<Group> findGroup(String name){
return this.get("groups", new String[]{
"q",name
});
}
/**
* Update your account.
*
* @param user
* @return
*/
public User putMe(User user){
return this.put("me", user);
}
/**
* Favor a specific track.
*
* @param track_id
* @return
*/
public Boolean putFavoriteTrack(Integer track_id){
return this.put("me/favorites/"+Integer.toString(track_id));
}
/**
* Post a new track.
*
* @param track
* @return
*/
public Track postTrack(Track track){
return this.post("tracks", track);
}
/**
* Post a new comment to a specific track.
*
* @param track_id
* @param comment
* @return
*/
public Comment postCommentToTrack(Integer track_id, Comment comment){
return this.post("tracks/"+Integer.toString(track_id)+"/comments", comment);
}
/**
* Delete a specific track.
*
* @param track_id
* @return
*/
public Boolean deleteTrack(Integer track_id){
return this.delete("tracks/"+Integer.toString(track_id));
}
/**
* Remove a specific favorite track.
*
* @param track_id
* @return
*/
public Boolean deleteFavoriteTrack(Integer track_id){
return this.delete("me/favorites/"+Integer.toString(track_id));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.