answer
stringlengths
17
10.2M
package com.google.research.bleth.simulator; public abstract class Simulation { Board board; public Board getBoard() { return board; } }
package net.imagej.ops; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import net.imagej.ops.OpCandidate.StatusCode; import org.scijava.Context; import org.scijava.InstantiableException; import org.scijava.command.CommandInfo; import org.scijava.command.CommandService; import org.scijava.convert.ConvertService; import org.scijava.log.LogService; import org.scijava.module.Module; import org.scijava.module.ModuleInfo; import org.scijava.module.ModuleItem; import org.scijava.module.ModuleService; import org.scijava.plugin.AbstractSingletonService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.service.Service; /** * Default service for finding {@link Op}s which match a template. * * @author Curtis Rueden */ @Plugin(type = Service.class) public class DefaultOpMatchingService extends AbstractSingletonService<Optimizer> implements OpMatchingService { @Parameter private Context context; @Parameter private ModuleService moduleService; @Parameter private CommandService commandService; @Parameter private ConvertService convertService; @Parameter private LogService log; // -- OpMatchingService methods -- @Override public List<CommandInfo> getOps() { return commandService.getCommandsOfType(Op.class); } @Override public <OP extends Op> Module findModule(final OpRef<OP> ref) { // find candidates with matching name & type final List<OpCandidate<OP>> candidates = findCandidates(ref); if (candidates.isEmpty()) { throw new IllegalArgumentException("No candidate '" + ref.getLabel() + "' ops"); } // narrow down candidates to the exact matches final List<Module> matches = findMatches(candidates); if (matches.size() == 1) { // a single match: return it if (log.isDebug()) { log.debug("Selected '" + ref.getLabel() + "' op: " + matches.get(0).getDelegateObject().getClass().getName()); } return optimize(matches.get(0)); } final String analysis = analyze(candidates, matches); throw new IllegalArgumentException(analysis); } @Override public <OP extends Op> List<OpCandidate<OP>> findCandidates( final OpRef<OP> ref) { final ArrayList<OpCandidate<OP>> candidates = new ArrayList<OpCandidate<OP>>(); for (final CommandInfo info : getOps()) { if (isCandidate(info, ref)) { candidates.add(new OpCandidate<OP>(ref, info)); } } return candidates; } @Override public <OP extends Op> List<Module> findMatches( final List<OpCandidate<OP>> candidates) { final ArrayList<Module> matches = new ArrayList<Module>(); double priority = Double.NaN; for (final OpCandidate<?> candidate : candidates) { final ModuleInfo info = candidate.getInfo(); final double p = info.getPriority(); if (p != priority && !matches.isEmpty()) { // NB: Lower priority was reached; stop looking for any more matches. break; } priority = p; final Module module = match(candidate); if (module != null) matches.add(module); } return matches; } @Override public <OP extends Op> Module match(final OpCandidate<OP> candidate) { if (!candidate.getInfo().isValid()) { // skip invalid modules candidate.setStatus(StatusCode.INVALID_MODULE); return null; } // check the number of args, padding optional args with null as needed int inputCount = 0, requiredCount = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { inputCount++; if (item.isRequired()) requiredCount++; } final Object[] args = candidate.getRef().getArgs(); if (args.length == inputCount) { // correct number of arguments return match(candidate, args); } if (args.length > inputCount) { // too many arguments candidate.setStatus(StatusCode.TOO_MANY_ARGS, args.length + " > " + inputCount); return null; } if (args.length < requiredCount) { // too few arguments candidate.setStatus(StatusCode.TOO_FEW_ARGS, args.length + " < " + requiredCount); return null; } // pad optional parameters with null (from right to left) final int argsToPad = inputCount - args.length; final int optionalCount = inputCount - requiredCount; final int optionalsToFill = optionalCount - argsToPad; final Object[] paddedArgs = new Object[inputCount]; int argIndex = 0, paddedIndex = 0, optionalIndex = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { if (!item.isRequired() && optionalIndex++ >= optionalsToFill) { // skip this optional parameter (pad with null) paddedIndex++; continue; } paddedArgs[paddedIndex++] = args[argIndex++]; } return match(candidate, paddedArgs); } @Override public Module assignInputs(final Module module, final Object... args) { int i = 0; for (final ModuleItem<?> item : module.getInfo().inputs()) { assign(module, args[i++], item); } return module; } @Override public Module optimize(final Module module) { final ArrayList<Module> optimal = new ArrayList<Module>(); final ArrayList<Optimizer> optimizers = new ArrayList<Optimizer>(); double priority = Double.NaN; for (final Optimizer optimizer : getInstances()) { final double p = optimizer.getPriority(); if (p != priority && !optimal.isEmpty()) { // NB: Lower priority was reached; stop looking for any more matches. break; } priority = p; final Module m = optimizer.optimize(module); if (m != null) { optimal.add(m); optimizers.add(optimizer); } } if (optimal.size() == 1) return optimal.get(0); if (optimal.isEmpty()) return module; // multiple matches final double p = optimal.get(0).getInfo().getPriority(); final StringBuilder sb = new StringBuilder(); final String label = module.getDelegateObject().getClass().getName(); sb.append("Multiple '" + label + "' optimizations of priority " + p + ":\n"); for (int i = 0; i < optimizers.size(); i++) { sb.append("\t" + optimizers.get(i).getClass().getName() + " produced:"); sb.append("\t\t" + getOpString(optimal.get(i).getInfo()) + "\n"); } log.warn(sb.toString()); return module; } @Override public String getOpString(final String name, final Object... args) { final StringBuilder sb = new StringBuilder(); sb.append(name + "("); boolean first = true; for (final Object arg : args) { if (first) first = false; else sb.append(", "); if (arg != null) sb.append(arg.getClass().getName() + " "); if (arg instanceof Class) sb.append(((Class<?>) arg).getName()); else sb.append(arg); } sb.append(")"); return sb.toString(); } @Override public String getOpString(final ModuleInfo info) { final StringBuilder sb = new StringBuilder(); if (!info.isValid()) sb.append("{!INVALID!} "); sb.append("[" + info.getPriority() + "] "); sb.append("(" + paramString(info.outputs()) + ")"); sb.append(" = " + info.getDelegateClassName()); sb.append("(" + paramString(info.inputs()) + ")"); return sb.toString(); } @Override public <OP extends Op> String analyze( final List<OpCandidate<OP>> candidates, final List<Module> matches) { final StringBuilder sb = new StringBuilder(); final OpRef<OP> ref = candidates.get(0).getRef(); if (matches.isEmpty()) { // no matches sb.append("No matching '" + ref.getLabel() + "' op\n"); } else { // multiple matches final double priority = matches.get(0).getInfo().getPriority(); sb.append("Multiple '" + ref.getLabel() + "' ops of priority " + priority + ":\n"); for (final Module module : matches) { sb.append("\t" + getOpString(module.getInfo()) + "\n"); } } // fail, with information about the template and candidates sb.append("Template:\n"); sb.append("\t" + getOpString(ref.getLabel(), ref.getArgs()) + "\n"); sb.append("Candidates:\n"); for (final OpCandidate<OP> candidate : candidates) { final ModuleInfo info = candidate.getInfo(); sb.append("\t" + getOpString(info) + "\n"); final String status = candidate.getStatus(); if (status != null) sb.append("\t\t" + status + "\n"); } return sb.toString(); } @Override public <OP extends Op> boolean isCandidate(final CommandInfo info, final OpRef<OP> ref) { if (!nameMatches(info, ref.getName())) return false; // the name matches; now check the class final Class<?> opClass; try { opClass = info.loadClass(); } catch (final InstantiableException exc) { log.error("Invalid op: " + info.getClassName()); return false; } return ref.getType() == null || ref.getType().isAssignableFrom(opClass); } // -- PTService methods -- @Override public Class<Optimizer> getPluginType() { return Optimizer.class; } // -- Helper methods -- private <OP extends Op> Module match(final OpCandidate<OP> candidate, final Object[] args) { // check that each parameter is compatible with its argument int i = 0; for (final ModuleItem<?> item : candidate.getInfo().inputs()) { final Object arg = args[i++]; if (!canAssign(candidate, arg, item)) return null; } // create module and assign the inputs final Module module = createModule(candidate.getInfo(), args); candidate.setModule(module); // make sure the op itself is happy with these arguments final Object op = module.getDelegateObject(); if (op instanceof Contingent) { final Contingent c = (Contingent) op; if (!c.conforms()) { candidate.setStatus(StatusCode.DOES_NOT_CONFORM); return null; } } // found a match! return module; } private boolean nameMatches(final ModuleInfo info, final String name) { if (name == null || name.equals(info.getName())) return true; // check for an alias final String alias = info.get("alias"); if (name.equals(alias)) return true; // check for a list of aliases final String aliases = info.get("aliases"); if (aliases != null) { for (final String a : aliases.split(",")) { if (name.equals(a.trim())) return true; } } return false; } /** Helper method of {@link #match}. */ private Module createModule(final ModuleInfo info, final Object... args) { final Module module = moduleService.createModule(info); context.inject(module.getDelegateObject()); return assignInputs(module, args); } private boolean canAssign(final OpCandidate<?> candidate, final Object arg, final ModuleItem<?> item) { if (arg == null) { if (item.isRequired()) { candidate.setStatus(StatusCode.REQUIRED_ARG_IS_NULL); return false; } return true; } final Type type = item.getGenericType(); if (!canConvert(arg, type)) { candidate.setStatus(StatusCode.CANNOT_CONVERT, "cannot coerce " + arg.getClass().getName() + " to " + type); return false; } return true; } private boolean canConvert(final Object o, final Type type) { if (o instanceof Class && convertService.supports((Class<?>) o, type)) { // NB: Class argument for matching, to help differentiate op signatures. return true; } return convertService.supports(o, type); } /** Helper method of {@link #assignInputs}. */ private void assign(final Module module, final Object arg, final ModuleItem<?> item) { if (arg != null) { final Type type = item.getGenericType(); final Object value = convert(arg, type); module.setInput(item.getName(), value); } module.setResolved(item.getName(), true); } private Object convert(final Object o, final Type type) { if (o instanceof Class && convertService.supports((Class<?>) o, type)) { // NB: Class argument for matching; fill with null. return null; } return convertService.convert(o, type); } private String paramString(final Iterable<ModuleItem<?>> items) { final StringBuilder sb = new StringBuilder(); boolean first = true; for (final ModuleItem<?> item : items) { if (first) first = false; else sb.append(", "); sb.append(getTypeName(item.getGenericType()) + " " + item.getName()); if (!item.isRequired()) sb.append("?"); } return sb.toString(); } private String getTypeName(final Type type) { if (type instanceof Class) return ((Class<?>) type).getName(); return type.toString(); } }
package com.huangzhimin.contacts.email; import java.util.ArrayList; import java.util.List; import java.io.StringReader; import com.huangzhimin.contacts.Contact; import com.huangzhimin.contacts.exception.ContactsException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlPullParser; /** * Hotmail * * @author flyerhzm * */ public class HotmailImporter extends EmailImporter { private String securityToken = null; /** * * * @param email * @param password */ public HotmailImporter(String email, String password) { super(email, password); } /** * hotmail * * @throws ContactsException */ public void doLogin() throws ContactsException { try { String loginData = doSoapPost(loginRequestUrl(), loginRequestXml(), null); loginResponseHandle(loginData); } catch (Exception e) { throw new ContactsException("Hotmail protocol has changed", e); } } /** * * * @return * @throws ContactsException */ public List<Contact> parseContacts() throws ContactsException { try { String contactsData = doSoapPost(contactsRequestUrl(), contactsRequestXml(), contactsRequestAction()); return contactsResponseHandle(contactsData); } catch (Exception e) { throw new ContactsException("Hotmail protocol has changed", e); } } private String loginRequestXml() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xml += "<Envelope xmlns=\"http: xml += "<Header>"; xml += "<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"PPAuthInfo\">"; xml += "<ps:HostingApp>{3:B}</ps:HostingApp>"; xml += "<ps:BinaryVersion>4</ps:BinaryVersion>"; xml += "<ps:UIVersion>1</ps:UIVersion>"; xml += "<ps:Cookies></ps:Cookies>"; xml += "<ps:RequestParams>AQAAAAIAAABsYwQAAAAzMDg0</ps:RequestParams>"; xml += "</ps:AuthInfo>"; xml += "<wsse:Security>"; xml += "<wsse:UsernameToken Id=\"user\">"; xml += "<wsse:Username>" + email + "</wsse:Username>"; xml += "<wsse:Password>" + password + "</wsse:Password>"; xml += "</wsse:UsernameToken>"; xml += "</wsse:Security>"; xml += "</Header>"; xml += "<Body>"; xml += "<ps:RequestMultipleSecurityTokens xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"RSTS\">"; xml += "<wst:RequestSecurityToken Id=\"RST0\">"; xml += "<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>"; xml += "<wsp:AppliesTo>"; xml += "<wsa:EndpointReference>"; xml += "<wsa:Address>http://Passport.NET/tb</wsa:Address>"; xml += "</wsa:EndpointReference>"; xml += "</wsp:AppliesTo>"; xml += "</wst:RequestSecurityToken>"; xml += "<wst:RequestSecurityToken Id=\"RST1\">"; xml += "<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>"; xml += "<wsp:AppliesTo>"; xml += "<wsa:EndpointReference>"; xml += "<wsa:Address>contacts.msn.com</wsa:Address>"; xml += "</wsa:EndpointReference>"; xml += "</wsp:AppliesTo>"; xml += "<wsse:PolicyReference URI=\"MBI\">"; xml += "</wsse:PolicyReference>"; xml += "</wst:RequestSecurityToken>"; xml += "<wst:RequestSecurityToken Id=\"RST2\">"; xml += "<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>"; xml += "<wsp:AppliesTo>"; xml += "<wsa:EndpointReference>"; xml += "<wsa:Address>storage.msn.com</wsa:Address>"; xml += "</wsa:EndpointReference>"; xml += "</wsp:AppliesTo>"; xml += "<wsse:PolicyReference URI=\"MBI\">"; xml += "</wsse:PolicyReference>"; xml += "</wst:RequestSecurityToken>"; xml += "</ps:RequestMultipleSecurityTokens>"; xml += "</Body>"; xml += "</Envelope>"; return xml; } private String loginRequestUrl() { String url = ""; if (email.indexOf("@msn.com") == -1) { url = "https://login.live.com/RST.srf"; } else { url = "https://msnia.login.live.com/pp650/RST.srf"; } return url; } private void loginResponseHandle(String data) throws Exception { if (data.indexOf("FailedAuthentication") >= 0) { throw new ContactsException("failed authentication"); } if (data.indexOf("<wsse:BinarySecurityToken") < 1) { throw new ContactsException("failed authentication"); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new StringReader(data)); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("BinarySecurityToken")) { if (xpp.getAttributeValue(null, "Id").equals("Compact1")) { xpp.next(); securityToken = xpp.getText().replace("&", "&amp;"); } } xpp.next(); eventType = xpp.getEventType(); } } private String contactsRequestXml() { String xml = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'\n"; xml += "xmlns:xsi='http: xml += "xmlns:xsd='http: xml += "xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'>\n"; xml += "<soap:Header>\n"; xml += "<ABApplicationHeader xmlns='http: xml += "<ApplicationId>CFE80F9D-180F-4399-82AB-413F33A1FA11</ApplicationId>\n"; xml += "<IsMigration>false</IsMigration>\n"; xml += "<PartnerScenario>Initial</PartnerScenario>\n"; xml += "</ABApplicationHeader>\n"; xml += "<ABAuthHeader xmlns='http: xml += "<ManagedGroupRequest>false</ManagedGroupRequest>\n"; xml += "<TicketToken>" + securityToken + "</TicketToken>\n"; xml += "</ABAuthHeader>\n"; xml += "</soap:Header>\n"; xml += "<soap:Body>\n"; xml += "<ABFindAll xmlns='http: xml += "<abId>00000000-0000-0000-0000-000000000000</abId>\n"; xml += "<abView>Full</abView>\n"; xml += "<deltasOnly>false</deltasOnly>\n"; xml += "<lastChange>0001-01-01T00:00:00.0000000-08:00</lastChange>\n"; xml += "</ABFindAll>\n"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; return xml; } private String contactsRequestUrl() { return "http://contacts.msn.com/abservice/abservice.asmx"; } private String contactsRequestAction() { return "http: } private List<Contact> contactsResponseHandle(String data) throws Exception { List<Contact> contacts = new ArrayList<Contact>(); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new StringReader(data)); int eventType = xpp.getEventType(); String username = null; String email = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG && "Contact".equals(xpp.getName())) { while (true) { if (eventType == XmlPullParser.END_TAG && "Contact".equals(xpp.getName())) { break; } if (eventType == XmlPullParser.START_TAG && "ContactEmail".equals(xpp.getName())) { while (true) { if (eventType == XmlPullParser.END_TAG && "ContactEmail".equals(xpp.getName())) { break; } if (eventType == XmlPullParser.START_TAG && "email".equals(xpp.getName())) { xpp.next(); email = xpp.getText(); } xpp.next(); eventType = xpp.getEventType(); } } if (eventType == XmlPullParser.START_TAG && "passportName".equals(xpp.getName())) { xpp.next(); email = xpp.getText(); } if (eventType == XmlPullParser.START_TAG && "displayName".equals(xpp.getName())) { xpp.next(); username = xpp.getText(); Contact contact = new Contact(username, email); contacts.add(contact); } xpp.next(); eventType = xpp.getEventType(); } } xpp.next(); eventType = xpp.getEventType(); } return contacts; } }
package net.minecraftforge.oredict; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.toposort.TopologicalSort; import cpw.mods.fml.common.toposort.TopologicalSort.DirectedGraph; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.RecipeBookCloning; import net.minecraft.item.crafting.RecipeFireworks; import net.minecraft.item.crafting.RecipesArmorDyes; import net.minecraft.item.crafting.RecipesMapCloning; import net.minecraft.item.crafting.RecipesMapExtending; import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.item.crafting.ShapelessRecipes; import static net.minecraftforge.oredict.RecipeSorter.Category.*; @SuppressWarnings("rawtypes") public class RecipeSorter implements Comparator<IRecipe> { public enum Category { UNKNOWN, SHAPELESS, SHAPED }; private static class SortEntry { private String name; private Class<?> cls; private Category cat; List<String> before = Lists.newArrayList(); List<String> after = Lists.newArrayList(); private SortEntry(String name, Class<?> cls, Category cat, String deps) { this.name = name; this.cls = cls; this.cat = cat; parseDepends(deps); } private void parseDepends(String deps) { if (deps.isEmpty()) return; for (String dep : deps.split(" ")) { if (dep.startsWith("before:")) { before.add(dep.substring(7)); } else if (dep.startsWith("after:")) { after.add(dep.substring(6)); } else { throw new IllegalArgumentException("Invalid dependancy: " + dep); } } } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("RecipeEntry(\"").append(name).append("\", "); buf.append(cat.name()).append(", "); buf.append(cls == null ? "" : cls.getName()).append(")"); if (before.size() > 0) { buf.append(" Before: ").append(Joiner.on(", ").join(before)); } if (after.size() > 0) { buf.append(" After: ").append(Joiner.on(", ").join(after)); } return buf.toString(); } @Override public int hashCode() { return name.hashCode(); } }; private static Map<Class, Category> categories = Maps.newHashMap(); //private static Map<String, Class> types = Maps.newHashMap(); private static Map<String, SortEntry> entries = Maps.newHashMap(); private static Map<Class, Integer> priorities = Maps.newHashMap(); public static RecipeSorter INSTANCE = new RecipeSorter(); private static boolean isDirty = true; private static SortEntry before = new SortEntry("Before", null, UNKNOWN, ""); private static SortEntry after = new SortEntry("After", null, UNKNOWN, ""); private RecipeSorter() { register("minecraft:shaped", ShapedRecipes.class, SHAPED, "before:minecraft:shapeless"); register("minecraft:mapextending", RecipesMapExtending.class, SHAPED, "after:minecraft:shaped before:minecraft:shapeless"); register("minecraft:shapeless", ShapelessRecipes.class, SHAPELESS, "after:minecraft:shaped"); register("minecraft:bookcloning", RecipeBookCloning.class, SHAPELESS, "after:minecraft:shapeless"); //Size 9 register("minecraft:fireworks", RecipeFireworks.class, SHAPELESS, "after:minecraft:shapeless"); //Size 10 register("minecraft:armordyes", RecipesArmorDyes.class, SHAPELESS, "after:minecraft:shapeless"); //Size 10 register("minecraft:mapcloning", RecipesMapCloning.class, SHAPELESS, "after:minecraft:shapeless"); //Size 10 register("forge:shapedore", ShapedOreRecipe.class, SHAPED, "after:minecraft:shaped before:minecraft:shapeless"); register("forge:shapelessore", ShapelessOreRecipe.class, SHAPELESS, "after:minecraft:shapeless"); } @Override public int compare(IRecipe r1, IRecipe r2) { Category c1 = getCategory(r1); Category c2 = getCategory(r2); if (c1 == SHAPELESS && c2 == SHAPED) return 1; if (c1 == SHAPED && c2 == SHAPELESS) return -1; if (r2.getRecipeSize() < r1.getRecipeSize()) return -1; if (r2.getRecipeSize() > r1.getRecipeSize()) return 1; return getPriority(r2) - getPriority(r1); // high priority value first! } private static Set<Class> warned = Sets.newHashSet(); @SuppressWarnings("unchecked") public static void sortCraftManager() { bake(); FMLLog.fine("Sorting recipies"); warned.clear(); Collections.sort(CraftingManager.getInstance().getRecipeList(), INSTANCE); } public static void register(String name, Class<?> recipe, Category category, String dependancies) { assert(category != UNKNOWN) : "Category must not be unknown!"; isDirty = true; SortEntry entry = new SortEntry(name, recipe, category, dependancies); entries.put(name, entry); setCategory(recipe, category); } public static void setCategory(Class<?> recipe, Category category) { assert(category != UNKNOWN) : "Category must not be unknown!"; categories.put(recipe, category); } public static Category getCategory(IRecipe recipe) { return getCategory(recipe.getClass()); } public static Category getCategory(Class<?> recipe) { Class<?> cls = recipe; Category ret = categories.get(cls); if (ret == null) { while (cls != Object.class) { cls = cls.getSuperclass(); ret = categories.get(cls); if (ret != null) { categories.put(recipe, ret); return ret; } } } return ret == null ? UNKNOWN : ret; } private static int getPriority(IRecipe recipe) { Class<?> cls = recipe.getClass(); Integer ret = priorities.get(cls); if (ret == null) { if (!warned.contains(cls)) { FMLLog.info(" Unknown recipe class! %s Modder please refer to %s", cls.getName(), RecipeSorter.class.getName()); warned.add(cls); } cls = cls.getSuperclass(); while (cls != Object.class) { ret = priorities.get(cls); if (ret != null) { priorities.put(recipe.getClass(), ret); FMLLog.fine(" Parent Found: %d - %s", ret.intValue(), cls.getName()); return ret.intValue(); } } } return ret == null ? 0 : ret.intValue(); } private static void bake() { if (!isDirty) return; FMLLog.fine("Forge RecipeSorter Baking:"); DirectedGraph<SortEntry> sorter = new DirectedGraph<SortEntry>(); sorter.addNode(before); sorter.addNode(after); sorter.addEdge(before, after); for (Map.Entry<String, SortEntry> entry : entries.entrySet()) { sorter.addNode(entry.getValue()); } for (Map.Entry<String, SortEntry> e : entries.entrySet()) { SortEntry entry = e.getValue(); boolean postAdded = false; sorter.addEdge(before, entry); for (String dep : entry.after) { if (entries.containsKey(dep)) { sorter.addEdge(entries.get(dep), entry); } } for (String dep : entry.before) { postAdded = true; sorter.addEdge(entry, after); if (entries.containsKey(dep)) { sorter.addEdge(entry, entries.get(dep)); } } if (!postAdded) { sorter.addEdge(entry, after); } } List<SortEntry> sorted = TopologicalSort.topologicalSort(sorter); int x = sorted.size(); for (SortEntry entry : sorted) { FMLLog.fine(" %d: %s", x, entry); priorities.put(entry.cls, x } } }
package com.hubspot.jinjava.objects.collections; import com.google.common.collect.ForwardingList; import com.hubspot.jinjava.interpret.IndexOutOfRangeException; import com.hubspot.jinjava.objects.PyWrapper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; public class PyList extends ForwardingList<Object> implements PyWrapper { private final List<Object> list; public PyList(List<Object> list) { this.list = list; } @Override protected List<Object> delegate() { return list; } public List<Object> toList() { return list; } public boolean append(Object e) { return add(e); } public void insert(int i, Object e) { if (i < 0 || i >= list.size()) { throw createOutOfRangeException(i); } add(i, e); } public boolean extend(PyList e) { return addAll(e.list); } public Object pop() { if (list.size() == 0) { throw createOutOfRangeException(0); } return remove(list.size() - 1); } public Object pop(int index) { if (index < 0 || index >= list.size()) { throw createOutOfRangeException(index); } return remove(index); } public long count(Object o) { return stream().filter(object -> Objects.equals(object, o)).count(); } public void reverse() { Collections.reverse(list); } public PyList copy() { return new PyList(new ArrayList<>(list)); } public int index(Object o) { return indexOf(o); } public int index(Object o, int begin, int end) { for (int i = begin; i < end; i++) { if (Objects.equals(o, get(i))) { return i; } } return -1; } IndexOutOfRangeException createOutOfRangeException(int index) { return new IndexOutOfRangeException( String.format("Index %d is out of range for list of size %d", index, list.size()) ); } }
package com.igexin.log.restapi.schedule; import com.igexin.log.restapi.LogfulProperties; import com.igexin.log.restapi.entity.LogLine; import com.igexin.log.restapi.mongod.MongoLogLineRepository; import com.igexin.log.restapi.parse.GraylogClientService; import com.igexin.log.restapi.weed.WeedFSClientService; import com.igexin.log.restapi.weed.WeedFSMeta; import com.igexin.log.restapi.weed.WeedQueueRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; @Component public class ScheduledTasks { private static final Logger LOG = LoggerFactory.getLogger(ScheduledTasks.class); private static final int PAGE_LIMIT = 2048; private static final long MAX_EXEC_MILLISECOND = 3600000; @Autowired private LogfulProperties logfulProperties; @Autowired private MongoLogLineRepository mongoLogLineRepository; @Autowired private WeedQueueRepository weedQueueRepository; @Autowired private WeedFSClientService weedFSClientService; @Autowired private GraylogClientService graylogClientService; private AtomicLong startExecTime = new AtomicLong(0); @Scheduled(cron = "*/300 * * * * *") @Async public void retryPutQueue() { weedFSClientService.resetServerError(); if (graylogClientService.isConnected()) { List<LogLine> logLineList = mongoLogLineRepository.findAllNotSendLimit(PAGE_LIMIT); for (LogLine logLine : logLineList) { graylogClientService.send(logLine); } } if (weedFSClientService.isConnected()) { List<WeedFSMeta> weedFSMetaList = weedQueueRepository.findAllNotWriteLimit(PAGE_LIMIT); for (WeedFSMeta weedFSMeta : weedFSMetaList) { weedFSClientService.write(weedFSMeta); } } } @Scheduled(cron = "0 0 */1 * * *") // every hour @Async public void clearMemory() { String weedPath = logfulProperties.weedDir(); ConcurrentHashMap<String, WeedFSMeta> map = weedFSClientService.getWeedMetaMap(); for (Map.Entry<String, WeedFSMeta> entry : map.entrySet()) { File file = new File(weedPath + "/" + entry.getKey() + "." + entry.getValue().getExtension()); if (!file.exists()) { map.remove(entry.getKey()); } } } //@Scheduled(cron = "0 10 1 ? * *") // every day 1:10 @Scheduled(cron = "0 0 */6 * * *") @Async public void clearFiles() { LOG.info("++++++++++ clear system file task start ++++++++++"); startExecTime.set(System.currentTimeMillis()); final long ttl = logfulProperties.expires() * 1000; final Path path = Paths.get(logfulProperties.getPath()); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { long current = System.currentTimeMillis(); if (current - startExecTime.get() >= MAX_EXEC_MILLISECOND) { return FileVisitResult.TERMINATE; } else { return FileVisitResult.CONTINUE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { long current = System.currentTimeMillis(); if (attrs.isRegularFile()) { if (!Files.isHidden(file)) { long diff = current - attrs.creationTime().toMillis(); if (diff >= ttl) { Files.delete(file); } } } if (current - startExecTime.get() >= MAX_EXEC_MILLISECOND) { return FileVisitResult.TERMINATE; } else { return FileVisitResult.CONTINUE; } } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.TERMINATE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { long current = System.currentTimeMillis(); if (current - startExecTime.get() >= MAX_EXEC_MILLISECOND) { return FileVisitResult.TERMINATE; } else { return FileVisitResult.CONTINUE; } } }); } catch (Exception e) { LOG.error("Exception", e); } } }
package org.apache.atlas.demo; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasServiceException; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.persistence.Id; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import java.util.Arrays; import java.util.List; public class AtlasEntitiesDemo implements AtlasDemoConstants { public static final String WEBTABLE_NAME = "default.webtable@cluster1"; private final AtlasClient atlasClient; public AtlasEntitiesDemo(String atlasServiceUrl) { atlasClient = new AtlasClient(new String[]{atlasServiceUrl}, new String[]{"admin", "admin"}); } public static void main(String[] args) throws AtlasServiceException, JSONException { AtlasEntitiesDemo atlasEntitiesDemo = new AtlasEntitiesDemo(args[0]); atlasEntitiesDemo.run(); } private void run() throws AtlasServiceException, JSONException { String namespaceId = createNamespace(); String tableId = createTable(namespaceId); retrieveEntity(namespaceId); retrieveEntity(tableId); retrieveEntityByUniqueAttribute(HBASE_TABLE_TYPE, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, WEBTABLE_NAME); updateEntity(tableId); retrieveEntity(tableId); deleteEntity(tableId); retrieveEntity(tableId); } private void deleteEntity(String id) throws AtlasServiceException { System.out.println("Deleting entity with GUID: " + id); AtlasClient.EntityResult entityResult = atlasClient.deleteEntities(id); for (String entity : entityResult.getDeletedEntities()) { System.out.println("Entity deleted: " + entity); } Utils.printDelimiter(); } private void updateEntity(String tableId) throws AtlasServiceException { System.out.println("Updating table state to disabled"); Referenceable tableEntity = new Referenceable(HBASE_TABLE_TYPE); tableEntity.set(TABLE_ATTRIBUTE_IS_ENABLED, false); String entityJson = InstanceSerialization.toJson(tableEntity, true); System.out.println(entityJson); AtlasClient.EntityResult entityResult = atlasClient.updateEntity(tableId, tableEntity); List<String> updateEntities = entityResult.getUpdateEntities(); for (String entity : updateEntities) { System.out.println("Updated Entity ID: " + entity); } Utils.printDelimiter(); } private void retrieveEntityByUniqueAttribute( String typeName, String uniqueAttributeName, String uniqueAttributeValue) throws AtlasServiceException { System.out.println("Retrieving entity with type: " + typeName + "/" + uniqueAttributeName+"=" + uniqueAttributeValue); Referenceable entity = atlasClient.getEntity(typeName, uniqueAttributeName, uniqueAttributeValue); String entityJson = InstanceSerialization.toJson(entity, true); System.out.println(entityJson); Utils.printDelimiter(); } private void retrieveEntity(String guid) throws AtlasServiceException { System.out.println("Retrieving entity with GUID: " + guid); Referenceable entity = atlasClient.getEntity(guid); String entityJson = InstanceSerialization.toJson(entity, true); System.out.println(entityJson); Utils.printDelimiter(); } private String createTable(String namespaceId) throws AtlasServiceException, JSONException { System.out.println("Creating Table, Column Family & Column entities"); Referenceable cssNsiColumn = new Referenceable(HBASE_COLUMN_TYPE); cssNsiColumn.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default.webtable.anchor.cssnsi@cluster1"); cssNsiColumn.set(AtlasClient.NAME, "cssnsi"); cssNsiColumn.set(AtlasClient.OWNER, "crawler"); cssNsiColumn.set(COLUMN_ATTRIBUTE_TYPE, "string"); Referenceable myLookCaColumn = new Referenceable(HBASE_COLUMN_TYPE); myLookCaColumn.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default.webtable.anchor.mylookca@cluster1"); myLookCaColumn.set(AtlasClient.NAME, "mylookca"); myLookCaColumn.set(AtlasClient.OWNER, "crawler"); myLookCaColumn.set(COLUMN_ATTRIBUTE_TYPE, "string"); Referenceable htmlColumn = new Referenceable(HBASE_COLUMN_TYPE); htmlColumn.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default.webtable.contents.html@cluster1"); htmlColumn.set(AtlasClient.NAME, "html"); htmlColumn.set(AtlasClient.OWNER, "crawler"); htmlColumn.set(COLUMN_ATTRIBUTE_TYPE, "byte[]"); Referenceable anchorCf = new Referenceable(HBASE_COLUMN_FAMILY_TYPE); anchorCf.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default.webtable.anchor@cluster1"); anchorCf.set(AtlasClient.NAME, "anchor"); anchorCf.set(AtlasClient.DESCRIPTION, "The anchor column family that stores all links"); anchorCf.set(AtlasClient.OWNER, "crawler"); anchorCf.set(CF_ATTRIBUTE_VERSIONS, 3); anchorCf.set(CF_ATTRIBUTE_IN_MEMORY, true); anchorCf.set(CF_ATTRIBUTE_COMPRESSION, "zip"); anchorCf.set(CF_ATTRIBUTE_BLOCK_SIZE, 128); anchorCf.set(CF_ATTRIBUTE_COLUMNS, Arrays.asList(getReferenceableId(cssNsiColumn), getReferenceableId(myLookCaColumn))); Referenceable contentsCf = new Referenceable(HBASE_COLUMN_FAMILY_TYPE); contentsCf.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default.webtable.contents@cluster1"); contentsCf.set(AtlasClient.NAME, "contents"); contentsCf.set(AtlasClient.DESCRIPTION, "The contents column family that stores the crawled content"); contentsCf.set(AtlasClient.OWNER, "crawler"); contentsCf.set(CF_ATTRIBUTE_VERSIONS, 1); contentsCf.set(CF_ATTRIBUTE_IN_MEMORY, false); contentsCf.set(CF_ATTRIBUTE_COMPRESSION, "lzo"); contentsCf.set(CF_ATTRIBUTE_BLOCK_SIZE, 1024); contentsCf.set(CF_ATTRIBUTE_COLUMNS, Arrays.asList(getReferenceableId(htmlColumn))); Referenceable webTable = new Referenceable(HBASE_TABLE_TYPE); webTable.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, WEBTABLE_NAME); webTable.set(AtlasClient.NAME, "webtable"); webTable.set(AtlasClient.DESCRIPTION, "Table that stores crawled information"); webTable.set(TABLE_ATTRIBUTE_IS_ENABLED, true); webTable.set(TABLE_ATTRIBUTE_NAMESPACE, getReferenceableId(namespaceId, HBASE_NAMESPACE_TYPE)); webTable.set(TABLE_ATTRIBUTE_COLUMN_FAMILIES, Arrays.asList(anchorCf, contentsCf)); List<Referenceable> entities = Arrays.asList(cssNsiColumn, myLookCaColumn, htmlColumn, anchorCf, contentsCf, webTable); JSONArray entitiesJson = new JSONArray(entities.size()); System.out.print("["); for (Referenceable entity : entities) { String entityJson = InstanceSerialization.toJson(entity, true); System.out.print(entityJson); System.out.println(","); entitiesJson.put(entityJson); } System.out.println("]"); List<String> entitiesCreated = atlasClient.createEntity(entities); for (String entity : entitiesCreated) { System.out.println("Entity created: " + entity); } Utils.printDelimiter(); return entitiesCreated.get(entitiesCreated.size()-1); } private Id getReferenceableId(Referenceable fullReferenceable) { return getReferenceableId(fullReferenceable.getId()._getId(), fullReferenceable.getTypeName()); } private Id getReferenceableId(String id, String typeName) { return new Id(id, 0, typeName); } private String createNamespace() throws AtlasServiceException { System.out.println("Creating namespace entity"); Referenceable hbaseNamespace = new Referenceable(HBASE_NAMESPACE_TYPE); hbaseNamespace.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, "default@cluster1"); hbaseNamespace.set(AtlasClient.NAME, "default"); hbaseNamespace.set(AtlasClient.DESCRIPTION, "Default HBase namespace"); hbaseNamespace.set(AtlasClient.OWNER, "hbase_admin"); String hbaseNamespaceJson = InstanceSerialization.toJson(hbaseNamespace, true); System.out.println(hbaseNamespaceJson); List<String> entitiesCreated = atlasClient.createEntity(hbaseNamespace); for (String entity : entitiesCreated) { System.out.println("Entity created: " + entity); } Utils.printDelimiter(); return entitiesCreated.get(0); } }
package com.itakeunconf.codecraft.model; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; @Entity @Table(name = "sessions") @SequenceGenerator(name = "seq_gen", sequenceName = "session_seq") public class PairingSession { @Id @GeneratedValue(generator = "seq_gen", strategy = GenerationType.AUTO) private Long id; @Size(min = 1, max = 255) @NotNull private String sessionName; @NotNull private String language; @NotNull private String practice; @NotNull private String duration; @NotNull @ManyToOne private User creator; @NotNull private String location; private String dateAsString; @NotNull @DateTimeFormat(pattern="yyyy-MM-dd HH:mm") private Date atTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSessionName() { return sessionName; } public void setSessionName(String sessionName) { this.sessionName = sessionName; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getPractice() { return practice; } public void setPractice(String practice) { this.practice = practice; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Date getAtTime() { return atTime; } public void setAtTime(Date atTime) { this.atTime = atTime; } @Transient public String getDateAsString() { return dateAsString; } public void setDateAsString(String dateAsString) { this.dateAsString = dateAsString; } public User getCreator() { return creator; } public void setCreator(User creator) { this.creator = creator; } }
package com.joybean.yogg.crawler; import com.joybean.yogg.datasource.CrawlerDataSource; import com.joybean.yogg.support.YoggException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import us.codecraft.webmagic.Request; import us.codecraft.webmagic.Spider; import us.codecraft.webmagic.SpiderListener; import us.codecraft.webmagic.processor.PageProcessor; import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover; import us.codecraft.webmagic.scheduler.QueueScheduler; import java.util.Arrays; /** * Default website crawler * * @author joybean */ @Component public class DefaultWebsiteCrawler implements WebsiteCrawler { private final static Logger LOGGER = LoggerFactory .getLogger(DefaultWebsiteCrawler.class); private static final int EXPECTED_WEBSITE_NUM = 100000; private PageProcessor pageProcessor; private WebsitePersistentPipeline persistencePipeline; private CrawlerDataSource crawlerDataSource; @Override public Spider start(String... startUrls) { try { if (startUrls.length == 0) { throw new IllegalArgumentException("Start urls for crawler must not be empty"); } int threads = crawlerDataSource.getThreads(); Spider spider = Spider.create(pageProcessor).setScheduler(new QueueScheduler() .setDuplicateRemover(new BloomFilterDuplicateRemover(EXPECTED_WEBSITE_NUM))).addPipeline(persistencePipeline).addUrl(startUrls).thread(threads); spider.setSpiderListeners(Arrays.asList(new SpiderListener() { @Override public void onSuccess(Request request) { } @Override public void onError(Request request) { //TODO notify UI LOGGER.error("Crawler execution error while processing {}", request); } })); spider.start(); return spider; } catch (Throwable e) { LOGGER.error("Failed to launch alexa crawler", e); throw new YoggException(e); } } @Autowired @Qualifier("defaultPageProcessor") public void setPageProcessor(PageProcessor pageProcessor) { this.pageProcessor = pageProcessor; } @Autowired public void setPersistencePipeline(WebsitePersistentPipeline persistencePipeline) { this.persistencePipeline = persistencePipeline; } @Autowired public void setCrawlerDataSource(CrawlerDataSource crawlerDataSource) { this.crawlerDataSource = crawlerDataSource; } }
package com.kolich.aws.services.s3.impl; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.kolich.aws.transport.AwsHeaders.S3_REDUCED_REDUNDANCY; import static com.kolich.aws.transport.AwsHeaders.S3_VERSION_ID; import static com.kolich.aws.transport.AwsHeaders.STORAGE_CLASS; import static com.kolich.common.util.URLEncodingUtils.urlDecode; import static com.kolich.common.util.URLEncodingUtils.urlEncode; import static java.util.regex.Pattern.compile; import static java.util.regex.Pattern.quote; import static org.apache.commons.io.IOUtils.copyLarge; import static org.apache.http.HttpHeaders.CONTENT_TYPE; import static org.apache.http.HttpStatus.SC_NO_CONTENT; import static org.apache.http.HttpStatus.SC_OK; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import org.apache.http.Header; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.transform.Unmarshallers; import com.kolich.aws.services.AbstractAwsService; import com.kolich.aws.services.AbstractAwsSigner; import com.kolich.aws.services.s3.S3Client; import com.kolich.aws.transport.AwsHttpRequest; import com.kolich.common.functional.either.Either; import com.kolich.http.common.response.HttpFailure; import com.kolich.http.common.response.HttpSuccess; public final class KolichS3Client extends AbstractAwsService implements S3Client { /** * Default hostname for the S3 service endpoint. */ private static final String S3_DEFAULT_ENDPOINT = "s3.amazonaws.com"; /** * Specifies the key to start with when listing objects in a bucket. * Amazon S3 lists objects in alphabetical order. */ private static final String S3_PARAM_MARKER = "marker"; /** * Limits the response to keys that begin with the specified prefix. * You can use prefixes to separate a bucket into different groupings * of keys. (You can think of using prefix to make groups in the same * way you'd use a folder in a file system.) */ private static final String S3_PARAM_PREFIX = "prefix"; /** * Bucket names can ONLY contain lowercase letters, numbers, periods (.), * underscores (_), and dashes (-). Bucket names MUST start with a number * or letter. Bucket names MUST be between 3 and 255 characters long. */ private static final Pattern VALID_BUCKET_NAME_PATTERN = compile("\\A[a-z0-9]{1}[a-z0-9_\\-\\.]{1,253}[a-z0-9]{1}\\Z"); private final HttpClient client_; public KolichS3Client(final HttpClient client, final AbstractAwsSigner signer) { super(signer, S3_DEFAULT_ENDPOINT); client_ = client; } public KolichS3Client(final HttpClient client, final String key, final String secret) { this(client, new KolichS3Signer(key, secret)); } private abstract class AwsS3HttpClosure<S> extends AwsBaseHttpClosure<S> { private final String bucketName_; public AwsS3HttpClosure(final HttpClient client, final int expectStatus, final String bucketName) { super(client, expectStatus); bucketName_ = bucketName; } public AwsS3HttpClosure(final HttpClient client, final int expectStatus) { this(client, expectStatus, null); } @Override public final void before(final HttpRequestBase request) throws Exception { validate(); prepare(request); signRequest(new AwsHttpRequest(request, bucketName_)); } public void validate() throws Exception { // Default, nothing. } public void prepare(final HttpRequestBase request) throws Exception { // Default, nothing. } @Override public S success(final HttpSuccess success) throws Exception { return null; // Default, return null on success. } /* @Override public void after(final HttpResponse response, final HttpContext context) throws Exception { if(response.getEntity() != null) { System.out.println(EntityUtils.toString(response.getEntity())); } } */ public final Either<HttpFailure,S> head(final String... path) { return super.head(buildPath(path)); } public final Either<HttpFailure,S> get(final String... path) { return super.get(buildPath(path)); } public final Either<HttpFailure,S> get() { return get((String[])null); } public final Either<HttpFailure,S> put(final String... path) { return super.put(buildPath(path)); } public final Either<HttpFailure,S> put() { return put((String[])null); } public final Either<HttpFailure,S> delete(final String... path) { return super.delete(buildPath(path)); } public final Either<HttpFailure,S> delete() { return delete((String[])null); } private final String buildPath(final String... path) { final StringBuilder sb = new StringBuilder(SLASH_STRING); if(path != null && path.length > 0) { sb.append(urlEncode(varargsToPathString(path))); } return sb.toString(); } } @Override public Either<HttpFailure,List<Bucket>> listBuckets() { return new AwsS3HttpClosure<List<Bucket>>(client_, SC_OK) { @Override public List<Bucket> success(final HttpSuccess success) throws Exception { return new Unmarshallers.ListBucketsUnmarshaller() .unmarshall(success.getContent()); } }.get(); } @Override public Either<HttpFailure,ObjectListing> listObjects(final String bucketName, final String marker, final String... path) { return new AwsS3HttpClosure<ObjectListing>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public void prepare(final HttpRequestBase request) throws Exception { final URIBuilder builder = new URIBuilder(request.getURI()); if(marker != null) { builder.addParameter(S3_PARAM_MARKER, marker); } // Add the prefix string to the request if we have one. if(path != null && path.length > 0) { builder.addParameter(S3_PARAM_PREFIX, varargsToPathString(path)); } request.setURI(builder.build()); } @Override public ObjectListing success(final HttpSuccess success) throws Exception { return new Unmarshallers.ListObjectsUnmarshaller() .unmarshall(success.getContent()); } }.get(); } @Override public Either<HttpFailure,ObjectListing> listObjects(final String bucketName, final String marker) { return listObjects(bucketName, marker, (String[])null); } @Override public Either<HttpFailure,ObjectListing> listObjects(final String bucketName) { return listObjects(bucketName, null); } @Override public Either<HttpFailure,Bucket> createBucket(final String bucketName) { return new AwsS3HttpClosure<Bucket>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public Bucket success(final HttpSuccess success) throws Exception { return new Bucket(bucketName); } }.put(); } @Override public Either<HttpFailure,Void> deleteBucket(final String bucketName) { return new AwsS3HttpClosure<Void>(client_, SC_NO_CONTENT, bucketName){ @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } }.delete(); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final boolean rrs, final ContentType type, final InputStream input, final long contentLength, final String... path) { return new AwsS3HttpClosure<PutObjectResult>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public void prepare(final HttpRequestBase request) throws Exception { if(rrs) { request.setHeader(STORAGE_CLASS, S3_REDUCED_REDUNDANCY); } // Although InputStreamEntity lets you specify a Content-Type, // we're intentionally forcing the issue here. It seems that // setting the content type on the request through a vanilla // InputStreamEntity does not actually do the right thing. if(type != null) { request.setHeader(CONTENT_TYPE, type.toString()); } ((HttpPut)request).setEntity(new InputStreamEntity(input, contentLength)); } @Override public PutObjectResult success(final HttpSuccess success) throws Exception { final PutObjectResult result = new PutObjectResult(); result.setETag(success.getETag()); result.setVersionId(success.getFirstHeader(S3_VERSION_ID)); return result; } }.put(path); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final ContentType type, final InputStream input, final long contentLength, final String... path) { return putObject(bucketName, false, type, input, contentLength, path); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final InputStream input, final long contentLength, final String... path) { return putObject(bucketName, null, input, contentLength, path); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final boolean rrs, final ContentType type, final byte[] object, final String... path) { return putObject(bucketName, rrs, type, new ByteArrayInputStream(object), object.length, path); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final ContentType type, final byte[] object, final String... path) { return putObject(bucketName, false, type, object, path); } @Override public Either<HttpFailure,PutObjectResult> putObject(final String bucketName, final byte[] object, final String... path) { return putObject(bucketName, null, object, path); } @Override public Either<HttpFailure,Void> deleteObject(final String bucketName, final String... path) { return new AwsS3HttpClosure<Void>(client_, SC_NO_CONTENT, bucketName){ @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } }.delete(path); } @Override public Either<HttpFailure,List<Header>> getObject(final String bucketName, final OutputStream destination, final String... path) { return new AwsS3HttpClosure<List<Header>>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public List<Header> success(final HttpSuccess success) throws Exception { // Copy the object. copyLarge(success.getContent(), destination); // Get and return the headers on the HTTP response. // This is where stuff like "Content-Type" and // "Content-Length" live. return Arrays.asList(success.getResponse().getAllHeaders()); } }.get(path); } @Override public Either<HttpFailure,byte[]> getObject(final String bucketName, final String... path) { return new AwsS3HttpClosure<byte[]>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } @Override public byte[] success(final HttpSuccess success) throws Exception { final ByteArrayOutputStream os = new ByteArrayOutputStream(); // Copy the object to the ByteArrayOutputStream. The consumer // of this method should be keenly aware that this method // copies the response body entirely into memory in order to // ultimately return the response as a byte[] array. copyLarge(success.getContent(), os); return os.toByteArray(); } }.get(path); } @Override public boolean objectExists(final String bucketName, final String... path) { return new AwsS3HttpClosure<Void>(client_, SC_OK, bucketName) { @Override public void validate() throws Exception { checkNotNull(bucketName, "Bucket name cannot be null."); checkState(isValidBucketName(bucketName), "Invalid bucket name, " + "did not match expected bucket name pattern."); } }.head(path).success(); } private static final boolean isValidBucketName(final String bucketName) { return VALID_BUCKET_NAME_PATTERN.matcher(bucketName).matches(); } /** * Given a variable list of arguments, prepare a fully qualified * path to a key in an S3 bucket. Each prefix in the list is * separated by an appropriate path separator. The resulting string * is NOT URL-encoded, but each prefix component is URL-encoded before * concatenated to the resulting path -- slashes and other special * characters in a prefix component that may be interpreted wrong when * used in a path are URL-encoded so we won't have any conflicts. * Note that empty strings in the varargs prefix list will NOT be appended * to the resulting prefix string. * Example: * <code> * new String[]{"accounts", "", "silly/path+dog"} * </code> * is returned as * <code> * "accounts/silly%2Fpath%2Bdog" * </code> */ public static final String varargsToPathString(final String... path) { checkNotNull(path, "The path string list cannot be null."); final StringBuilder sb = new StringBuilder(); for(int i = 0, l = path.length; i < l; i++) { if(!EMPTY_STRING.equals(path[i])) { sb.append(urlEncode(path[i])); // Don't append a "/" if this element is the last in the list. sb.append((i < l-1) ? SLASH_STRING : EMPTY_STRING); } } return sb.toString(); } /** * Given a prefix string, generated by * {@link KolichS3Client#varargsToPathString(String...)}, returns * a variable arguments compatible String[] array containing each prefix * component. Each component in the resulting prefix String[] array will be * fully URL-decoded. Note that any empty strings, once the prefix string * is split around a path separator, are NOT added to the resulting * varargs list. */ public static final String[] pathStringToVarargs(final String path) { checkNotNull(path, "The path string list cannot be null."); final List<String> prl = new ArrayList<String>(); for(final String p : path.split(quote(SLASH_STRING))) { if(!EMPTY_STRING.equals(p)) { prl.add(urlDecode(p)); } } return prl.toArray(new String[]{}); } /** * Appends the given key to the end of the prefix list, then returns a * a new String[] array representing that list. */ public static final String[] appendKeyToPath(final String key, final String... path) { checkNotNull(key, "The key to append cannot be null."); checkNotNull(path, "The path string list cannot be null."); final List<String> prl = new ArrayList<String>(Arrays.asList(path)); // The entity key becomes the last element in the prefix list. prl.add(key); return prl.toArray(new String[]{}); } }
package org.biouno.unochoice.model; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.biouno.unochoice.util.SafeHtmlExtendedMarkupFormatter; import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript; import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext; import org.kohsuke.stapler.DataBoundConstructor; import groovy.lang.Binding; import hudson.Extension; import hudson.PluginManager; import hudson.Util; import jenkins.model.Jenkins; /** * A Groovy script. * * @author Bruno P. Kinoshita * @since 0.23 */ public class GroovyScript extends AbstractScript { /* * Serial UID. */ private static final long serialVersionUID = -3741105849416473898L; private static final Logger LOGGER = Logger.getLogger(GroovyScript.class.getName()); /** * Script content. */ @Deprecated private transient String script; /** * Secure script content. */ private SecureGroovyScript secureScript; @Nullable @Deprecated private transient String fallbackScript; /** * Secure fallback script content. */ @Nullable private SecureGroovyScript secureFallbackScript; @Deprecated public GroovyScript(String script, String fallbackScript) { this(new SecureGroovyScript(script, false, null), new SecureGroovyScript(fallbackScript, false, null)); } @DataBoundConstructor public GroovyScript(SecureGroovyScript script, SecureGroovyScript fallbackScript) { if (script != null) { this.secureScript = script.configuringWithNonKeyItem(); } if (fallbackScript != null) { this.secureFallbackScript = fallbackScript.configuringWithNonKeyItem(); } } private Object readResolve() { if (secureScript == null) { if (script != null) { secureScript = new SecureGroovyScript(script, false, null).configuring(ApprovalContext.create()); } } if (secureFallbackScript == null) { if (fallbackScript != null) { secureFallbackScript = new SecureGroovyScript(fallbackScript, false, null) .configuring(ApprovalContext.create()); } } return this; } /** * @return the script */ public SecureGroovyScript getScript() { return secureScript; } /** * @return the fallbackScript */ public SecureGroovyScript getFallbackScript() { return secureFallbackScript; } /* * (non-Javadoc) * * @see org.biouno.unochoice.model.Script#eval() */ @Override public Object eval() { return eval(Collections.emptyMap()); } /* * (non-Javadoc) * * @see org.biouno.unochoice.model.Script#eval(java.util.Map) */ @Override public Object eval(Map<String, String> parameters) throws RuntimeException { if (secureScript == null) { return null; } final Jenkins instance = Jenkins.getInstanceOrNull(); ClassLoader cl = null; if (instance != null) { try { PluginManager pluginManager = instance.getPluginManager(); cl = pluginManager.uberClassLoader; } catch (Exception e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } } if (cl == null) { cl = Thread.currentThread().getContextClassLoader(); } final Binding context = new Binding(); // @SuppressWarnings("unchecked") final Map<String, String> envVars = System.getenv(); for (Entry<String, String> parameter : parameters.entrySet()) { Object value = parameter.getValue(); if (value != null) { if (value instanceof String) { value = Util.replaceMacro((String) value, envVars); } context.setVariable(parameter.getKey(), value); } } try { Object returnValue = secureScript.evaluate(cl, context, null); // sanitize the text if running script in sandbox mode if (secureScript.isSandbox()) { returnValue = resolveTypeAndSanitize(returnValue); } return returnValue; } catch (Exception re) { if (this.secureFallbackScript != null) { try { LOGGER.log(Level.FINEST, "Fallback to default script...", re); Object returnValue = secureFallbackScript.evaluate(cl, context, null); // sanitize the text if running script in sandbox mode if (secureFallbackScript.isSandbox()) { returnValue = resolveTypeAndSanitize(returnValue); } return returnValue; } catch (Exception e2) { LOGGER.log(Level.WARNING, "Error executing fallback script", e2); throw new RuntimeException("Failed to evaluate fallback script: " + e2.getMessage(), e2); } } else { LOGGER.log(Level.WARNING, "No fallback script configured for '%s'"); throw new RuntimeException("Failed to evaluate script: " + re.getMessage(), re); } } } /** * Resolves the type of the return value, and then applies the sanitization to * the value before returning it. * * <p>If the type is text, it will simply pass the value through the markup formatter.</p> * * <p>If the type is a list, then it will replace each value by itself sanitized * (i.e. [sanitizeFn(value) for value in list]).</p> * * <p>Finally, if it is a map, does similar as with the list, and calls replaceAll to * apply the sanitize function to each member of the map.</p> * * @param returnValue a value of type String, List, or Map returned after the Groovy code was evaluated * @return sanitized value * @throws RuntimeException if the type of the given {@code returnValue} is not String, List, or Map */ private Object resolveTypeAndSanitize(Object returnValue) { if (returnValue instanceof CharSequence) { return sanitizeString(returnValue); } else if (returnValue instanceof List) { List<?> list = (List<?>) returnValue; return list.stream() .map(this::sanitizeString) .collect(Collectors.toList()); } else if (returnValue instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) returnValue; Map<Object, Object> returnMap = new LinkedHashMap<>(map.size()); map.forEach((key, value) -> { String newKey = sanitizeString(key); String newValue = sanitizeString(value); returnMap.put(newKey, newValue); }); return returnMap; } throw new RuntimeException("Return type of Groovy script must be a valid String, List, or Map"); } /** * Sanitize a string using the plug-in safe HTML markup formatter. * @param input the input object * @return sanitized input, or {@code null} if the input is {@code null} */ private String sanitizeString(Object input) { if (input == null) { return null; } try { return SafeHtmlExtendedMarkupFormatter.INSTANCE.translate(input.toString()); } catch (IOException e) { throw new RuntimeException(String.format("Failed to sanitize input due to: %s", e.getMessage()), e); } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { final String secureScriptText = (secureScript != null) ? secureScript.getScript() : ""; final String fallbackScriptText = (secureFallbackScript != null) ? secureFallbackScript.getScript() : ""; return "GroovyScript [script=" + secureScriptText + ", fallbackScript=" + fallbackScriptText + "]"; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((secureFallbackScript == null) ? 0 : secureFallbackScript.hashCode()); result = prime * result + ((secureScript == null) ? 0 : secureScript.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GroovyScript other = (GroovyScript) obj; if (secureFallbackScript == null) { if (other.secureFallbackScript != null) return false; } else if (!secureFallbackScript.equals(other.secureFallbackScript)) return false; if (secureScript == null) { return other.secureScript == null; } return secureScript.equals(other.secureScript); } @Extension public static class DescriptorImpl extends ScriptDescriptor { /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Groovy Script"; } } }
package com.philihp.weblabora.model; import static com.philihp.weblabora.model.TerrainTypeEnum.*; import java.util.Set; import com.google.common.collect.ArrayTable; import com.google.common.collect.DiscreteDomains; import com.google.common.collect.Ranges; import com.google.common.collect.Table; public class CommandBuyDistrict implements MoveCommand { public static enum Side { HILLS(MOOR, FOREST, FOREST, HILLSIDE, HILLSIDE), PLAINS(FOREST, TerrainTypeEnum.PLAINS, TerrainTypeEnum.PLAINS, TerrainTypeEnum.PLAINS, HILLSIDE); private TerrainTypeEnum[] types; Side(TerrainTypeEnum... types) { this.types = types; } public TerrainTypeEnum getType(int column) { return types[column]; } }; @Override public void execute(Board board, CommandParameters params) throws WeblaboraException { execute(board, Integer.parseInt(params.get(0)), Side.valueOf(params.get(1)) ); } public static void execute(Board board, int y, Side side) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); int cost = board.purchaseDistrict(); if(player.getCoins() < cost) throw new WeblaboraException("Purchase price for a district is "+cost+", but player "+player.getColor()+" only has "+player.getCoins()+"."); player.subtractCoins(cost); Landscape landscape = player.getLandscape(); Table<Integer, Integer, Terrain> oldTerrain = landscape.getTerrain(); checkForOverlap(oldTerrain, y); checkForConnection(oldTerrain, y); Set<Integer> oldRows = oldTerrain.rowKeySet(); Set<Integer> oldColumns = oldTerrain.columnKeySet(); int minRow = y; int maxRow = y; for(int i : oldRows) { if(i < minRow) minRow = i; if(i > maxRow) maxRow = i; } Set<Integer> newRows = Ranges.closed(minRow, maxRow).asSet(DiscreteDomains.integers()); ArrayTable<Integer, Integer, Terrain> newTerrain = ArrayTable.create(newRows, oldColumns); for(Integer rowKey : newRows) { for(Integer columnKey : oldColumns) { if(oldTerrain.contains(rowKey, columnKey)) { newTerrain.put(rowKey, columnKey, oldTerrain.get(rowKey, columnKey)); } } } for(Integer columnKey : Ranges.closed(0,4).asSet(DiscreteDomains.integers())) { newTerrain.put(y, columnKey, new Terrain(landscape, side.getType(columnKey), null, columnKey, y)); } landscape.setTerrain(newTerrain); } private static void checkForConnection( Table<Integer, Integer, Terrain> oldTerrain, int y) throws WeblaboraException { boolean west = oldTerrain.contains(y,-1) && oldTerrain.get(y,-1) != null; boolean east = oldTerrain.contains(y,5) && oldTerrain.get(y,5) != null; boolean north = oldTerrain.contains(y-1, 0) && oldTerrain.get(y-1,0) != null; boolean south = oldTerrain.contains(y+1, 0) && oldTerrain.get(y+1,0) != null; if( (north || south || east || west) == false) { throw new WeblaboraException("Cannot put a district at "+y+", as it does not connect to the rest of the landscape"); } } private static void checkForOverlap( Table<Integer, Integer, Terrain> oldTerrain, int y) throws WeblaboraException { if(oldTerrain.contains(y, 0) && oldTerrain.get(y, 0) != null) { throw new WeblaboraException("Cannot put a district at "+y+", as it would overlap"); } } }
package com.richrelevance.stash.plugin; import com.atlassian.event.api.EventListener; import com.atlassian.stash.event.pull.*; import com.atlassian.stash.pull.PullRequest; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.*; import static java.net.HttpURLConnection.HTTP_OK; public class PullRequestHook { // add log4j.logger.attlassian.plugin=DEBUG to stash-config.properties on Stash home directory to use this logger // private static final Logger log = LoggerFactory.getLogger("atlassian.plugin"); // Needs a log4j.properties private static final Logger log = LoggerFactory.getLogger(PullRequestHook.class); private final String BASEURL = System.getProperty("prhook.baseUrl", "http://localhost/bamboo"); private final String URL = System.getProperty("prhook.url", "$BASEURL/rest/api/latest/queue/$PLAN?bamboo.variable.prnumber=$PRNUMBER&os_authType=basic"); private final String USER = System.getProperty("prhook.user", "user"); private final String PASSWORD = System.getProperty("prhook.password", "password"); @EventListener public void onPullRequestOpen(PullRequestOpenedEvent event) { triggerPullRequest(event.getPullRequest()); } @EventListener public void onPullRequestReopen(PullRequestReopenedEvent event) { triggerPullRequest(event.getPullRequest()); } @EventListener public void onPullRequestRescope(PullRequestRescopedEvent event) { } @EventListener public void onPullRequestComment(PullRequestCommentAddedEvent event) { } private void triggerPullRequest(PullRequest pullRequest) { final String url = getUrl(pullRequest); if (url != null && !url.isEmpty()) { String authStringEnc = getAuthenticationString(); final HttpURLConnection connection; try { URLConnection conn = new java.net.URL(url).openConnection(); if (conn instanceof HttpURLConnection) { connection = (HttpURLConnection) conn; } else { log.error("not an Http connection: " + url); return; } } catch (IOException e) { log.error("unable to open a connection to " + url, e); return; } connection.setRequestProperty("Authorization", "Basic " + authStringEnc); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Accept-Charset", "UTF-8"); try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { log.error("unable to set method to POST", e); return; } try { connection.connect(); } catch (SocketTimeoutException e) { log.error("timeout connecting to " + url, e); } catch (IOException e) { log.error("unable to connect to " + url, e); } try { final int responseCode = connection.getResponseCode(); if (responseCode == -1) { log.error("response from " + url + "is not a valid http response"); return; } else if (responseCode != HTTP_OK) { log.error("failed to trigger " + url + ": " + responseCode + "(" + connection.getResponseMessage() + ")"); return; } } catch (IOException e) { log.error("unable to get response code from connection to " + url); return; } try { String encoding = connection.getContentEncoding(); encoding = encoding == null ? "UTF-8" : encoding; final InputStream buildRequisitionResponse = connection.getInputStream(); final String response = IOUtils.toString(buildRequisitionResponse, encoding); log.info("response from " + url + ": " + response); buildRequisitionResponse.close(); } catch (IOException e) { log.error("unable to get POST response", e); } } else { log.error("empty trigger url"); } } private String getUrl(PullRequest pullRequest) { final Long prNumber = pullRequest.getId(); if (prNumber != null) { return URL.replace("$BASEURL", BASEURL).replace("$PLAN", urlEncode("RRCORE-PRTEST")).replace("$PRNUMBER", prNumber.toString()); } else { log.error("id of pull request is null:" + pullRequest); return ""; } } private String getAuthenticationString() { final String authString = USER + ":" + PASSWORD; final byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); return new String(authEncBytes); } private static String urlEncode(String string) { try { return URLEncoder.encode(string, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
package com.ss.editor.plugin.api; import com.jme3.post.Filter; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.JmeThread; import com.ss.editor.util.EditorUtil; import com.ss.rlib.util.ClassUtils; import com.ss.rlib.util.array.Array; import com.ss.rlib.util.array.ArrayFactory; import com.ss.rlib.util.dictionary.DictionaryFactory; import com.ss.rlib.util.dictionary.ObjectDictionary; import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; /** * The class with some extensions to editor's render. * * @author JavaSaBr */ public class RenderFilterExtension { @NotNull private static final RenderFilterExtension INSTANCE = new RenderFilterExtension(); @FromAnyThread public static @NotNull RenderFilterExtension getInstance() { return INSTANCE; } /** * The map filter to its refresh action. */ @NotNull private final ObjectDictionary<Filter, Consumer<@NotNull ? extends Filter>> refreshActions; /** * The additional filters. */ @NotNull private final Array<Filter> filters; private RenderFilterExtension() { this.filters = ArrayFactory.newArray(Filter.class); this.refreshActions = DictionaryFactory.newObjectDictionary(); } /** * Register the new additional filter. * * @param filter the filter. */ @JmeThread public void register(@NotNull final Filter filter) { this.filters.add(filter); EditorUtil.getGlobalFilterPostProcessor() .addFilter(filter); } /** * Set the handler to handle refresh events. * * @param filter the filter. * @param handler the handler. * @param <T> the filter's type. */ @JmeThread public <T extends Filter> void setOnRefresh(@NotNull final T filter, @NotNull final Consumer<@NotNull T> handler) { if (!filters.contains(filter)) { throw new IllegalArgumentException("The filter " + filter + "isn't registered."); } refreshActions.put(filter, handler); } /** * Refresh all filters. */ @JmeThread public void refreshFilters() { refreshActions.forEach((filter, consumer) -> { final Consumer<@NotNull Filter> cast = ClassUtils.unsafeCast(consumer); cast.accept(filter); }); } @JmeThread public void enableFilters() { } @JmeThread public void disableFilters() { } }
package org.lightmare.scannotation; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import org.apache.log4j.Logger; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.scannotation.archiveiterator.Filter; import org.scannotation.archiveiterator.IteratorFactory; import org.scannotation.archiveiterator.StreamIterator; /** * Extension of {@link org.scannotation.AnnotationDB} for saving Map< * {@link String}, {@link URL}> of class name and {@link URL} for its archive * * @author levan * @since 0.0.18-SNAPSHOT */ public class AnnotationDB extends org.scannotation.AnnotationDB { private static final long serialVersionUID = 1L; // To store which class in which URL is found protected Map<String, URL> classOwnersURLs = new WeakHashMap<String, URL>(); // To store which class in which File is found protected Map<String, String> classOwnersFiles = new WeakHashMap<String, String>(); // File separator and extension characters private static final char FILE_EXTEWNTION_SELIM = '.'; private static final char FILE_SEPARATOR_CHAR = '/'; // Log messages private static String SCANNING_STARTED_MESSAGE = "Started scanning for archives on @Stateless annotation"; private static String SCANNING_FINISHED_MESSAGE = "Finished scanning for archives on @Stateless annotation"; private static final String SCANNING_URL_MESSAGE = "Scanning URL "; private static final String FINISHED_URL_MESSAGE = "Finished URL scanning "; private static final Logger LOG = Logger.getLogger(AnnotationDB.class); /** * Filters java archive files * * @author levan * @since 0.0.84-SNAPSHOT */ protected class ArchiveFilter implements Filter { @Override public boolean accepts(String subFileName) { boolean valid; if (subFileName.endsWith(ArchiveUtils.CLASS_FILE_EXT)) { if (subFileName.startsWith(ArchiveUtils.FILE_SEPARATOR)) { subFileName = subFileName .substring(CollectionUtils.SECOND_INDEX); } String fileNameForCheck = subFileName.replace( FILE_SEPARATOR_CHAR, FILE_EXTEWNTION_SELIM); valid = !ignoreScan(fileNameForCheck); } else { valid = Boolean.FALSE; } return valid; } } /** * Gets file name from passed {@link URL} instance * * @param url * @return {@link String} */ private String getFileName(URL url) { String fileName = url.getFile(); int lastIndex = fileName.lastIndexOf(ArchiveUtils.FILE_SEPARATOR); if (lastIndex > StringUtils.NOT_EXISTING_INDEX) { ++lastIndex; fileName = fileName.substring(lastIndex); } return fileName; } /** * Checks file name should be or not ignored from scanning file list * * @param intf * @return <code>boolean</code> */ private boolean ignoreScan(String intf) { boolean valid = Boolean.FALSE; String value; String ignored; int length = ignoredPackages.length; for (int i = CollectionUtils.FIRST_INDEX; ObjectUtils.notTrue(valid) && i < length; i++) { ignored = ignoredPackages[i]; value = StringUtils.concat(ignored, FILE_EXTEWNTION_SELIM); if (intf.startsWith(value)) { valid = Boolean.TRUE; } } return valid; } private <K, V> void putIfAbscent(Map<K, V> map, K key, V value) { boolean contained = map.containsKey(key); if (ObjectUtils.notTrue(contained)) { map.put(key, value); } } /** * caches scanned file information * * @param annotations * @param className * @param url */ protected void populate(Annotation[] annotations, String className, URL url) { if (ObjectUtils.notNull(annotations)) { Set<String> classAnnotations = classIndex.get(className); String fileName; boolean contained; for (Annotation ann : annotations) { Set<String> classes = annotationIndex.get(ann.getTypeName()); if (classes == null) { classes = new HashSet<String>(); annotationIndex.put(ann.getTypeName(), classes); } classes.add(className); putIfAbscent(classOwnersURLs, className, url); putIfAbscent(classOwnersFiles,className, url); classAnnotations.add(ann.getTypeName()); } } } /** * Scans passed {@link ClassFile} instance for specific annotations * * @param cf * @param url */ protected void scanClass(ClassFile cf, URL url) { String className = cf.getName(); AnnotationsAttribute visible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); AnnotationsAttribute invisible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.invisibleTag); if (ObjectUtils.notNull(visible)) { populate(visible.getAnnotations(), className, url); } if (ObjectUtils.notNull(invisible)) { populate(invisible.getAnnotations(), className, url); } } /** * Scans passed {@link InputStream} instance for specific annotations * * @param bits * @param url * @throws IOException */ public void scanClass(InputStream bits, URL url) throws IOException { DataInputStream dstream = new DataInputStream(new BufferedInputStream( bits)); ClassFile cf = null; try { cf = new ClassFile(dstream); String classFileName = cf.getName(); classIndex.put(classFileName, new HashSet<String>()); if (scanClassAnnotations) { scanClass(cf, url); } if (scanMethodAnnotations || scanParameterAnnotations) { scanMethods(cf); } if (scanFieldAnnotations) { scanFields(cf); } // create an index of interfaces the class implements String[] interfaces = cf.getInterfaces(); if (ObjectUtils.notNull(interfaces)) { Set<String> intfs = new HashSet<String>(); for (String intf : interfaces) { intfs.add(intf); } implementsIndex.put(classFileName, intfs); } } finally { IOUtils.closeAll(dstream, bits); } } @Override public void scanArchives(URL... urls) throws IOException { LOG.info(SCANNING_STARTED_MESSAGE); for (URL url : urls) { Filter filter = new ArchiveFilter(); LOG.info(StringUtils.concat(SCANNING_URL_MESSAGE, url)); StreamIterator it = IteratorFactory.create(url, filter); InputStream stream = it.next(); while (ObjectUtils.notNull(stream)) { scanClass(stream, url); stream = it.next(); } LOG.info(StringUtils.concat(FINISHED_URL_MESSAGE, url)); } LOG.info(SCANNING_FINISHED_MESSAGE); } public Map<String, URL> getClassOwnersURLs() { return classOwnersURLs; } public Map<String, String> getClassOwnersFiles() { return classOwnersFiles; } }
package org.lightmare.scannotation; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import org.apache.log4j.Logger; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.scannotation.archiveiterator.Filter; import org.scannotation.archiveiterator.IteratorFactory; import org.scannotation.archiveiterator.StreamIterator; /** * Extension of {@link org.scannotation.AnnotationDB} for saving Map< * {@link String}, {@link URL}> of class name and {@link URL} for its archive * * @author levan * */ public class AnnotationDB extends org.scannotation.AnnotationDB { private static final long serialVersionUID = 1L; // To store which class in which URL is found protected Map<String, URL> classOwnersURLs = new WeakHashMap<String, URL>(); // To store which class in which File is found protected Map<String, String> classOwnersFiles = new WeakHashMap<String, String>(); // File separator and extension characters private static final char FILE_EXTEWNTION_SELIM = '.'; private static final char FILE_SEPARATOR_CHAR = '/'; private static String SCANNING_STARTED_MESSAGE = "Started scanning for archives on @Stateless annotation"; private static String SCANNING_FINISHED_MESSAGE = "Finished scanning for archives on @Stateless annotation"; private static final String SCANNING_URL_MESSAGE = "Scanning URL "; private static final Logger LOG = Logger.getLogger(AnnotationDB.class); /** * Filters java archive files * * @author levan * @since 0.0.84-SNAPSHOT */ protected class ArchiveFilter implements Filter { @Override public boolean accepts(String subFileName) { boolean valid; if (subFileName.endsWith(ArchiveUtils.CLASS_FILE_EXT)) { if (subFileName.startsWith(ArchiveUtils.FILE_SEPARATOR)) { subFileName = subFileName .substring(CollectionUtils.SECOND_INDEX); } String fileNameForCheck = subFileName.replace( FILE_SEPARATOR_CHAR, FILE_EXTEWNTION_SELIM); valid = !ignoreScan(fileNameForCheck); } else { valid = Boolean.FALSE; } return valid; } } private String getFileName(URL url) { String fileName = url.getFile(); int lastIndex = fileName.lastIndexOf(ArchiveUtils.FILE_SEPARATOR); if (lastIndex > StringUtils.NOT_EXISTING_INDEX) { ++lastIndex; fileName = fileName.substring(lastIndex); } return fileName; } private boolean ignoreScan(String intf) { boolean valid = Boolean.FALSE; String value; String ignored; int length = ignoredPackages.length; for (int i = CollectionUtils.FIRST_INDEX; ObjectUtils.notTrue(valid) && i < length; i++) { ignored = ignoredPackages[i]; value = StringUtils.concat(ignored, FILE_EXTEWNTION_SELIM); if (intf.startsWith(value)) { valid = Boolean.TRUE; } } return valid; } protected void populate(Annotation[] annotations, String className, URL url) { if (ObjectUtils.notNull(annotations)) { Set<String> classAnnotations = classIndex.get(className); String fileName; for (Annotation ann : annotations) { Set<String> classes = annotationIndex.get(ann.getTypeName()); if (classes == null) { classes = new HashSet<String>(); annotationIndex.put(ann.getTypeName(), classes); } classes.add(className); if (!classOwnersURLs.containsKey(className)) { classOwnersURLs.put(className, url); } if (!classOwnersFiles.containsKey(className)) { fileName = getFileName(url); classOwnersFiles.put(className, fileName); } classAnnotations.add(ann.getTypeName()); } } } protected void scanClass(ClassFile cf, URL url) { String className = cf.getName(); AnnotationsAttribute visible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.visibleTag); AnnotationsAttribute invisible = (AnnotationsAttribute) cf .getAttribute(AnnotationsAttribute.invisibleTag); if (ObjectUtils.notNull(visible)) { populate(visible.getAnnotations(), className, url); } if (ObjectUtils.notNull(invisible)) { populate(invisible.getAnnotations(), className, url); } } public void scanClass(InputStream bits, URL url) throws IOException { DataInputStream dstream = new DataInputStream(new BufferedInputStream( bits)); ClassFile cf = null; try { cf = new ClassFile(dstream); String classFileName = cf.getName(); classIndex.put(classFileName, new HashSet<String>()); if (scanClassAnnotations) { scanClass(cf, url); } if (scanMethodAnnotations || scanParameterAnnotations) { scanMethods(cf); } if (scanFieldAnnotations) { scanFields(cf); } // create an index of interfaces the class implements String[] interfaces = cf.getInterfaces(); if (ObjectUtils.notNull(interfaces)) { Set<String> intfs = new HashSet<String>(); for (String intf : interfaces) { intfs.add(intf); } implementsIndex.put(classFileName, intfs); } } finally { IOUtils.closeAll(dstream, bits); } } @Override public void scanArchives(URL... urls) throws IOException { LOG.info(SCANNING_STARTED_MESSAGE); for (URL url : urls) { Filter filter = new ArchiveFilter(); LOG.info(StringUtils.concat(SCANNING_URL_MESSAGE, url)); StreamIterator it = IteratorFactory.create(url, filter); InputStream stream = it.next(); while (ObjectUtils.notNull(stream)) { scanClass(stream, url); stream = it.next(); } LOG.info(StringUtils.concat("Finished URL scanning ", url)); } LOG.info("Finished scanning for archives on @Stateless annotation"); } public Map<String, URL> getClassOwnersURLs() { return classOwnersURLs; } public Map<String, String> getClassOwnersFiles() { return classOwnersFiles; } }
package com.telefonica.iot.cygnus.sinks; import com.telefonica.iot.cygnus.backends.mysql.MySQLBackend.TableType; import static com.telefonica.iot.cygnus.backends.mysql.MySQLBackend.TableType.TABLEBYDESTINATION; import static com.telefonica.iot.cygnus.backends.mysql.MySQLBackend.TableType.TABLEBYSERVICEPATH; import com.telefonica.iot.cygnus.backends.mysql.MySQLBackendImpl; import com.telefonica.iot.cygnus.containers.NotifyContextRequest; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.Constants; import com.telefonica.iot.cygnus.utils.Utils; import java.util.ArrayList; import java.util.Map; import org.apache.flume.Context; public class OrionMySQLSink extends OrionSink { private static final CygnusLogger LOGGER = new CygnusLogger(OrionMySQLSink.class); private String mysqlHost; private String mysqlPort; private String mysqlUsername; private String mysqlPassword; private TableType tableType; private boolean rowAttrPersistence; private MySQLBackendImpl persistenceBackend; /** * Constructor. */ public OrionMySQLSink() { super(); } // OrionMySQLSink /** * Gets the MySQL host. It is protected due to it is only required for testing purposes. * @return The MySQL host */ protected String getMySQLHost() { return mysqlHost; } // getMySQLHost /** * Gets the MySQL port. It is protected due to it is only required for testing purposes. * @return The MySQL port */ protected String getMySQLPort() { return mysqlPort; } // getMySQLPort /** * Gets the MySQL username. It is protected due to it is only required for testing purposes. * @return The MySQL username */ protected String getMySQLUsername() { return mysqlUsername; } // getMySQLUsername /** * Gets the MySQL password. It is protected due to it is only required for testing purposes. * @return The MySQL password */ protected String getMySQLPassword() { return mysqlPassword; } // getMySQLPassword /** * Returns if the attribute persistence is row-based. It is protected due to it is only required for testing * purposes. * @return True if the attribute persistence is row-based, false otherwise */ protected boolean getRowAttrPersistence() { return rowAttrPersistence; } // getRowAttrPersistence /** * Returns the table type. It is protected due to it is only required for testing purposes. * @return The table type */ protected TableType getTableType() { return tableType; } // getTableType /** * Returns the persistence backend. It is protected due to it is only required for testing purposes. * @return The persistence backend */ protected MySQLBackendImpl getPersistenceBackend() { return persistenceBackend; } // getPersistenceBackend /** * Sets the persistence backend. It is protected due to it is only required for testing purposes. * @param persistenceBackend */ protected void setPersistenceBackend(MySQLBackendImpl persistenceBackend) { this.persistenceBackend = persistenceBackend; } // setPersistenceBackend @Override public void configure(Context context) { mysqlHost = context.getString("mysql_host", "localhost"); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_host=" + mysqlHost + ")"); mysqlPort = context.getString("mysql_port", "3306"); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_port=" + mysqlPort + ")"); mysqlUsername = context.getString("mysql_username", "opendata"); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_username=" + mysqlUsername + ")"); // FIXME: mysqlPassword should be read as a SHA1 and decoded here mysqlPassword = context.getString("mysql_password", "unknown"); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_password=" + mysqlPassword + ")"); String tableTypeStr = context.getString("table_type", "table-per-destination"); tableType = TableType.valueOf(tableTypeStr.replaceAll("-", "").toUpperCase()); rowAttrPersistence = context.getString("attr_persistence", "row").equals("row"); LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence=" + (rowAttrPersistence ? "row" : "column") + ")"); super.configure(context); } // configure @Override public void start() { // create the persistence backend LOGGER.debug("[" + this.getName() + "] MySQL persistence backend created"); persistenceBackend = new MySQLBackendImpl(mysqlHost, mysqlPort, mysqlUsername, mysqlPassword); super.start(); LOGGER.info("[" + this.getName() + "] Startup completed"); } // start @Override void persistOne(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception { throw new Exception("Not yet supoported. You should be using persistBatch method."); } // persistOne @Override void persistBatch(Batch defaultBatch, Batch groupedBatch) throws Exception { // select batch depending on the enable grouping parameter Batch batch = (enableGrouping ? groupedBatch : defaultBatch); if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // iterate on the destinations, for each one a single create / append will be performed for (String destination : batch.getDestinations()) { LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // get the sub-batch for this destination ArrayList<CygnusEvent> subBatch = batch.getEvents(destination); // get an aggregator for this destination and initialize it MySQLAggregator aggregator = getAggregator(rowAttrPersistence); aggregator.initialize(subBatch.get(0)); for (CygnusEvent cygnusEvent : subBatch) { aggregator.aggregate(cygnusEvent); } // for // persist the fieldValues persistAggregation(aggregator); batch.setPersisted(destination); } // for } // persistBatch /** * Class for aggregating fieldValues. */ private abstract class MySQLAggregator { // string containing the data fieldValues protected String aggregation; protected String service; protected String servicePath; protected String destination; protected String dbName; protected String tableName; protected String typedFieldNames; protected String fieldNames; public MySQLAggregator() { aggregation = ""; } // MySQLAggregator public String getAggregation() { return aggregation; } // getAggregation public String getDbName() { return dbName; } // getDbName public String getTableName() { return tableName; } // getTableName public String getTypedFieldNames() { return typedFieldNames; } // getTypedFieldNames public String getFieldNames() { return fieldNames; } // getFieldNames public void initialize(CygnusEvent cygnusEvent) throws Exception { service = cygnusEvent.getService(); servicePath = cygnusEvent.getServicePath(); destination = cygnusEvent.getDestination(); dbName = buildDbName(service); tableName = buildTableName(servicePath, destination, tableType); } // initialize public abstract void aggregate(CygnusEvent cygnusEvent) throws Exception; } // MySQLAggregator /** * Class for aggregating batches in row mode. */ private class RowAggregator extends MySQLAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); typedFieldNames = "(" + Constants.RECV_TIME_TS + " long, " + Constants.RECV_TIME + " text, " + Constants.ENTITY_ID + " text, " + Constants.ENTITY_TYPE + " text, " + Constants.ATTR_NAME + " text, " + Constants.ATTR_TYPE + " text, " + Constants.ATTR_VALUE + " text, " + Constants.ATTR_MD + " text" + ")"; fieldNames = "(" + Constants.RECV_TIME_TS + "," + Constants.RECV_TIME + "," + Constants.ENTITY_ID + "," + Constants.ENTITY_TYPE + "," + Constants.ATTR_NAME + "," + Constants.ATTR_TYPE + "," + Constants.ATTR_VALUE + "," + Constants.ATTR_MD + ")"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create a column and aggregate it String row = "('" + recvTimeTs + "','" + recvTime + "','" + entityId + "','" + entityType + "','" + attrName + "','" + attrType + "','" + attrValue + "','" + attrMetadata + "')"; if (aggregation.isEmpty()) { aggregation += row; } else { aggregation += "," + row; } // if else } // for } // aggregate } // RowAggregator /** * Class for aggregating batches in column mode. */ private class ColumnAggregator extends MySQLAggregator { @Override public void initialize(CygnusEvent cygnusEvent) throws Exception { super.initialize(cygnusEvent); // particulat initialization typedFieldNames = "(" + Constants.RECV_TIME + " text"; fieldNames = "(" + Constants.RECV_TIME; // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); typedFieldNames += "," + attrName + " text," + attrName + "_md text"; fieldNames += "," + attrName + "," + attrName + "_md"; } // for typedFieldNames += ")"; fieldNames += ")"; } // initialize @Override public void aggregate(CygnusEvent cygnusEvent) throws Exception { // get the event headers long recvTimeTs = cygnusEvent.getRecvTimeTs(); String recvTime = Utils.getHumanReadable(recvTimeTs, true); // get the event body ContextElement contextElement = cygnusEvent.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } String column = "('" + recvTime + "'"; for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // create part of the column with the current attribute (a.k.a. a column) column += ",'" + attrValue + "','" + attrMetadata + "'"; } // for // now, aggregate the column if (aggregation.isEmpty()) { aggregation += column + ")"; } else { aggregation += "," + column + ")"; } // if else } // aggregate } // ColumnAggregator private MySQLAggregator getAggregator(boolean rowAttrPersistence) { if (rowAttrPersistence) { return new RowAggregator(); } else { return new ColumnAggregator(); } // if else } // getAggregator private void persistAggregation(MySQLAggregator aggregator) throws Exception { String typedFieldNames = aggregator.getTypedFieldNames(); String fieldNames = aggregator.getFieldNames(); String fieldValues = aggregator.getAggregation(); String dbName = aggregator.getDbName(); String tableName = aggregator.getTableName(); LOGGER.info("[" + this.getName() + "] Persisting data at OrionMySQLSink. Database (" + dbName + "), Table (" + tableName + "), Data (" + fieldValues + ")"); // creating the database and the table has only sense if working in row mode, in column node // everything must be provisioned in advance if (aggregator instanceof RowAggregator) { persistenceBackend.createDatabase(dbName); persistenceBackend.createTable(dbName, tableName, typedFieldNames); } persistenceBackend.insertContextData(dbName, tableName, fieldNames, fieldValues); } // persistAggregation /** * Builds a database name given a fiwareService. It throws an exception if the naming conventions are violated. * @param fiwareService * @return * @throws Exception */ private String buildDbName(String fiwareService) throws Exception { String dbName = fiwareService; if (dbName.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building dbName=fiwareService (" + dbName + ") and its length is greater " + "than " + Constants.MAX_NAME_LEN); } return dbName; } // buildDbName /** * Builds a package name given a fiwareServicePath and a destination. It throws an exception if the naming * conventions are violated. * @param fiwareServicePath * @param destination * @return * @throws Exception */ private String buildTableName(String fiwareServicePath, String destination, TableType tableType) throws Exception { String tableName; switch(tableType) { case TABLEBYDESTINATION: if (fiwareServicePath.length() == 0) { tableName = destination; } else { tableName = fiwareServicePath + '_' + destination; } // if else break; case TABLEBYSERVICEPATH: tableName = fiwareServicePath; break; default: throw new CygnusBadConfiguration("Unknown table type (" + tableType.toString() + " in OrionMySQLSink, " + "cannot build the table name. Please, use TABLEBYSERVICEPATH or TABLEBYDESTINATION"); } // switch if (tableName.length() > Constants.MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building tableName=fiwareServicePath + '_' + destination (" + tableName + ") and its length is greater than " + Constants.MAX_NAME_LEN); } return tableName; } // buildTableName } // OrionMySQLSink
package org.nanopub.extra.security; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.eclipse.rdf4j.RDF4JException; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.FOAF; import org.eclipse.rdf4j.model.vocabulary.RDFS; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler; import org.eclipse.rdf4j.rio.turtle.TurtleParser; import org.nanopub.Nanopub; import org.nanopub.extra.server.GetNanopub; import net.trustyuri.TrustyUriUtils; public class IntroNanopub implements Serializable { private static final long serialVersionUID = -2760220283018515835L; static HttpClient defaultHttpClient; static { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(100).setSocketTimeout(1000) .setCookieSpec(CookieSpecs.STANDARD).build(); defaultHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); } public static IntroNanopub get(String userId) throws IOException, RDF4JException { return get(userId, (HttpClient) null); } public static IntroNanopub get(String userId, HttpClient httpClient) throws IOException, RDF4JException { IntroExtractor ie = extract(userId, httpClient); if (ie != null) { return new IntroNanopub(ie.getIntroNanopub(), ie.getName(), SimpleValueFactory.getInstance().createIRI(userId)); } return null; } public static IntroNanopub get(String userId, IntroExtractor ie) { return new IntroNanopub(ie.getIntroNanopub(), ie.getName(), SimpleValueFactory.getInstance().createIRI(userId)); } public static IntroExtractor extract(String userId, HttpClient httpClient) throws IOException, RDF4JException { if (httpClient == null) httpClient = defaultHttpClient; HttpGet get = new HttpGet(userId); get.setHeader("Accept", "text/turtle"); InputStream in = null; try { HttpResponse resp = httpClient.execute(get); if (!wasSuccessful(resp)) { EntityUtils.consumeQuietly(resp.getEntity()); throw new IOException(resp.getStatusLine().toString()); } in = resp.getEntity().getContent(); IntroExtractor ie = new IntroExtractor(userId); TurtleParser parser = new TurtleParser(); parser.setRDFHandler(ie); parser.parse(in, userId); return ie; } finally { if (in != null) in.close(); } } private Nanopub nanopub; private IRI user; private String name; private Map<IRI,KeyDeclaration> keyDeclarations = new HashMap<>(); public IntroNanopub(Nanopub nanopub, IRI user) { this(nanopub, null, user); } public IntroNanopub(Nanopub nanopub, String name, IRI user) { this.nanopub = nanopub; this.user = user; for (Statement st : nanopub.getAssertion()) { if (st.getPredicate().equals(KeyDeclaration.DECLARED_BY) && st.getObject() instanceof IRI) { IRI subj = (IRI) st.getSubject(); KeyDeclaration d; if (keyDeclarations.containsKey(subj)) { d = keyDeclarations.get(subj); } else { d = new KeyDeclaration(subj); keyDeclarations.put(subj, d); } d.addDeclarer((IRI) st.getObject()); } } for (Statement st : nanopub.getAssertion()) { IRI subj = (IRI) st.getSubject(); if (!keyDeclarations.containsKey(subj)) continue; KeyDeclaration d = keyDeclarations.get(subj); IRI pred = st.getPredicate(); Value obj = st.getObject(); if (pred.equals(CryptoElement.HAS_ALGORITHM) && obj instanceof Literal) { try { d.setAlgorithm((Literal) obj); } catch (MalformedCryptoElementException ex) { ex.printStackTrace(); } } else if (pred.equals(CryptoElement.HAS_PUBLIC_KEY) && obj instanceof Literal) { try { d.setPublicKeyLiteral((Literal) obj); } catch (MalformedCryptoElementException ex) { ex.printStackTrace(); } } } } public Nanopub getNanopub() { return nanopub; } public IRI getUser() { return user; } public String getName() { return name; } public List<KeyDeclaration> getKeyDeclarations() { return new ArrayList<>(keyDeclarations.values()); } public static class IntroExtractor extends AbstractRDFHandler { private String userId; private Nanopub introNanopub; private String name; public IntroExtractor(String userId) { this.userId = userId; } public void handleStatement(Statement st) throws RDFHandlerException { if (introNanopub != null) return; if (!st.getSubject().stringValue().equals(userId)) return; if (st.getPredicate().stringValue().equals(FOAF.PAGE.stringValue())) { String o = st.getObject().stringValue(); if (TrustyUriUtils.isPotentialTrustyUri(o)) { introNanopub = GetNanopub.get(o); } } else if (st.getPredicate().stringValue().equals(RDFS.LABEL.stringValue())) { name = st.getObject().stringValue(); } }; public Nanopub getIntroNanopub() { return introNanopub; } public String getName() { return name; } } private static boolean wasSuccessful(HttpResponse resp) { int c = resp.getStatusLine().getStatusCode(); return c >= 200 && c < 300; } }
package org.oblodiff.token.text.simple; import java.util.Collection; import org.oblodiff.token.api.Token; import org.oblodiff.token.text.TextualSplittableToken; import java.util.Stack; public class Document extends TextualSplittableToken { private static final String NON_WHITE_SPACE_REGEX = "\\S"; private static final String WHITE_SPACE_REGEX = "\\s"; private static final Character CARRIAGE_RETURN = '\r'; private static final Character LINE_FEED = '\n'; /** * Dedicated constructor. * * @param content must not be {@code null} */ public Document(final String content) { super(content); } @Override protected boolean shouldSplitAt(final int i, final Character character) { final boolean isCarriageReturn = character.equals(CARRIAGE_RETURN); return (isCarriageReturn || character.equals(LINE_FEED)) && containsBreakTillNextNonWhitespace(i + 1, isCarriageReturn); } private boolean containsBreakTillNextNonWhitespace(final int begin, final boolean isCarriageReturn) { for (int i = begin; i < getContent().length(); ++i) { final Character character = getContent().charAt(i); if (character.equals(CARRIAGE_RETURN)) { return true; } if (character.equals(LINE_FEED) && (i > begin || !isCarriageReturn)) { return true; } if (String.valueOf(character.charValue()).matches(NON_WHITE_SPACE_REGEX)) { return false; } } return false; } @Override protected Token newToken(final String content) { return new Sentence(content); } @Override protected void endReached(final Collection<Token> children, final int begin, Character cc) { final Stack<Character> whitespaces = new Stack<>(); for (int i = getContent().length() - 1; i >= begin; --i) { final Character character = getContent().charAt(i); if (String.valueOf(character.charValue()).matches(WHITE_SPACE_REGEX)) { whitespaces.push(character); } else { break; } } addToken(children, begin, getContent().length() - whitespaces.size()); while (!whitespaces.isEmpty()) { children.add(new org.oblodiff.token.text.Character(whitespaces.pop())); } } @Override protected int addDivider(final Collection<Token> children, final int begin, Character cc) { int inserted = 0; for (int i = begin; i < getContent().length(); ++i) { final Character character = getContent().charAt(i); if (String.valueOf(character.charValue()).matches(WHITE_SPACE_REGEX)) { children.add(new org.oblodiff.token.text.Character(character)); ++inserted; } else { break; } } return inserted; } }
package com.thetransactioncompany.cors; import javax.servlet.http.HttpServletRequest; /** * Enumeration of the CORS request types. * * @author Vladimir Dzhuvinov * @author Brandon Murray */ public enum CORSRequestType { /** * Simple / actual CORS request. */ ACTUAL, /** * Preflight CORS request. */ PREFLIGHT, /** * Other (non-CORS) request. */ OTHER; /** * Detects the CORS type of the specified HTTP request. * * @param request The HTTP request to check. Must not be {@code null}. * * @return The CORS request type. */ public static CORSRequestType detect(final HttpServletRequest request) { // All CORS request have an Origin header if (request.getHeader("Origin") == null) return OTHER; // Some browsers include the Origin header even when submitting // section-7.3 String requestOrigin = request.getScheme() + "://" + request.getHeader("Host"); if (request.getHeader("Host") != null && request.getHeader("Origin").equals(requestOrigin)) return OTHER; // We have a CORS request - determine type if (request.getHeader("Access-Control-Request-Method") != null && request.getMethod() != null && request.getMethod().equals("OPTIONS") ) return PREFLIGHT; else return ACTUAL; } }
package org.odlabs.wiquery.core.options; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.wicket.Component; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.odlabs.wiquery.core.javascript.JsScope; /** * $Id$ * <p> * Wraps a set of options possibly defined for a WiQuery {@link Component}. * </p> * * <p> * By default, Options are rendered as a JavaScript object like this: * * <pre> * { * option1: 'value1', * option2: 'value2 * } * </pre> * * This rendering can be customized by creating a {@link IOptionsRenderer}. * </p> * * @author Lionel Armanet * @author Hielke Hoeve * @author Ernesto Reinaldo Barreiro * @since 0.5 */ public class Options implements IModel<Options> { private static final long serialVersionUID = 1L; private Component owner; /** * The internal structure is a map associating each option label with each * option value. */ private Map<String, Object> options = new LinkedHashMap<String, Object>(); /** * The {@link IOptionsRenderer} to use. */ private IOptionsRenderer optionsRenderer; /** * Build a new empty {@link Options} instance that does not bind to a * component. This does not allow the usage of IComponentAssignedModels as * option values. */ public Options() { this(null); } /** * Build a new empty {@link Options} instance that binds to a component */ public Options(Component owner) { this.owner = owner; this.optionsRenderer = DefaultOptionsRenderer.get(); } public void setOwner(Component owner) { if (this.owner != null && this.owner != owner) throw new IllegalArgumentException( "Cannot use the same Options for multiple components"); this.owner = owner; } /** * <p> * Returns if the given option is defined or not. * </p> * * @param key * the option name. */ public boolean containsKey(Object key) { return options.containsKey(key); } /** * <p> * Returns the given option value as a String. * </p> * * @param key * the option name. */ public String get(String key) { String ret = getValueFromOptions(key, StringOption.class); if (ret == null && options.containsKey(ret)) ret = options.get(key).toString(); return ret; } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public Boolean getBoolean(String key) { return getValueFromOptions(key, BooleanOption.class); } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public JsScope getJsScope(String key) { return (JsScope) this.options.get(key); } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. * @return the complex option */ public IComplexOption getComplexOption(String key) { Object object = this.options.get(key); if (object instanceof IComplexOption) return (IComplexOption) object; return null; } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public Double getDouble(String key) { return getValueFromOptions(key, DoubleOption.class); } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public Float getFloat(String key) { return getValueFromOptions(key, FloatOption.class); } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public Integer getInt(String key) { return getValueFromOptions(key, IntegerOption.class); } /** * Returns the JavaScript statement corresponding to options. */ public CharSequence getJavaScriptOptions() { StringBuilder sb = new StringBuilder(); this.optionsRenderer.renderBefore(sb); int count = 0; for (Entry<String, Object> entry : options.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof IModelOption<?>) value = ((IModelOption<?>) value).wrapOnAssignment(owner); boolean isLast = !(count < options.size() - 1); if (value instanceof JsScope) { // Case of a JsScope sb.append(this.optionsRenderer.renderOption(key, ((JsScope) value).render(), isLast)); } else if (value instanceof ICollectionItemOptions) { // Case of an ICollectionItemOptions sb.append(this.optionsRenderer.renderOption(key, ((ICollectionItemOptions) value).getJavascriptOption(), isLast)); } else if (value instanceof IComplexOption) { // Case of an IComplexOption sb .append(this.optionsRenderer.renderOption(key, ((IComplexOption) value).getJavascriptOption(), isLast)); } else if (value instanceof ITypedOption<?>) { // Case of an ITypedOption sb.append(this.optionsRenderer .renderOption(key, ((ITypedOption<?>) value) .getJavascriptOption(), isLast)); } else { // Other cases sb .append(this.optionsRenderer.renderOption(key, value, isLast)); } count++; } this.optionsRenderer.renderAfter(sb); return sb; } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. * @return the list */ public ICollectionItemOptions getListItemOptions(String key) { Object object = this.options.get(key); if (object instanceof ICollectionItemOptions) return (ICollectionItemOptions) object; return null; } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public String getLiteral(String key) { return getValueFromOptions(key, LiteralOption.class); } /** * <p> * Returns the given option value. * </p> * * @param key * the option name. */ public Short getShort(String key) { return getValueFromOptions(key, ShortOption.class); } /** * @return true if no options are defined, false otherwise. */ public boolean isEmpty() { return this.options.isEmpty(); } private <T, O extends IModelOption<T>> T getValueFromOptions(String key, Class<O> optionClass) { Object object = this.options.get(key); if (optionClass.isInstance(object)) { O option = optionClass.cast(object); return option.wrapOnAssignment(owner).getValue(); } return null; } private void putOption(String key, IModelOption<?> option) { options.put(key, option); } /** * <p> * Put an boolean value for the given option name. * </p> * * @param key * the option name. * @param value * the boolean value. */ public Options put(String key, boolean value) { putOption(key, new BooleanOption(value)); return this; } /** * <p> * Put an boolean value for the given option name. * </p> * * @param key * the option name. * @param value * the boolean value. */ public Options putBoolean(String key, IModel<Boolean> value) { putOption(key, new BooleanOption(value)); return this; } /** * <p> * Puts an double value for the given option name. * </p> * * @param key * the option name. * @param value * the float double. */ public Options put(String key, double value) { putOption(key, new DoubleOption(value)); return this; } /** * <p> * Puts an IModel &lt;Double&gt; value for the given option name. * </p> * * @param key * the option name. * @param value * the float value. */ public Options putDouble(String key, IModel<Double> value) { putOption(key, new DoubleOption(value)); return this; } /** * <p> * Puts an float value for the given option name. * </p> * * @param key * the option name * @param value * The float value * @return */ public Options put(String key, float value) { putOption(key, new FloatOption(value)); return this; } /** * <p> * Puts an IModel &lt;Double&gt; value for the given option name. * </p> * * @param key * the option name. * @param value * the float double. */ public Options putFloat(String key, IModel<Float> value) { putOption(key, new FloatOption(value)); return this; } /** * <p> * Puts a list of IListItemOption value for the given option name. * </p> * * @param key * the option name. * @param value * the IListItemOption list. */ public Options put(String key, ICollectionItemOptions value) { options.put(key, value); return this; } /** * <p> * Puts a complex option value for the given option name. * </p> * * @param key * the option name. * @param value * the IComplexOption. */ public Options put(String key, IComplexOption value) { options.put(key, value); return this; } /** * <p> * Puts an int value for the given option name. * </p> * * @param key * the option name. * @param value * the int value. */ public Options put(String key, int value) { putOption(key, new IntegerOption(value)); return this; } /** * <p> * Puts an int value for the given option name. * </p> * * @param key * the option name. * @param value * the int value. */ public Options putInteger(String key, IModel<Integer> value) { putOption(key, new IntegerOption(value)); return this; } /** * <p> * Puts a {@link JsScope} value for the given option name. * </p> * * @param key * the option name. * @param value * the {@link JsScope} value. */ public Options put(String key, JsScope value) { options.put(key, value); return this; } /** * <p> * Puts an short value for the given option name. * </p> * * @param key * the option name. * @param value * the short value. */ public Options put(String key, short value) { putOption(key, new ShortOption(value)); return this; } /** * <p> * Puts an short value for the given option name. * </p> * * @param key * the option name. * @param value * the short value. */ public Options putShort(String key, IModel<Short> value) { putOption(key, new ShortOption(value)); return this; } /** * <p> * Puts a {@link String} value for the given option name. * </p> * * @param key * the option name. * @param value * the {@link String} value. */ public Options put(String key, String value) { putOption(key, new StringOption(value)); return this; } /** * <p> * Puts a {@link String} value for the given option name. * </p> * * @param key * the option name. * @param value * the {@link String} value. */ public Options putString(String key, IModel<String> value) { putOption(key, new StringOption(value)); return this; } /** * <p> * Puts a {@link Long} value for the given option name. * </p> * * @param key * the option name. * @param value * the {@link Long} value. */ public Options put(String key, long value) { putOption(key, new LongOption(value)); return this; } /** * <p> * Puts a {@link Long} value for the given option name. * </p> * * @param key * the option name. * @param value * the {@link Long} value. */ public Options putLong(String key, IModel<Long> value) { putOption(key, new LongOption(value)); return this; } /** * <p> * Puts a {@link String} value as a JavaScript literal for the given name. * <p> * Note that the JavaScript resulting from this options will be <code>'value'</code> * </p> * </p> * * @param key * the option name. * @param value * the {@link LiteralOption} value. */ public Options putLiteral(String key, String value) { putOption(key, new LiteralOption(value)); return this; } /** * <p> * Puts a {@link String} value as a JavaScript literal for the given name. * <p> * Note that the JavaScript resulting from this options will be <code>'value'</code> * </p> * </p> * * @param key * the option name. * @param value * the {@link LiteralOption} value. */ public Options putLiteral(String key, IModel<String> value) { putOption(key, new LiteralOption(value)); return this; } /** * <p> * Removes an option for a given name. * </p> * * @param key * the option's key to remove. */ public void removeOption(String key) { this.options.remove(key); } /** * Sets the renderer to use. */ public void setRenderer(IOptionsRenderer optionsRenderer) { this.optionsRenderer = optionsRenderer; } public Options getObject() { return this; } public void setObject(Options object) { throw new UnsupportedOperationException( "The setObject() function is not supported for object Options."); } public void detach() { onDetach(this.options); } @SuppressWarnings("unchecked") private void onDetach(Object detachable) { if (detachable instanceof Component) ((Component) detachable).detach(); else if (detachable instanceof IDetachable) ((IDetachable) detachable).detach(); else if (detachable instanceof Map<?, ?>) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) detachable).entrySet()) { onDetach(entry.getKey()); onDetach(entry.getValue()); } } else if (detachable instanceof Iterable<?>) { Iterator<Object> iter = ((Iterable<Object>) detachable).iterator(); while (iter.hasNext()) { onDetach(iter.next()); } } } }
package com.treasure_data.jdbc.command; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hsqldb.result.ResultConstants; import com.treasure_data.client.ClientException; import com.treasure_data.jdbc.compiler.expr.DateValue; import com.treasure_data.jdbc.compiler.expr.DoubleValue; import com.treasure_data.jdbc.compiler.expr.Expression; import com.treasure_data.jdbc.compiler.expr.JdbcParameter; import com.treasure_data.jdbc.compiler.expr.LongValue; import com.treasure_data.jdbc.compiler.expr.NullValue; import com.treasure_data.jdbc.compiler.expr.StringValue; import com.treasure_data.jdbc.compiler.expr.TimeValue; import com.treasure_data.jdbc.compiler.expr.ops.ExpressionList; import com.treasure_data.jdbc.compiler.expr.ops.ItemsList; import com.treasure_data.jdbc.compiler.parser.CCSQLParser; import com.treasure_data.jdbc.compiler.parser.ParseException; import com.treasure_data.jdbc.compiler.schema.Column; import com.treasure_data.jdbc.compiler.schema.Table; import com.treasure_data.jdbc.compiler.stat.ColumnDefinition; import com.treasure_data.jdbc.compiler.stat.CreateTable; import com.treasure_data.jdbc.compiler.stat.Drop; import com.treasure_data.jdbc.compiler.stat.Index; import com.treasure_data.jdbc.compiler.stat.Insert; import com.treasure_data.jdbc.compiler.stat.Select; import com.treasure_data.jdbc.compiler.stat.Statement; /** * @see org.hsqldb.Session * @see org.hsqldb.SessionInterface */ public class CommandExecutor { private ClientAPI api; public CommandExecutor(ClientAPI api) { this.api = api; } public ClientAPI getAPI() { return api; } public synchronized void execute(CommandContext context) throws SQLException { switch (context.mode) { case ResultConstants.EXECDIRECT: executeDirect(context); break; case ResultConstants.EXECUTE: case ResultConstants.BATCHEXECUTE: throw new UnsupportedOperationException(); case ResultConstants.PREPARE: executePrepare(context); break; case ResultConstants.LARGE_OBJECT_OP: case ResultConstants.BATCHEXECDIRECT: case ResultConstants.CLOSE_RESULT: case ResultConstants.UPDATE_RESULT: case ResultConstants.FREESTMT: case ResultConstants.GETSESSIONATTR: case ResultConstants.SETSESSIONATTR: case ResultConstants.ENDTRAN: case ResultConstants.SETCONNECTATTR: case ResultConstants.REQUESTDATA: case ResultConstants.DISCONNECT: default: throw new SQLException("invalid mode: " + context.mode); } } public void executeDirect(CommandContext context) throws SQLException { try { String sql = context.sql; InputStream in = new ByteArrayInputStream(sql.getBytes()); CCSQLParser p = new CCSQLParser(in); context.compiledSql = p.Statement(); validateStatement(context); extractJdbcParameters(context); if (context.paramList.size() != 0) { throw new ParseException("sql includes some jdbcParameters"); } executeCompiledStatement(context); } catch (ParseException e) { throw new SQLException(e); } } public void executePrepare(CommandContext context) throws SQLException { if (context.compiledSql == null) { try { String sql = context.sql; InputStream in = new ByteArrayInputStream(sql.getBytes()); CCSQLParser p = new CCSQLParser(in); context.compiledSql = p.Statement(); validateStatement(context); extractJdbcParameters(context); } catch (ParseException e) { throw new SQLException(e); } } else { executeCompiledPreparedStatement(context); } } public void validateStatement(CommandContext context) throws ParseException { Statement stat = context.compiledSql; if (stat == null) { throw new ParseException("stat is null"); } if (stat instanceof Insert) { validateStatement(context, (Insert) stat); } else if (stat instanceof CreateTable) { validateStatement(context, (CreateTable) stat); } else if (stat instanceof Drop) { validateStatement(context, (Drop) stat); } else if (stat instanceof Select) { validateStatement(context, (Select) stat); } else { throw new ParseException("unsupported statement: " + stat); } } public void extractJdbcParameters(CommandContext context) throws ParseException { context.paramList = new ArrayList<String>(); Statement stat = context.compiledSql; if (stat instanceof Insert) { extractJdbcParameters(context, (Insert) stat); } else if (stat instanceof CreateTable) { extractJdbcParameters(context, (CreateTable) stat); } else if (stat instanceof Drop) { extractJdbcParameters(context, (Drop) stat); } else if (stat instanceof Select) { extractJdbcParameters(context, (Select) stat); } else { throw new ParseException("unsupported statement: " + stat); } } public void executeCompiledStatement(CommandContext context) throws SQLException { Statement stat = context.compiledSql; if (stat instanceof Insert) { executeCompiledStatement(context, (Insert) stat); } else if (stat instanceof CreateTable) { executeCompiledStatement(context, (CreateTable) stat); } else if (stat instanceof Drop) { executeCompiledStatement(context, (Drop) stat); } else if (stat instanceof Select) { executeCompiledStatement(context, (Select) stat); } else { throw new SQLException("unsupported statement: " + stat); } } public void executeCompiledPreparedStatement(CommandContext context) throws SQLException { Statement stat = context.compiledSql; if (stat instanceof Insert) { executeCompiledPreparedStatement(context, (Insert) stat); } else if (stat instanceof CreateTable) { executeCompiledPreparedStatement(context, (CreateTable) stat); } else if (stat instanceof Drop) { executeCompiledPreparedStatement(context, (Drop) stat); } else if (stat instanceof Select) { executeCompiledPreparedStatement(context, (Select) stat); } else { throw new SQLException("unsupported statement: " + stat); } } public void validateStatement(CommandContext context, Select stat) throws ParseException { // ignore } public void executeCompiledStatement(CommandContext context, Select stat) throws SQLException { String sql = stat.toString(); try { context.resultSet = api.select(sql); } catch (ClientException e) { throw new SQLException(e); } } public void executeCompiledPreparedStatement(CommandContext context, Select stat) throws SQLException { executeCompiledStatement(context, stat); } public void extractJdbcParameters(CommandContext context, Select stat) { // ignore } public void validateStatement(CommandContext context, Insert stat) throws ParseException { Table table = stat.getTable(); // table validation if (table == null || table.getName() == null || table.getName().isEmpty()) { throw new ParseException("invalid table name: " + table); } // columns validation List<Column> cols = stat.getColumns(); if (cols == null || cols.size() <= 0) { throw new ParseException("invalid columns: " + cols); } // items validation List<Expression> exprs; { ItemsList items = stat.getItemsList(); if (items == null) { throw new ParseException("invalid item list: " + items); } try { exprs = ((ExpressionList) items).getExpressions(); } catch (Throwable t) { throw new ParseException("unsupported expressions"); } } // other validations if (cols.size() != exprs.size()) { throw new ParseException("invalid columns or expressions"); } } public void executeCompiledStatement(CommandContext context, Insert stat) throws SQLException { /** * SQL: * insert into table02 (k1, k2, k3) values (2, 'muga', 'nishizawa') * * ret: * table => table02 * cols => [k1, k2, k3] * items => (2, 'muga', 'nishizawa') */ Table table = stat.getTable(); List<Column> cols = stat.getColumns(); List<Expression> exprs = ((ExpressionList) stat.getItemsList()).getExpressions(); try { Map<String, Object> record = new HashMap<String, Object>(); Iterator<Column> col_iter = cols.iterator(); Iterator<Expression> expr_iter = exprs.iterator(); while (col_iter.hasNext()) { Column col = col_iter.next(); Expression expr = expr_iter.next(); record.put(col.getColumnName(), toValue(expr)); } api.insert(table.getName(), record); } catch (Exception e) { throw new UnsupportedOperationException(); } } public void executeCompiledPreparedStatement(CommandContext context, Insert stat) { /** * SQL: * insert into table02 (k1, k2, k3) values (?, ?, 'nishizawa') * * ret: * table => table02 * cols => [k1, k2, k3] * items => (?, ?, 'nishizawa') */ Table table = stat.getTable(); List<Column> cols = stat.getColumns(); List<Expression> exprs = ((ExpressionList) stat.getItemsList()).getExpressions(); List<String> paramList = context.paramList; Map<Integer, Object> params = context.params; try { Map<String, Object> record = new HashMap<String, Object>(); Iterator<Column> col_iter = cols.iterator(); Iterator<Expression> expr_iter = exprs.iterator(); while (col_iter.hasNext()) { Column col = col_iter.next(); Expression expr = expr_iter.next(); String colName = col.getColumnName(); int i = getIndex(paramList, colName); if (i >= 0) { record.put(colName, params.get(new Integer(i + 1))); } else { record.put(colName, toValue(expr)); } } api.insert(table.getName(), record); } catch (Exception e) { throw new UnsupportedOperationException(); } } public void extractJdbcParameters(CommandContext context, Insert stat) { List<Column> cols = stat.getColumns(); List<Expression> exprs = ((ExpressionList) stat.getItemsList()).getExpressions(); int len = cols.size(); for (int i = 0; i < len; i++) { Expression expr = exprs.get(i); if (! (expr instanceof JdbcParameter)) { continue; } String colName = cols.get(i).getColumnName(); context.paramList.add(colName); } } public void validateStatement(CommandContext context, CreateTable stat) throws ParseException { // table validation Table table = stat.getTable(); if (table == null || table.getName() == null || table.getName().isEmpty()) { throw new ParseException("invalid table name: " + table); } // column definition validation List<ColumnDefinition> def = stat.getColumnDefinitions(); if (def == null || def.size() == 0) { throw new ParseException("invalid column definitions: " + def); } // this variable is not used @SuppressWarnings("unused") List<Index> indexes = stat.getIndexes(); } public void executeCompiledStatement(CommandContext context, CreateTable stat) { /** * SQL: * create table table01(c0 varchar(255), c1 int) * * ret: * table => table02 */ Table table = stat.getTable(); List<ColumnDefinition> def = stat.getColumnDefinitions(); @SuppressWarnings("unused") List<Index> indexes = stat.getIndexes(); try { api.create(table.getName()); } catch (Exception e) { throw new UnsupportedOperationException(); } } public void executeCompiledPreparedStatement(CommandContext context, CreateTable stat) throws SQLException { executeCompiledStatement(context, stat); } public void extractJdbcParameters(CommandContext context, CreateTable stat) { // ignore } public void validateStatement(CommandContext context, Drop stat) throws ParseException { String tableName = stat.getName(); if (tableName == null || tableName.isEmpty()) { throw new ParseException("invalid table name: " + tableName); } @SuppressWarnings("unused") List<String> params = stat.getParameters(); String type = stat.getType(); if (! (type.equals("table"))) { throw new ParseException("unsupported type: " + type); } } public void executeCompiledStatement(CommandContext context, Drop stat) { /** * SQL: * drop table table02 * * ret: * table => table02 */ String tableName = stat.getName(); @SuppressWarnings("unused") List<String> params = stat.getParameters(); String type = stat.getType(); try { api.drop(tableName); } catch (ClientException e) { throw new UnsupportedOperationException(); } } public void executeCompiledPreparedStatement(CommandContext context, Drop stat) throws SQLException { executeCompiledStatement(context, stat); } public void extractJdbcParameters(CommandContext context, Drop stat) { // ignore } private static int getIndex(List<String> list, String data) { for (int i = 0; i < list.size(); i++) { String d = list.get(i); if (d.equals(data)) { return i; } } return -1; } private static Object toValue(Expression expr) throws ParseException { if (expr instanceof DateValue) { DateValue v = (DateValue) expr; return v.getValue().getTime() / 1000; } else if (expr instanceof DoubleValue) { DoubleValue v = (DoubleValue) expr; return v.getValue(); } else if (expr instanceof LongValue) { LongValue v = (LongValue) expr; return v.getValue(); } else if (expr instanceof NullValue) { return null; } else if (expr instanceof StringValue) { StringValue v = (StringValue) expr; return v.getValue(); } else if (expr instanceof TimeValue) { TimeValue v = (TimeValue) expr; return v.getValue().getTime() / 1000; } else { throw new ParseException( String.format("Type of value is not supported: %s", expr)); } } }
package org.openmechanics.htmleditor; import org.openmechanics.htmleditor.util.Local; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.event.CaretEvent; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledEditorKit; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import static org.openmechanics.htmleditor.Constants.RESOURCE_FOLDER; @SuppressWarnings({ "WeakerAccess", "LocalCanBeFinal", "ResultOfMethodCallIgnored", "unused", "SwitchStatementWithoutDefaultBranch", "unchecked", "ConstantConditions" }) public class HTMLEditor extends JPanel { private static final Logger LOG = LoggerFactory.getLogger(HTMLEditor.class); public JEditorPane editor = new JEditorPane("text/html", ""); JScrollPane jScrollPane1 = new JScrollPane(); public HTMLEditorKit editorKit = new HTMLEditorKit(); public HTMLDocument document = null; boolean bold = false; boolean italic = false; boolean under = false; boolean list = false; String currentTagName = "BODY"; Element currentParaElement = null; Border border1, border2; Class cl = org.openmechanics.htmleditor.HTMLEditor.class; String imagesDir = null; String imagesPath = null; public void setImagesDir(String path) { imagesDir = path; } public String getImagesDir() { return imagesDir; } abstract static class HTMLEditorAction extends AbstractAction { HTMLEditorAction(String name, ImageIcon icon) { super(name, icon); super.putValue(Action.SHORT_DESCRIPTION, name); } HTMLEditorAction(String name) { super(name); super.putValue(Action.SHORT_DESCRIPTION, name); } } public Action boldAction = new HTMLEditorAction( Local.getString("Bold"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "bold.png"))) { @Override public void actionPerformed(ActionEvent e) { boldActionB_actionPerformed(e); } }; public Action italicAction = new HTMLEditorAction( Local.getString("Italic"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "italic.png"))) { @Override public void actionPerformed(ActionEvent e) { italicActionB_actionPerformed(e); } }; public Action underAction = new HTMLEditorAction( Local.getString("Underline"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "underline.png"))) { @Override public void actionPerformed(ActionEvent e) { underActionB_actionPerformed(e); } }; public Action ulAction = new HTMLEditorAction( Local.getString("Unordered list"), new ImageIcon( cl.getResource(RESOURCE_FOLDER + "listunordered.png"))) { @Override public void actionPerformed(ActionEvent e) { ulActionB_actionPerformed(e); } }; public Action olAction = new HTMLEditorAction( Local.getString("Ordered list"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "listordered.png"))) { @Override public void actionPerformed(ActionEvent e) { olActionB_actionPerformed(e); } }; public Action lAlignAction = new HTMLEditorAction( Local.getString("Align left"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "alignleft.png"))) { @Override public void actionPerformed(ActionEvent e) { lAlignActionB_actionPerformed(e); } }; public Action cAlignAction = new HTMLEditorAction( Local.getString("Align center"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "aligncenter.png"))) { @Override public void actionPerformed(ActionEvent e) { cAlignActionB_actionPerformed(e); } }; public Action rAlignAction = new HTMLEditorAction( Local.getString("Align right"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "alignright.png"))) { @Override public void actionPerformed(ActionEvent e) { rAlignActionB_actionPerformed(e); } }; public Action imageAction = new HTMLEditorAction( Local.getString("Insert image"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "image.png"))) { @Override public void actionPerformed(ActionEvent e) { imageActionB_actionPerformed(e); } }; public Action tableAction = new HTMLEditorAction( Local.getString("Insert table"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "table.png"))) { @Override public void actionPerformed(ActionEvent e) { tableActionB_actionPerformed(e); } }; public Action linkAction = new HTMLEditorAction( Local.getString("Insert hyperlink"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "link.png"))) { @Override public void actionPerformed(ActionEvent e) { linkActionB_actionPerformed(e); } }; public Action propsAction = new HTMLEditorAction( Local.getString("Object properties"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "properties.png"))) { @Override public void actionPerformed(ActionEvent e) { propsActionB_actionPerformed(e); } }; public Action selectAllAction = new HTMLEditorAction(Local.getString("Select all")) { @Override public void actionPerformed(ActionEvent e) { editor.selectAll(); } }; public Action insertHRAction = new HTMLEditorAction( Local.getString("Insert horizontal rule"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "hr.png"))) { @Override public void actionPerformed(ActionEvent e) { try { editorKit.insertHTML( document, editor.getCaretPosition(), "<hr>", 0, 0, HTML.Tag.HR); } catch (Exception ex) { LOG.warn("action failed", ex); } } }; CharTablePanel charTablePanel = new CharTablePanel(editor); boolean charTableShow = false; public JTabbedPane toolsPanel = new JTabbedPane(); public boolean toolsPanelShow = false; public void showToolsPanel() { if (toolsPanelShow) { return; } this.add(toolsPanel, BorderLayout.SOUTH); toolsPanelShow = true; } public void hideToolsPanel() { if (!toolsPanelShow) { return; } this.remove(charTablePanel); toolsPanelShow = false; } void addCharTablePanel() { showToolsPanel(); toolsPanel.addTab(Local.getString("Characters"), charTablePanel); } void removeCharTablePanel() { toolsPanel.remove(charTablePanel); if (toolsPanel.getTabCount() == 0) { hideToolsPanel(); } } public Action insCharAction = new HTMLEditorAction( Local.getString("Insert character"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "char.png"))) { @Override public void actionPerformed(ActionEvent e) { if (!charTableShow) { addCharTablePanel(); charTableShow = true; insCharActionB.setBorder(border2); } else { removeCharTablePanel(); charTableShow = false; insCharActionB.setBorder(border1); } insCharActionB.setBorderPainted(charTableShow); } }; public Action findAction = new HTMLEditorAction( Local.getString("Find & Replace"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "find.png"))) { @Override public void actionPerformed(ActionEvent e) { doFind(); } }; public InsertTableCellAction insertTableCellAction = new InsertTableCellAction(); public InsertTableRowAction insertTableRowAction = new InsertTableRowAction(); public BreakAction breakAction = new BreakAction(); public Action cutAction = new HTMLEditorKit.CutAction(); public Action styleCopyAction = new HTMLEditorKit.CopyAction(); public Action copyAction = styleCopyAction; public Action stylePasteAction = new HTMLEditorKit.PasteAction(); public Action pasteAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { //editor.paste(); doPaste(); } }; private void doCopy() { Element el = document.getParagraphElement(editor.getSelectionStart()); if (el.getName().toUpperCase().equals("P-IMPLIED")) { el = el.getParentElement(); } String elName = el.getName(); StringWriter sw = new StringWriter(); String copy; java.awt.datatransfer.Clipboard clip = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); try { editorKit.write( sw, document, editor.getSelectionStart(), editor.getSelectionEnd() - editor.getSelectionStart()); copy = sw.toString(); copy = copy.split("<" + elName + "(.*?)>")[1]; copy = copy.split("</" + elName + ">")[0]; clip.setContents( new java.awt.datatransfer.StringSelection(copy.trim()), null); } catch (Exception ex) { LOG.warn("action failed", ex); } } private void doPaste() { Clipboard clip = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); try { Transferable content = clip.getContents(this); if (content == null) { return; } String txt = content .getTransferData(new DataFlavor(String.class, "String")) .toString(); document.replace( editor.getSelectionStart(), editor.getSelectionEnd() - editor.getSelectionStart(), txt, editorKit.getInputAttributes()); } catch (Exception ex) { LOG.warn("action failed", ex); } } /** * Listener for the edits on the current document. */ protected UndoableEditListener undoHandler = new UndoHandler(); /** UndoManager that we add edits to. */ protected UndoManager undo = new UndoManager(); public UndoAction undoAction = new UndoAction(); public RedoAction redoAction = new RedoAction(); JButton jAlignActionB = new JButton(); public JToolBar editToolbar = new JToolBar(); JButton lAlignActionB = new JButton(); JButton olActionB = new JButton(); JButton linkActionB = new JButton(); JButton italicActionB = new JButton(); JButton propsActionB = new JButton(); JButton imageActionB = new JButton(); public static final int T_P = 0; public static final int T_H1 = 1; public static final int T_H2 = 2; public static final int T_H3 = 3; public static final int T_H4 = 4; public static final int T_H5 = 5; public static final int T_H6 = 6; public static final int T_PRE = 7; //private final int T_ADDRESS = 8; public static final int T_BLOCKQ = 8; String[] elementTypes = { Local.getString("Paragraph"), Local.getString("Header") + " 1", Local.getString("Header") + " 2", Local.getString("Header") + " 3", Local.getString("Header") + " 4", Local.getString("Header") + " 5", Local.getString("Header") + " 6", Local.getString("Preformatted"), //"Address", Local.getString("Blockquote") }; public JComboBox blockCB = new JComboBox(elementTypes); boolean blockCBEventsLock = false; public static final int I_NORMAL = 0; public static final int I_EM = 1; public static final int I_STRONG = 2; public static final int I_CODE = 3; public static final int I_CITE = 4; public static final int I_SUPERSCRIPT = 5; public static final int I_SUBSCRIPT = 6; public static final int I_CUSTOM = 7; String[] inlineTypes = { Local.getString("Normal"), Local.getString("Emphasis"), Local.getString("Strong"), Local.getString("Code"), Local.getString("Cite"), Local.getString("Superscript"), Local.getString("Subscript"), Local.getString("Custom style") + "..." }; public JComboBox inlineCB = new JComboBox(inlineTypes); boolean inlineCBEventsLock = false; JButton boldActionB = new JButton(); JButton ulActionB = new JButton(); JButton rAlignActionB = new JButton(); JButton tableActionB = new JButton(); JButton cAlignActionB = new JButton(); JButton underActionB = new JButton(); BorderLayout borderLayout1 = new BorderLayout(); JPopupMenu defaultPopupMenu = new JPopupMenu(); //JPopupMenu tablePopupMenu = new JPopupMenu(); JMenuItem jMenuItemUndo = new JMenuItem(undoAction); JMenuItem jMenuItemRedo = new JMenuItem(redoAction); JMenuItem jMenuItemCut = new JMenuItem(cutAction); JMenuItem jMenuItemCopy = new JMenuItem(copyAction); JMenuItem jMenuItemPaste = new JMenuItem(pasteAction); JMenuItem jMenuItemProp = new JMenuItem(propsAction); JMenuItem jMenuItemInsCell = new JMenuItem(insertTableCellAction); JMenuItem jMenuItemInsRow = new JMenuItem(insertTableRowAction); int currentCaret = 0; int currentFontSize = 4; JButton brActionB = new JButton(); JButton hrActionB = new JButton(); JButton insCharActionB = new JButton(); public HTMLEditor() { try { jbInit(); } catch (Exception ex) { LOG.warn("action failed", ex); } } void jbInit() throws Exception { cutAction.putValue( Action.SMALL_ICON, new ImageIcon(cl.getResource(RESOURCE_FOLDER + "cut.png"))); cutAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK)); cutAction.putValue(Action.NAME, Local.getString("Cut")); cutAction.putValue(Action.SHORT_DESCRIPTION, Local.getString("Cut")); copyAction.putValue( Action.SMALL_ICON, new ImageIcon(cl.getResource(RESOURCE_FOLDER + "copy.png"))); copyAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK)); copyAction.putValue(Action.NAME, Local.getString("Copy")); copyAction.putValue(Action.SHORT_DESCRIPTION, Local.getString("Copy")); pasteAction.putValue( Action.SMALL_ICON, new ImageIcon(cl.getResource(RESOURCE_FOLDER + "paste.png"))); pasteAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK)); pasteAction.putValue(Action.NAME, Local.getString("Paste")); pasteAction.putValue( Action.SHORT_DESCRIPTION, Local.getString("Paste")); stylePasteAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_V, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); stylePasteAction.putValue( Action.NAME, Local.getString("Paste special")); stylePasteAction.putValue( Action.SHORT_DESCRIPTION, Local.getString("Paste special")); selectAllAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK)); boldAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK)); italicAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK)); underAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_U, KeyEvent.CTRL_MASK)); breakAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK)); breakAction.putValue(Action.NAME, Local.getString("Insert Break")); breakAction.putValue( Action.SHORT_DESCRIPTION, Local.getString("Insert Break")); findAction.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK)); document = (HTMLDocument) editorKit.createDefaultDocument(); border1 = BorderFactory.createEtchedBorder( Color.white, new Color(142, 142, 142)); border2 = BorderFactory.createBevelBorder( BevelBorder.LOWERED, Color.white, Color.white, new Color(142, 142, 142), new Color(99, 99, 99)); this.setLayout(borderLayout1); /* * jAlignActionB.setIcon( new * ImageIcon(org.openmechanics.htmleditor.HTMLEditor.class.getResource("resources/icons/alignjust.png"))); * jAlignActionB.setMaximumSize(new Dimension(22, 22)); * jAlignActionB.setMinimumSize(new Dimension(22, 22)); * jAlignActionB.setPreferredSize(new Dimension(22, 22)); * jAlignActionB.setFocusable(false); */ editor.addCaretListener(this::editor_caretUpdate); editor.setEditorKit(editorKit); editorKit.setDefaultCursor(new Cursor(Cursor.TEXT_CURSOR)); editor.setDocument(document); document.addUndoableEditListener(undoHandler); this.setPreferredSize(new Dimension(520, 57)); editToolbar.setRequestFocusEnabled(false); editToolbar.setToolTipText(""); boldActionB.setAction(boldAction); boldActionB.setBorder(border1); boldActionB.setMaximumSize(new Dimension(22, 22)); boldActionB.setMinimumSize(new Dimension(22, 22)); boldActionB.setPreferredSize(new Dimension(22, 22)); boldActionB.setBorderPainted(false); boldActionB.setFocusable(false); boldActionB.setText(""); italicActionB.setAction(italicAction); italicActionB.setBorder(border1); italicActionB.setMaximumSize(new Dimension(22, 22)); italicActionB.setMinimumSize(new Dimension(22, 22)); italicActionB.setPreferredSize(new Dimension(22, 22)); italicActionB.setBorderPainted(false); italicActionB.setFocusable(false); italicActionB.setText(""); underActionB.setAction(underAction); underActionB.setBorder(border1); underActionB.setMaximumSize(new Dimension(22, 22)); underActionB.setMinimumSize(new Dimension(22, 22)); underActionB.setPreferredSize(new Dimension(22, 22)); underActionB.setBorderPainted(false); underActionB.setFocusable(false); underActionB.setText(""); lAlignActionB.setAction(lAlignAction); lAlignActionB.setMaximumSize(new Dimension(22, 22)); lAlignActionB.setMinimumSize(new Dimension(22, 22)); lAlignActionB.setPreferredSize(new Dimension(22, 22)); lAlignActionB.setBorderPainted(false); lAlignActionB.setFocusable(false); lAlignActionB.setText(""); rAlignActionB.setAction(rAlignAction); rAlignActionB.setFocusable(false); rAlignActionB.setPreferredSize(new Dimension(22, 22)); rAlignActionB.setBorderPainted(false); rAlignActionB.setMinimumSize(new Dimension(22, 22)); rAlignActionB.setMaximumSize(new Dimension(22, 22)); rAlignActionB.setText(""); cAlignActionB.setAction(cAlignAction); cAlignActionB.setMaximumSize(new Dimension(22, 22)); cAlignActionB.setMinimumSize(new Dimension(22, 22)); cAlignActionB.setPreferredSize(new Dimension(22, 22)); cAlignActionB.setBorderPainted(false); cAlignActionB.setFocusable(false); cAlignActionB.setText(""); ulActionB.setAction(ulAction); ulActionB.setMaximumSize(new Dimension(22, 22)); ulActionB.setMinimumSize(new Dimension(22, 22)); ulActionB.setPreferredSize(new Dimension(22, 22)); ulActionB.setBorderPainted(false); ulActionB.setFocusable(false); ulActionB.setText(""); olActionB.setAction(olAction); olActionB.setMaximumSize(new Dimension(22, 22)); olActionB.setMinimumSize(new Dimension(22, 22)); olActionB.setPreferredSize(new Dimension(22, 22)); olActionB.setBorderPainted(false); olActionB.setFocusable(false); olActionB.setText(""); linkActionB.setAction(linkAction); linkActionB.setMaximumSize(new Dimension(22, 22)); linkActionB.setMinimumSize(new Dimension(22, 22)); linkActionB.setPreferredSize(new Dimension(22, 22)); linkActionB.setBorderPainted(false); linkActionB.setFocusable(false); linkActionB.setText(""); propsActionB.setAction(propsAction); propsActionB.setFocusable(false); propsActionB.setPreferredSize(new Dimension(22, 22)); propsActionB.setBorderPainted(false); propsActionB.setMinimumSize(new Dimension(22, 22)); propsActionB.setMaximumSize(new Dimension(22, 22)); propsActionB.setText(""); imageActionB.setAction(imageAction); imageActionB.setMaximumSize(new Dimension(22, 22)); imageActionB.setMinimumSize(new Dimension(22, 22)); imageActionB.setPreferredSize(new Dimension(22, 22)); imageActionB.setBorderPainted(false); imageActionB.setFocusable(false); imageActionB.setText(""); tableActionB.setAction(tableAction); tableActionB.setFocusable(false); tableActionB.setPreferredSize(new Dimension(22, 22)); tableActionB.setBorderPainted(false); tableActionB.setMinimumSize(new Dimension(22, 22)); tableActionB.setMaximumSize(new Dimension(22, 22)); tableActionB.setText(""); brActionB.setAction(breakAction); brActionB.setFocusable(false); brActionB.setBorderPainted(false); brActionB.setPreferredSize(new Dimension(22, 22)); brActionB.setMinimumSize(new Dimension(22, 22)); brActionB.setMaximumSize(new Dimension(22, 22)); brActionB.setText(""); hrActionB.setAction(insertHRAction); hrActionB.setMaximumSize(new Dimension(22, 22)); hrActionB.setMinimumSize(new Dimension(22, 22)); hrActionB.setPreferredSize(new Dimension(22, 22)); hrActionB.setBorderPainted(false); hrActionB.setFocusable(false); hrActionB.setText(""); insCharActionB.setAction(insCharAction); insCharActionB.setBorder(border1); insCharActionB.setMaximumSize(new Dimension(22, 22)); insCharActionB.setMinimumSize(new Dimension(22, 22)); insCharActionB.setPreferredSize(new Dimension(22, 22)); insCharActionB.setBorderPainted(false); insCharActionB.setFocusable(false); insCharActionB.setText(""); blockCB.setBackground(new Color(230, 230, 230)); blockCB.setMaximumRowCount(12); blockCB.setFont(new java.awt.Font("Dialog", 1, 10)); blockCB.setMaximumSize(new Dimension(120, 22)); blockCB.setMinimumSize(new Dimension(60, 22)); blockCB.setPreferredSize(new Dimension(79, 22)); blockCB.setFocusable(false); blockCB.addActionListener(this::blockCB_actionPerformed); inlineCB.addActionListener(this::inlineCB_actionPerformed); inlineCB.setFocusable(false); inlineCB.setPreferredSize(new Dimension(79, 22)); inlineCB.setMinimumSize(new Dimension(60, 22)); inlineCB.setMaximumSize(new Dimension(120, 22)); inlineCB.setFont(new java.awt.Font("Dialog", 1, 10)); inlineCB.setMaximumRowCount(12); inlineCB.setBackground(new Color(230, 230, 230)); this.add(jScrollPane1, BorderLayout.CENTER); this.add(editToolbar, BorderLayout.NORTH); editToolbar.add(propsActionB, null); editToolbar.addSeparator(); editToolbar.add(blockCB, null); editToolbar.addSeparator(); editToolbar.add(inlineCB, null); editToolbar.addSeparator(); editToolbar.add(boldActionB, null); editToolbar.add(italicActionB, null); editToolbar.add(underActionB, null); editToolbar.addSeparator(); editToolbar.add(ulActionB, null); editToolbar.add(olActionB, null); editToolbar.addSeparator(); editToolbar.add(lAlignActionB, null); editToolbar.add(cAlignActionB, null); editToolbar.add(rAlignActionB, null); editToolbar.addSeparator(); editToolbar.add(imageActionB, null); editToolbar.add(tableActionB, null); editToolbar.add(linkActionB, null); editToolbar.addSeparator(); editToolbar.add(hrActionB, null); editToolbar.add(brActionB, null); editToolbar.add(insCharActionB, null); jScrollPane1.getViewport().add(editor, null); toolsPanel.setTabPlacement(JTabbedPane.BOTTOM); toolsPanel.setFont(new Font("Dialog", 1, 10)); // editToolbar.add(jAlignActionB, null); /* KEY ACTIONS */ /* * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK), */ editor.getKeymap().removeKeyStrokeBinding( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new ParaBreakAction()); /* * editor.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_B, * KeyEvent.CTRL_MASK), boldAction); * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), * italicAction); editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_U, KeyEvent.CTRL_MASK), */ /* * editor.getKeymap().addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_Z, * KeyEvent.CTRL_MASK), undoAction); * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_MASK + * KeyEvent.SHIFT_MASK), redoAction); * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK + * KeyEvent.SHIFT_MASK), insertTableCellAction); * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK), */ editor.getKeymap().removeKeyStrokeBinding( KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK)); editor.getKeymap().removeKeyStrokeBinding( KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK)); editor.getKeymap().removeKeyStrokeBinding( KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK)); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK), copyAction); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_MASK), pasteAction); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke( KeyEvent.VK_V, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK), stylePasteAction); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK), cutAction); editor.getKeymap().addActionForKeyStroke( KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK), findAction); /* * editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, KeyEvent.CTRL_MASK), * zoomInAction); editor.getKeymap().addActionForKeyStroke( * KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, KeyEvent.CTRL_MASK), */ /* POPUP MENUs */ /* * jMenuItemUndo.setAction(undoAction); jMenuItemUndo.setText("Undo"); * jMenuItemUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, * KeyEvent.CTRL_MASK)); jMenuItemUndo.setIcon( new * ImageIcon(org.openmechanics.htmleditor.AppFrame.class.getResource("resources/icons/undo16.png"))); * * jMenuItemRedo.setAction(redoAction); jMenuItemRedo.setText("Redo"); * jMenuItemRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, * KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); jMenuItemRedo.setIcon( * new * ImageIcon(org.openmechanics.htmleditor.AppFrame.class.getResource("resources/icons/redo16.png"))); * * jMenuItemCut.setAction(cutAction); jMenuItemCut.setText("Cut"); * jMenuItemCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, * KeyEvent.CTRL_MASK)); jMenuItemCut.setIcon( new * ImageIcon(org.openmechanics.htmleditor.AppFrame.class.getResource("resources/icons/cut.png"))); * * jMenuItemCopy.setAction(copyAction); jMenuItemCopy.setText("Copy"); * jMenuItemCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, * KeyEvent.CTRL_MASK)); jMenuItemCopy.setIcon( new * ImageIcon(org.openmechanics.htmleditor.AppFrame.class.getResource("resources/icons/copy.png"))); * * jMenuItemPaste.setAction(pasteAction); * jMenuItemPaste.setText("Paste"); * jMenuItemPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, * KeyEvent.CTRL_MASK)); jMenuItemPaste.setIcon( new * ImageIcon(org.openmechanics.htmleditor.AppFrame.class.getResource("resources/icons/paste.png"))); * * jMenuItemProp.setAction(propsAction); * jMenuItemProp.setText("Properties"); jMenuItemProp.setIcon( */ /* * defaultPopupMenu.add(jMenuItemUndo); * defaultPopupMenu.add(jMenuItemRedo); * defaultPopupMenu.addSeparator(); defaultPopupMenu.add(jMenuItemCut); * defaultPopupMenu.add(jMenuItemCopy); * defaultPopupMenu.add(jMenuItemPaste); * defaultPopupMenu.addSeparator(); */ /* * jMenuItemInsCell.setAction(new InsertTableCellAction()); * jMenuItemInsCell.setText(Local.getString("Insert table cell")); * * jMenuItemInsRow.setAction(new InsertTableRowAction()); */ /* * tablePopupMenu.add(jMenuItemUndo); * tablePopupMenu.add(jMenuItemRedo); tablePopupMenu.addSeparator(); * tablePopupMenu.add(jMenuItemCut); tablePopupMenu.add(jMenuItemCopy); * tablePopupMenu.add(jMenuItemPaste); tablePopupMenu.addSeparator(); * tablePopupMenu.add(jMenuItemInsCell); * tablePopupMenu.add(jMenuItemInsRow); tablePopupMenu.addSeparator(); */ editor.addMouseListener(new PopupListener()); document.getStyleSheet().setBaseFontSize(currentFontSize); this.requestFocusInWindow(); } class PopupListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { JPopupMenu popupMenu = new JPopupMenu(); popupMenu.setFocusable(false); popupMenu.add(jMenuItemUndo); popupMenu.add(jMenuItemRedo); popupMenu.addSeparator(); popupMenu.add(jMenuItemCut); popupMenu.add(jMenuItemCopy); popupMenu.add(jMenuItemPaste); popupMenu.addSeparator(); if (jMenuItemInsCell.getAction().isEnabled()) { popupMenu.add(jMenuItemInsCell); jMenuItemInsCell.setEnabled(true); popupMenu.add(jMenuItemInsRow); jMenuItemInsRow.setEnabled(true); popupMenu.addSeparator(); } popupMenu.add(jMenuItemProp); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } } /** * Resets the undo manager. */ protected void resetUndoManager() { undo.discardAllEdits(); undoAction.update(); redoAction.update(); } class UndoHandler implements UndoableEditListener { /** * Messaged when the Document has created an edit, the edit is added to * <code>undo</code>, an instance of UndoManager. */ @Override public void undoableEditHappened(UndoableEditEvent e) { undo.addEdit(e.getEdit()); undoAction.update(); redoAction.update(); } } class UndoAction extends AbstractAction { public UndoAction() { super(Local.getString("Undo")); setEnabled(false); putValue( Action.SMALL_ICON, new ImageIcon(cl.getResource(RESOURCE_FOLDER + "undo16.png"))); putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { LOG.warn("action failed", ex); } update(); redoAction.update(); } protected void update() { if (undo.canUndo()) { setEnabled(true); putValue( Action.SHORT_DESCRIPTION, undo.getUndoPresentationName()); } else { setEnabled(false); putValue(Action.SHORT_DESCRIPTION, Local.getString("Undo")); } } } class RedoAction extends AbstractAction { public RedoAction() { super(Local.getString("Redo")); setEnabled(false); putValue( Action.SMALL_ICON, new ImageIcon(cl.getResource(RESOURCE_FOLDER + "redo16.png"))); putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_Z, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); } @Override public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { LOG.warn("Redo failed", ex); } update(); undoAction.update(); } protected void update() { if (undo.canRedo()) { setEnabled(true); putValue( Action.SHORT_DESCRIPTION, undo.getRedoPresentationName()); } else { setEnabled(false); putValue(Action.SHORT_DESCRIPTION, Local.getString("Redo")); } } } public class BlockAction extends AbstractAction { int _type; public BlockAction(int type, String name) { super(name); _type = type; } @Override public void actionPerformed(ActionEvent e) { blockCB.setSelectedIndex(_type); } } public class InlineAction extends AbstractAction { int _type; public InlineAction(int type, String name) { super(name); _type = type; } @Override public void actionPerformed(ActionEvent e) { inlineCB.setSelectedIndex(_type); } } public String getContent() { try { return editor.getText(); } catch (Exception e) { LOG.warn("getContent()", e); return ""; } } public void boldActionB_actionPerformed(ActionEvent e) { if (!bold) { boldActionB.setBorder(border2); } else { boldActionB.setBorder(border1); } bold = !bold; boldActionB.setBorderPainted(bold); /* * SimpleAttributeSet attrs = new SimpleAttributeSet(); * attrs.addAttribute(StyleConstants.Bold, new Boolean(bold)); */ new StyledEditorKit.BoldAction().actionPerformed(e); } public void italicActionB_actionPerformed(ActionEvent e) { if (!italic) { italicActionB.setBorder(border2); } else { italicActionB.setBorder(border1); } italic = !italic; italicActionB.setBorderPainted(italic); new StyledEditorKit.ItalicAction().actionPerformed(e); } public void underActionB_actionPerformed(ActionEvent e) { if (!under) { underActionB.setBorder(border2); } else { underActionB.setBorder(border1); } under = !under; underActionB.setBorderPainted(under); new StyledEditorKit.UnderlineAction().actionPerformed(e); } void editor_caretUpdate(CaretEvent e) { currentCaret = e.getDot(); AttributeSet charattrs = null; if (editor.getCaretPosition() > 0) { try { charattrs = document .getCharacterElement(editor.getCaretPosition() - 1) .getAttributes(); } catch (Exception ex) { LOG.warn("action failed", ex); } } else { charattrs = document .getCharacterElement(editor.getCaretPosition()) .getAttributes(); } if (charattrs .containsAttribute(StyleConstants.Bold, Boolean.TRUE)) { boldActionB.setBorder(border2); bold = true; } else if (bold) { boldActionB.setBorder(border1); bold = false; } boldActionB.setBorderPainted(bold); if (charattrs .containsAttribute(StyleConstants.Italic, Boolean.TRUE)) { italicActionB.setBorder(border2); italic = true; } else if (italic) { italicActionB.setBorder(border1); italic = false; } italicActionB.setBorderPainted(italic); if (charattrs .containsAttribute(StyleConstants.Underline, Boolean.TRUE)) { underActionB.setBorder(border2); under = true; } else if (under) { underActionB.setBorder(border1); under = false; } underActionB.setBorderPainted(under); /* * String iName = document * .getCharacterElement(editor.getCaretPosition()) .getAttributes() * .getAttribute(StyleConstants.NameAttribute) .toString() */ inlineCBEventsLock = true; inlineCB.setEnabled(!charattrs.isDefined(HTML.Tag.A)); if (charattrs.isDefined(HTML.Tag.EM)) { inlineCB.setSelectedIndex(I_EM); } else if (charattrs.isDefined(HTML.Tag.STRONG)) { inlineCB.setSelectedIndex(I_STRONG); } else if ( (charattrs.isDefined(HTML.Tag.CODE)) || (charattrs.isDefined(HTML.Tag.SAMP))) { inlineCB.setSelectedIndex(I_CODE); } else if (charattrs.isDefined(HTML.Tag.SUP)) { inlineCB.setSelectedIndex(I_SUPERSCRIPT); } else if (charattrs.isDefined(HTML.Tag.SUB)) { inlineCB.setSelectedIndex(I_SUBSCRIPT); } else if (charattrs.isDefined(HTML.Tag.CITE)) { inlineCB.setSelectedIndex(I_CITE); } else if (charattrs.isDefined(HTML.Tag.FONT)) { inlineCB.setSelectedIndex(I_CUSTOM); } else { inlineCB.setSelectedIndex(I_NORMAL); } inlineCBEventsLock = false; Element pEl = document.getParagraphElement(editor.getCaretPosition()); String pName = pEl.getName().toUpperCase(); blockCBEventsLock = true; if (pName.equals("P-IMPLIED")) { pName = pEl.getParentElement().getName().toUpperCase(); } switch (pName) { case "P": blockCB.setSelectedIndex(T_P); break; case "H1": blockCB.setSelectedIndex(T_H1); break; case "H2": blockCB.setSelectedIndex(T_H2); break; case "H3": blockCB.setSelectedIndex(T_H3); break; case "H4": blockCB.setSelectedIndex(T_H4); break; case "H5": blockCB.setSelectedIndex(T_H5); break; case "H6": blockCB.setSelectedIndex(T_H6); break; case "PRE": blockCB.setSelectedIndex(T_PRE); break; case "BLOCKQUOTE": blockCB.setSelectedIndex(T_BLOCKQ); break; } blockCBEventsLock = false; this.insertTableCellAction.update(); this.insertTableRowAction.update(); } public void ulActionB_actionPerformed(ActionEvent e) { String parentname = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName(); HTML.Tag parentTag = HTML.getTag(parentname); HTMLEditorKit.InsertHTMLTextAction ulAction = new HTMLEditorKit.InsertHTMLTextAction( "insertUL", "<ul><li></li></ul>", parentTag, HTML.Tag.UL); ulAction.actionPerformed(e); list = true; } public void olActionB_actionPerformed(ActionEvent e) { String parentname = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName(); HTML.Tag parentTag = HTML.getTag(parentname); HTMLEditorKit.InsertHTMLTextAction olAction = new HTMLEditorKit.InsertHTMLTextAction( "insertOL", "<ol><li></li></ol>", parentTag, HTML.Tag.OL); olAction.actionPerformed(e); list = true; } void removeIfEmpty(Element elem) { if (elem.getEndOffset() - elem.getStartOffset() < 2) { try { document.remove(elem.getStartOffset(), elem.getEndOffset()); } catch (Exception ex) { LOG.warn("action failed", ex); } } } class ParaBreakAction extends AbstractAction { ParaBreakAction() { super("ParaBreakAction"); } @Override public void actionPerformed(ActionEvent e) { Element elem = document.getParagraphElement(editor.getCaretPosition()); String elName = elem.getName().toUpperCase(); String parentname = elem.getParentElement().getName(); HTML.Tag parentTag = HTML.getTag(parentname); if (parentname.toUpperCase().equals("P-IMPLIED")) { parentTag = HTML.Tag.IMPLIED; } if (parentname.toLowerCase().equals("li")) { // HTML.Tag listTag = // HTML.getTag(elem.getParentElement().getParentElement().getName()); if (elem.getEndOffset() - elem.getStartOffset() > 1) { try { document.insertAfterEnd( elem.getParentElement(), "<li></li>"); editor.setCaretPosition( elem.getParentElement().getEndOffset()); } catch (Exception ex) { LOG.warn("action failed", ex); } } else { try { document.remove(editor.getCaretPosition(), 1); } catch (Exception ex) { LOG.warn("action failed", ex); } Element listParentElement = elem .getParentElement() .getParentElement() .getParentElement(); HTML.Tag listParentTag = HTML.getTag(listParentElement.getName()); String listParentTagName = listParentTag.toString(); if (listParentTagName.toLowerCase().equals("li")) { Element listAncEl = listParentElement.getParentElement(); try { editorKit.insertHTML( document, listAncEl.getEndOffset(), "<li><p></p></li>", 3, 0, HTML.Tag.LI); } catch (Exception ex) { LOG.warn("action failed", ex); } } else { HTMLEditorKit.InsertHTMLTextAction pAction = new HTMLEditorKit.InsertHTMLTextAction( "insertP", "<p></p>", listParentTag, HTML.Tag.P); pAction.actionPerformed(e); } } } else if ( (elName.equals("PRE")) || (elName.equals("ADDRESS")) || (elName.equals("BLOCKQUOTE"))) { if (editor.getCaretPosition() > 0) { removeIfEmpty( document.getParagraphElement( editor.getCaretPosition() - 1)); } HTMLEditorKit.InsertHTMLTextAction pAction = new HTMLEditorKit.InsertHTMLTextAction( "insertP", "<p></p>", parentTag, HTML.Tag.P); pAction.actionPerformed(e); } else if (elName.equals("P-IMPLIED")) { try { document.insertAfterEnd(elem.getParentElement(), "<p></p>"); editor.setCaretPosition( elem.getParentElement().getEndOffset()); } catch (Exception ex) { LOG.warn("action failed", ex); } } else { editor.replaceSelection("\n"); editorKit.getInputAttributes().removeAttribute( HTML.Attribute.ID); editorKit.getInputAttributes().removeAttribute( HTML.Attribute.CLASS); } } } class BreakAction extends AbstractAction { BreakAction() { super( Local.getString("Insert break"), new ImageIcon(cl.getResource(RESOURCE_FOLDER + "break.png"))); } @Override public void actionPerformed(ActionEvent e) { String elName = document .getParagraphElement(editor.getCaretPosition()) .getName(); HTML.Tag tag = HTML.getTag(elName); if (elName.toUpperCase().equals("P-IMPLIED")) { tag = HTML.Tag.IMPLIED; } HTMLEditorKit.InsertHTMLTextAction hta = new HTMLEditorKit.InsertHTMLTextAction( "insertBR", "<br>", tag, HTML.Tag.BR); hta.actionPerformed(e); //insertHTML("<br>",editor.getCaretPosition()); } } class InsertTableRowAction extends AbstractAction { InsertTableRowAction() { super(Local.getString("Insert table row")); this.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { String trTag = "<tr>"; Element tr = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getParentElement(); for (int i = 0; i < tr.getElementCount(); i++) { if (tr.getElement(i).getName().toUpperCase().equals("TD")) { trTag += "<td><p></p></td>"; } } trTag += "</tr>"; try { document.insertAfterEnd(tr, trTag); //editorKit.insertHTML(document, editor.getCaretPosition(), // trTag, 3, 0, HTML.Tag.TR); } catch (Exception ex) { LOG.warn("action failed", ex); } } @Override public boolean isEnabled() { return document != null && document.getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName() .toUpperCase() .equals("TD"); } public void update() { this.setEnabled(isEnabled()); } } class InsertTableCellAction extends AbstractAction { InsertTableCellAction() { super(Local.getString("Insert table cell")); this.putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK + KeyEvent.SHIFT_MASK)); } @Override public void actionPerformed(ActionEvent e) { String tdTag = "<td><p></p></td>"; Element td = document .getParagraphElement(editor.getCaretPosition()) .getParentElement(); try { document.insertAfterEnd(td, tdTag); } catch (Exception ex) { LOG.warn("action failed", ex); } } @Override public boolean isEnabled() { return document != null && document.getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName() .toUpperCase() .equals("TD"); } public void update() { this.setEnabled(isEnabled()); } } public void lAlignActionB_actionPerformed(ActionEvent e) { HTMLEditorKit.AlignmentAction aa = new HTMLEditorKit.AlignmentAction( "leftAlign", StyleConstants.ALIGN_LEFT); aa.actionPerformed(e); } public void cAlignActionB_actionPerformed(ActionEvent e) { HTMLEditorKit.AlignmentAction aa = new HTMLEditorKit.AlignmentAction( "centerAlign", StyleConstants.ALIGN_CENTER); aa.actionPerformed(e); } public void rAlignActionB_actionPerformed(ActionEvent e) { HTMLEditorKit.AlignmentAction aa = new HTMLEditorKit.AlignmentAction( "rightAlign", StyleConstants.ALIGN_RIGHT); aa.actionPerformed(e); } public void jAlignActionB_actionPerformed(ActionEvent e) { HTMLEditorKit.AlignmentAction aa = new HTMLEditorKit.AlignmentAction( "justifyAlign", StyleConstants.ALIGN_JUSTIFIED); aa.actionPerformed(e); } public void insertHTML(String html, int location) { //assumes editor is already set to "text/html" type try { HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); Document doc = editor.getDocument(); StringReader reader = new StringReader(html); kit.read(reader, doc, location); } catch (Exception ex) { LOG.warn("action failed", ex); } } public void imageActionB_actionPerformed(ActionEvent e) { ImageDialog dlg = new ImageDialog(null); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); //dlg.setLocation(imageActionB.getLocationOnScreen()); dlg.setModal(true); dlg.setVisible(true); if (!dlg.CANCELLED) { String parentname = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName(); //HTML.Tag parentTag = HTML.getTag(parentname); String urlString = dlg.fileField.getText(); String path = urlString; if (imagesDir != null) { try { URL url = new URL(urlString); if (!url.getProtocol().startsWith("http")) { path = imagesDir + "/" + url.getFile(); } } catch (MalformedURLException e1) { // no-op } } try { String imgTag = "<img src=\"" + path + "\" alt=\"" + dlg.altField.getText() + "\" "; String w = dlg.widthField.getText(); try { Integer.parseInt(w, 10); imgTag += " width=\"" + w + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String h = dlg.heightField.getText(); try { Integer.parseInt(h, 10); imgTag += " height=\"" + h + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String hs = dlg.hspaceField.getText(); try { Integer.parseInt(hs, 10); imgTag += " hspace=\"" + hs + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String vs = dlg.vspaceField.getText(); try { Integer.parseInt(vs, 10); imgTag += " vspace=\"" + vs + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String b = dlg.borderField.getText(); try { Integer.parseInt(b, 10); imgTag += " border=\"" + b + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } if (dlg.alignCB.getSelectedIndex() > 0) { imgTag += " align=\"" + dlg.alignCB.getSelectedItem() + "\" "; } imgTag += ">"; if (!dlg.urlField.getText().isEmpty()) { imgTag = "<a href=\"" + dlg.urlField.getText() + "\">" + imgTag + "</a>"; if (editor.getCaretPosition() == document.getLength()) { imgTag += "&nbsp;"; } editorKit.insertHTML( document, editor.getCaretPosition(), imgTag, 0, 0, HTML.Tag.A); } else { editorKit.insertHTML( document, editor.getCaretPosition(), imgTag, 0, 0, HTML.Tag.IMG); } } catch (Exception ex) { LOG.warn("action failed", ex); } } } public void tableActionB_actionPerformed(ActionEvent e) { TableDialog dlg = new TableDialog(null); //dlg.setLocation(tableActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.setVisible(true); if (dlg.CANCELLED) { return; } String tableTag = "<table "; String w = dlg.widthField.getText().trim(); if (!w.isEmpty()) { tableTag += " width=\"" + w + "\" "; } String h = dlg.heightField.getText().trim(); if (!h.isEmpty()) { tableTag += " height=\"" + h + "\" "; } String cp = dlg.cellpadding.getValue().toString(); try { Integer.parseInt(cp, 10); tableTag += " cellpadding=\"" + cp + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String cs = dlg.cellspacing.getValue().toString(); try { Integer.parseInt(cs, 10); tableTag += " cellspacing=\"" + cs + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String b = dlg.border.getValue().toString(); try { Integer.parseInt(b, 10); tableTag += " border=\"" + b + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } if (dlg.alignCB.getSelectedIndex() > 0) { tableTag += " align=\"" + dlg.alignCB.getSelectedItem() + "\" "; } if (dlg.vAlignCB.getSelectedIndex() > 0) { tableTag += " valign=\"" + dlg.vAlignCB.getSelectedItem() + "\" "; } if (!dlg.bgcolorField.getText().isEmpty()) { tableTag += " bgcolor=\"" + dlg.bgcolorField.getText() + "\" "; } tableTag += ">"; int cols = 1; int rows = 1; try { cols = (Integer) dlg.columns.getValue(); } catch (Exception ex) { LOG.warn("action failed", ex); } try { rows = (Integer) dlg.rows.getValue(); } catch (Exception ex) { LOG.warn("action failed", ex); } for (int r = 0; r < rows; r++) { tableTag += "<tr>"; for (int c = 0; c < cols; c++) { tableTag += "<td><p></p></td>"; } tableTag += "</tr>"; } tableTag += "</table>"; String parentname = document .getParagraphElement(editor.getCaretPosition()) .getParentElement() .getName(); HTML.Tag parentTag = HTML.getTag(parentname); //insertHTML(tableTag, editor.getCaretPosition()); try { editorKit.insertHTML( document, editor.getCaretPosition(), tableTag, 1, 0, HTML.Tag.TABLE); //removeIfEmpty(document.getParagraphElement(editor.getCaretPosition()-1)); } catch (Exception ex) { LOG.warn("action failed", ex); } } public void linkActionB_actionPerformed(ActionEvent e) { LinkDialog dlg = new LinkDialog(null); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); if (editor.getSelectedText() != null) { dlg.txtDesc.setText(editor.getSelectedText()); } dlg.setVisible(true); if (dlg.CANCELLED) { return; } String aTag = "<a"; if (!dlg.txtURL.getText().isEmpty()) { aTag += " href=\"" + dlg.txtURL.getText() + "\""; } if (!dlg.txtName.getText().isEmpty()) { aTag += " name=\"" + dlg.txtName.getText() + "\""; } if (!dlg.txtTitle.getText().isEmpty()) { aTag += " title=\"" + dlg.txtTitle.getText() + "\""; } if (dlg.chkNewWin.isSelected()) { aTag += " target=\"_blank\""; } aTag += ">" + dlg.txtDesc.getText() + "</a>"; if (editor.getCaretPosition() == document.getLength()) { aTag += "&nbsp;"; } editor.replaceSelection(""); try { editorKit.insertHTML( document, editor.getCaretPosition(), aTag, 0, 0, HTML.Tag.A); } catch (Exception ex) { LOG.warn("action failed", ex); } } void setLinkProperties( Element el, String href, String target, String title, String name) { LinkDialog dlg = new LinkDialog(null); dlg.setLocation(linkActionB.getLocationOnScreen()); dlg.setModal(true); //dlg.descPanel.setVisible(false); dlg.txtURL.setText(href); dlg.txtName.setText(name); dlg.txtTitle.setText(title); try { dlg.txtDesc.setText( document.getText( el.getStartOffset(), el.getEndOffset() - el.getStartOffset())); } catch (Exception ex) { LOG.warn("action failed", ex); } dlg.chkNewWin.setSelected(target.toUpperCase().equals("_BLANK")); dlg.header.setText(Local.getString("Hyperlink properties")); dlg.setTitle(Local.getString("Hyperlink properties")); dlg.setVisible(true); if (dlg.CANCELLED) { return; } String aTag = "<a"; if (!dlg.txtURL.getText().isEmpty()) { aTag += " href=\"" + dlg.txtURL.getText() + "\""; } if (!dlg.txtName.getText().isEmpty()) { aTag += " name=\"" + dlg.txtName.getText() + "\""; } if (!dlg.txtTitle.getText().isEmpty()) { aTag += " title=\"" + dlg.txtTitle.getText() + "\""; } if (dlg.chkNewWin.isSelected()) { aTag += " target=\"_blank\""; } aTag += ">" + dlg.txtDesc.getText() + "</a>"; try { document.setOuterHTML(el, aTag); } catch (Exception ex) { LOG.warn("action failed", ex); } } void setImageProperties( Element el, String src, String alt, String width, String height, String hspace, String vspace, String border, String align) { ImageDialog dlg = new ImageDialog(null); dlg.setLocation(imageActionB.getLocationOnScreen()); dlg.setModal(true); dlg.setTitle(Local.getString("Image properties")); dlg.fileField.setText(src); dlg.altField.setText(alt); dlg.widthField.setText(width); dlg.heightField.setText(height); dlg.hspaceField.setText(hspace); dlg.vspaceField.setText(vspace); dlg.borderField.setText(border); dlg.alignCB.setSelectedItem(align); dlg.updatePreview(); dlg.setVisible(true); if (dlg.CANCELLED) { return; } String imgTag = "<img src=\"" + dlg.fileField.getText() + "\" alt=\"" + dlg.altField.getText() + "\" "; String w = dlg.widthField.getText(); try { Integer.parseInt(w, 10); imgTag += " width=\"" + w + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String h = dlg.heightField.getText(); try { Integer.parseInt(h, 10); imgTag += " height=\"" + h + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String hs = dlg.hspaceField.getText(); try { Integer.parseInt(hs, 10); imgTag += " hspace=\"" + hs + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String vs = dlg.vspaceField.getText(); try { Integer.parseInt(vs, 10); imgTag += " vspace=\"" + vs + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } String b = dlg.borderField.getText(); try { Integer.parseInt(b, 10); imgTag += " border=\"" + b + "\" "; } catch (Exception ex) { LOG.warn("action failed", ex); } if (dlg.alignCB.getSelectedIndex() > 0) { imgTag += " align=\"" + dlg.alignCB.getSelectedItem() + "\" "; } imgTag += ">"; if (!dlg.urlField.getText().isEmpty()) { imgTag = "<a href=\"" + dlg.urlField.getText() + "\">" + imgTag + "</a>"; if (editor.getCaretPosition() == document.getLength()) { imgTag += "&nbsp;"; } } try { document.setOuterHTML(el, imgTag); } catch (Exception ex) { LOG.warn("action failed", ex); } } void setElementProperties(Element el, String id, String cls, String sty) { ElementDialog dlg = new ElementDialog(null); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.setTitle(Local.getString("Object properties")); dlg.idField.setText(id); dlg.classField.setText(cls); dlg.styleField.setText(sty); // Uncommented, returns a simple p into the header... fix needed ? //dlg.header.setText(el.getName()); dlg.setVisible(true); if (dlg.CANCELLED) { return; } SimpleAttributeSet attrs = new SimpleAttributeSet(el.getAttributes()); if (!dlg.idField.getText().isEmpty()) { attrs.addAttribute(HTML.Attribute.ID, dlg.idField.getText()); } if (!dlg.classField.getText().isEmpty()) { attrs.addAttribute(HTML.Attribute.CLASS, dlg.classField.getText()); } if (!dlg.styleField.getText().isEmpty()) { attrs.addAttribute(HTML.Attribute.STYLE, dlg.styleField.getText()); } document.setParagraphAttributes(el.getStartOffset(), 0, attrs, true); } void setTableProperties(Element td) { Element tr = td.getParentElement(); Element table = tr.getParentElement(); TdDialog dlg = new TdDialog(null); dlg.setLocation(editor.getLocationOnScreen()); dlg.setModal(true); dlg.setTitle(Local.getString("Table properties")); AttributeSet tda = td.getAttributes(); if (tda.isDefined(HTML.Attribute.BGCOLOR)) { dlg.tdBgcolorField.setText( tda.getAttribute(HTML.Attribute.BGCOLOR).toString()); Util.setBgcolorField(dlg.tdBgcolorField); } if (tda.isDefined(HTML.Attribute.WIDTH)) { dlg.tdWidthField.setText( tda.getAttribute(HTML.Attribute.WIDTH).toString()); } if (tda.isDefined(HTML.Attribute.HEIGHT)) { dlg.tdHeightField.setText( tda.getAttribute(HTML.Attribute.HEIGHT).toString()); } if (tda.isDefined(HTML.Attribute.COLSPAN)) { try { Integer i = new Integer( tda.getAttribute(HTML.Attribute.COLSPAN).toString()); dlg.tdColspan.setValue(i); } catch (Exception ex) { LOG.warn("action failed", ex); } } if (tda.isDefined(HTML.Attribute.ROWSPAN)) { try { Integer i = new Integer( tda.getAttribute(HTML.Attribute.ROWSPAN).toString()); dlg.tdRowspan.setValue(i); } catch (Exception ex) { LOG.warn("action failed", ex); } } if (tda.isDefined(HTML.Attribute.ALIGN)) { dlg.tdAlignCB.setSelectedItem( tda .getAttribute(HTML.Attribute.ALIGN) .toString() .toLowerCase()); } if (tda.isDefined(HTML.Attribute.VALIGN)) { dlg.tdValignCB.setSelectedItem( tda .getAttribute(HTML.Attribute.VALIGN) .toString() .toLowerCase()); } dlg.tdNowrapChB.setSelected((tda.isDefined(HTML.Attribute.NOWRAP))); AttributeSet tra = tr.getAttributes(); if (tra.isDefined(HTML.Attribute.BGCOLOR)) { dlg.trBgcolorField.setText( tra.getAttribute(HTML.Attribute.BGCOLOR).toString()); Util.setBgcolorField(dlg.trBgcolorField); } if (tra.isDefined(HTML.Attribute.ALIGN)) { dlg.trAlignCB.setSelectedItem( tra .getAttribute(HTML.Attribute.ALIGN) .toString() .toLowerCase()); } if (tra.isDefined(HTML.Attribute.VALIGN)) { dlg.trValignCB.setSelectedItem( tra .getAttribute(HTML.Attribute.VALIGN) .toString() .toLowerCase()); } AttributeSet ta = table.getAttributes(); if (ta.isDefined(HTML.Attribute.BGCOLOR)) { dlg.bgcolorField.setText( ta.getAttribute(HTML.Attribute.BGCOLOR).toString()); Util.setBgcolorField(dlg.bgcolorField); } if (ta.isDefined(HTML.Attribute.WIDTH)) { dlg.widthField.setText( ta.getAttribute(HTML.Attribute.WIDTH).toString()); } if (ta.isDefined(HTML.Attribute.HEIGHT)) { dlg.heightField.setText( ta.getAttribute(HTML.Attribute.HEIGHT).toString()); } if (ta.isDefined(HTML.Attribute.ALIGN)) { dlg.alignCB.setSelectedItem( ta.getAttribute(HTML.Attribute.ALIGN).toString().toLowerCase()); } if (ta.isDefined(HTML.Attribute.VALIGN)) { dlg.vAlignCB.setSelectedItem( ta .getAttribute(HTML.Attribute.VALIGN) .toString() .toLowerCase()); } if (ta.isDefined(HTML.Attribute.CELLPADDING)) { try { Integer i = new Integer( ta.getAttribute(HTML.Attribute.CELLPADDING).toString()); dlg.cellpadding.setValue(i); } catch (Exception ex) { LOG.warn("action failed", ex); } } if (ta.isDefined(HTML.Attribute.CELLSPACING)) { try { Integer i = new Integer( ta.getAttribute(HTML.Attribute.CELLSPACING).toString()); dlg.cellspacing.setValue(i); } catch (Exception ex) { LOG.warn("action failed", ex); } } if (ta.isDefined(HTML.Attribute.BORDER)) { try { Integer i = new Integer( ta.getAttribute(HTML.Attribute.BORDER).toString()); dlg.border.setValue(i); } catch (Exception ex) { LOG.warn("action failed", ex); } } dlg.setVisible(true); if (dlg.CANCELLED) { return; } String tdTag = "<td"; if (!dlg.tdBgcolorField.getText().isEmpty()) { tdTag += " bgcolor=\"" + dlg.tdBgcolorField.getText() + "\""; } if (!dlg.tdWidthField.getText().isEmpty()) { tdTag += " width=\"" + dlg.tdWidthField.getText() + "\""; } if (!dlg.tdHeightField.getText().isEmpty()) { tdTag += " height=\"" + dlg.tdHeightField.getText() + "\""; } if (!dlg.tdColspan.getValue().toString().equals("0")) { tdTag += " colspan=\"" + dlg.tdColspan.getValue().toString() + "\""; } if (!dlg.tdRowspan.getValue().toString().equals("0")) { tdTag += " rowspan=\"" + dlg.tdRowspan.getValue().toString() + "\""; } if (!dlg.tdAlignCB.getSelectedItem().toString().isEmpty()) { tdTag += " align=\"" + dlg.tdAlignCB.getSelectedItem().toString() + "\""; } if (!dlg.tdValignCB.getSelectedItem().toString().isEmpty()) { tdTag += " valign=\"" + dlg.tdValignCB.getSelectedItem().toString() + "\""; } if (dlg.tdNowrapChB.isSelected()) { tdTag += " nowrap"; } tdTag += ">"; String trTag = "<tr"; if (!dlg.trBgcolorField.getText().isEmpty()) { trTag += " bgcolor=\"" + dlg.trBgcolorField.getText() + "\""; } if (!dlg.trAlignCB.getSelectedItem().toString().isEmpty()) { trTag += " align=\"" + dlg.trAlignCB.getSelectedItem().toString() + "\""; } if (!dlg.trValignCB.getSelectedItem().toString().isEmpty()) { trTag += " valign=\"" + dlg.trValignCB.getSelectedItem().toString() + "\""; } trTag += ">"; String tTag = "<table"; if (!dlg.bgcolorField.getText().isEmpty()) { tTag += " bgcolor=\"" + dlg.bgcolorField.getText() + "\""; } if (!dlg.widthField.getText().isEmpty()) { tTag += " width=\"" + dlg.widthField.getText() + "\""; } if (!dlg.heightField.getText().isEmpty()) { tTag += " height=\"" + dlg.heightField.getText() + "\""; } tTag += " cellpadding=\"" + dlg.cellpadding.getValue().toString() + "\""; tTag += " cellspacing=\"" + dlg.cellspacing.getValue().toString() + "\""; tTag += " border=\"" + dlg.border.getValue().toString() + "\""; if (!dlg.alignCB.getSelectedItem().toString().isEmpty()) { tTag += " align=\"" + dlg.alignCB.getSelectedItem().toString() + "\""; } if (!dlg.vAlignCB.getSelectedItem().toString().isEmpty()) { tTag += " valign=\"" + dlg.vAlignCB.getSelectedItem().toString() + "\""; } tTag += ">"; try { StringWriter sw = new StringWriter(); String copy; editorKit.write( sw, document, td.getStartOffset(), td.getEndOffset() - td.getStartOffset()); copy = sw.toString(); copy = copy.split("<td(.*?)>")[1]; copy = copy.split("</td>")[0]; document.setOuterHTML(td, tdTag + copy + "</td>"); sw = new StringWriter(); editorKit.write( sw, document, tr.getStartOffset(), tr.getEndOffset() - tr.getStartOffset()); copy = sw.toString(); copy = copy.split("<tr(.*?)>")[1]; copy = copy.split("</tr>")[0]; document.setOuterHTML(tr, trTag + copy + "</tr>"); sw = new StringWriter(); editorKit.write( sw, document, table.getStartOffset(), table.getEndOffset() - table.getStartOffset()); copy = sw.toString(); copy = copy.split("<table(.*?)>")[1]; copy = copy.split("</table>")[0]; document.setOuterHTML(table, tTag + copy + "</table>"); } catch (Exception ex) { LOG.warn("table props set failed!", ex); } } void blockCB_actionPerformed(ActionEvent e) { if (blockCBEventsLock) { return; } int sel = blockCB.getSelectedIndex(); HTML.Tag tag = null; switch (sel) { case T_P: tag = HTML.Tag.P; break; case T_H1: tag = HTML.Tag.H1; break; case T_H2: tag = HTML.Tag.H2; break; case T_H3: tag = HTML.Tag.H3; break; case T_H4: tag = HTML.Tag.H4; break; case T_H5: tag = HTML.Tag.H5; break; case T_H6: tag = HTML.Tag.H6; break; case T_PRE: tag = HTML.Tag.PRE; break; case T_BLOCKQ: tag = HTML.Tag.BLOCKQUOTE; break; } Element el = document.getParagraphElement(editor.getCaretPosition()); if (el.getName().toUpperCase().equals("P-IMPLIED")) { Element pEl = el.getParentElement(); String pElName = pEl.getName(); String newName = tag.toString(); StringWriter sw = new StringWriter(); String copy; try { editorKit.write( sw, document, el.getStartOffset(), el.getEndOffset() - el.getStartOffset()); copy = sw.toString(); copy = copy.split("<" + pElName + "(.*?)>")[1]; copy = copy.split("</" + pElName + ">")[0]; document.setOuterHTML( pEl, "<" + newName + ">" + copy + "</" + newName + ">"); return; } catch (Exception ex) { LOG.warn("action failed", ex); } } SimpleAttributeSet attrs = new SimpleAttributeSet(el.getAttributes()); //attrs.removeAttribute(StyleConstants.NameAttribute); attrs.addAttribute(StyleConstants.NameAttribute, tag); if (editor.getSelectionEnd() - editor.getSelectionStart() > 0) { document.setParagraphAttributes( editor.getSelectionStart(), editor.getSelectionEnd() - editor.getSelectionStart(), attrs, true); } else { document.setParagraphAttributes( editor.getCaretPosition(), 0, attrs, true); } } public void propsActionB_actionPerformed(ActionEvent e) { AbstractDocument.BranchElement pEl = (AbstractDocument.BranchElement) document.getParagraphElement( editor.getCaretPosition()); Element el = pEl.positionToElement(editor.getCaretPosition()); AttributeSet attrs = el.getAttributes(); String elName = attrs .getAttribute(StyleConstants.NameAttribute) .toString() .toUpperCase(); if (elName.equals("IMG")) { String src = "", alt = "", width = "", height = "", hspace = "", vspace = "", border = "", align = ""; if (attrs.isDefined(HTML.Attribute.SRC)) { src = attrs.getAttribute(HTML.Attribute.SRC).toString(); } if (attrs.isDefined(HTML.Attribute.ALT)) { alt = attrs.getAttribute(HTML.Attribute.ALT).toString(); } if (attrs.isDefined(HTML.Attribute.WIDTH)) { width = attrs.getAttribute(HTML.Attribute.WIDTH).toString(); } if (attrs.isDefined(HTML.Attribute.HEIGHT)) { height = attrs.getAttribute(HTML.Attribute.HEIGHT).toString(); } if (attrs.isDefined(HTML.Attribute.HSPACE)) { hspace = attrs.getAttribute(HTML.Attribute.HSPACE).toString(); } if (attrs.isDefined(HTML.Attribute.VSPACE)) { vspace = attrs.getAttribute(HTML.Attribute.VSPACE).toString(); } if (attrs.isDefined(HTML.Attribute.BORDER)) { border = attrs.getAttribute(HTML.Attribute.BORDER).toString(); } if (attrs.isDefined(HTML.Attribute.ALIGN)) { align = attrs.getAttribute(HTML.Attribute.ALIGN).toString(); } setImageProperties( el, src, alt, width, height, hspace, vspace, border, align); return; } Object k; for (Enumeration en = attrs.getAttributeNames(); en.hasMoreElements(); ) { k = en.nextElement(); if (k.toString().equals("a")) { String[] param = attrs.getAttribute(k).toString().split(" "); String href = "", target = "", title = "", name = ""; for (final String aParam : param) { if (aParam.startsWith("href=")) { href = aParam.split("=")[1]; } else if (aParam.startsWith("title=")) { title = aParam.split("=")[1]; } else if (aParam.startsWith("target=")) { target = aParam.split("=")[1]; } else if (aParam.startsWith("name=")) { name = aParam.split("=")[1]; } } setLinkProperties(el, href, target, title, name); return; } } if (pEl.getParentElement().getName().toUpperCase().equals("TD")) { setTableProperties(pEl.getParentElement()); return; } String id = "", cls = "", sty = ""; AttributeSet pa = pEl.getAttributes(); if (pa.getAttribute(HTML.Attribute.ID) != null) { id = pa.getAttribute(HTML.Attribute.ID).toString(); } if (pa.getAttribute(HTML.Attribute.CLASS) != null) { cls = pa.getAttribute(HTML.Attribute.CLASS).toString(); } if (pa.getAttribute(HTML.Attribute.STYLE) != null) { sty = pa.getAttribute(HTML.Attribute.STYLE).toString(); } setElementProperties(pEl, id, cls, sty); } String setFontProperties(Element el, String text) { FontDialog dlg = new FontDialog(null); //dlg.setLocation(editor.getLocationOnScreen()); Dimension dlgSize = dlg.getSize(); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); AttributeSet ea = el.getAttributes(); if (ea.isDefined(StyleConstants.FontFamily)) { dlg.fontFamilyCB.setSelectedItem( ea.getAttribute(StyleConstants.FontFamily).toString()); } if (ea.isDefined(HTML.Tag.FONT)) { String s = ea.getAttribute(HTML.Tag.FONT).toString(); String size = s.substring(s.indexOf("size=") + 5, s.indexOf("size=") + 6); dlg.fontSizeCB.setSelectedItem(size); } if (ea.isDefined(StyleConstants.Foreground)) { dlg.colorField.setText( Util.encodeColor( (Color) ea.getAttribute(StyleConstants.Foreground))); Util.setColorField(dlg.colorField); dlg.sample.setForeground( (Color) ea.getAttribute(StyleConstants.Foreground)); } if (text != null) { dlg.sample.setText(text); } dlg.setVisible(true); if (dlg.CANCELLED) { return null; } String attrs = ""; if (dlg.fontSizeCB.getSelectedIndex() > 0) { attrs += "size=\"" + dlg.fontSizeCB.getSelectedItem() + "\""; } if (dlg.fontFamilyCB.getSelectedIndex() > 0) { attrs += "face=\"" + dlg.fontFamilyCB.getSelectedItem() + "\""; } if (!dlg.colorField.getText().isEmpty()) { attrs += "color=\"" + dlg.colorField.getText() + "\""; } if (!attrs.isEmpty()) { return " " + attrs; } else { return null; } } void inlineCB_actionPerformed(ActionEvent e) { if (inlineCBEventsLock) { return; } int sel = inlineCB.getSelectedIndex(); if (sel == I_NORMAL) { Element el = document.getCharacterElement(editor.getCaretPosition()); SimpleAttributeSet attrs = new SimpleAttributeSet(); attrs.addAttribute(StyleConstants.NameAttribute, HTML.Tag.CONTENT); if (editor.getSelectionEnd() > editor.getSelectionStart()) { document.setCharacterAttributes( editor.getSelectionStart(), editor.getSelectionEnd() - editor.getSelectionStart(), attrs, true); } else { document.setCharacterAttributes( el.getStartOffset(), el.getEndOffset() - el.getStartOffset(), attrs, true); } return; } String text = "&nbsp;"; if (editor.getSelectedText() != null) { text = editor.getSelectedText(); } String tag = ""; String att = ""; switch (sel) { case I_EM: tag = "em"; break; case I_STRONG: tag = "strong"; break; case I_CODE: tag = "code"; break; case I_SUPERSCRIPT: tag = "sup"; break; case I_SUBSCRIPT: tag = "sub"; break; case I_CITE: tag = "cite"; break; case I_CUSTOM: tag = "font"; att = setFontProperties( document.getCharacterElement(editor.getCaretPosition()), editor.getSelectedText()); if (att == null) { return; } break; } String html = "<" + tag + att + ">" + text + "</" + tag + ">"; if (editor.getCaretPosition() == document.getLength()) { html += "&nbsp;"; } editor.replaceSelection(""); try { editorKit.insertHTML( document, editor.getCaretPosition(), html, 0, 0, HTML.getTag(tag)); if (editor.getCaretPosition() == document.getLength()) { editor.setCaretPosition(editor.getCaretPosition() - 1); } } catch (Exception ex) { LOG.warn("action failed", ex); } } public void setDocument(Document doc) { this.document = (HTMLDocument) doc; initEditor(); } public void initEditor() { editor.setDocument(document); //undo = new UndoManager(); resetUndoManager(); document.addUndoableEditListener(undoHandler); editor.setCaretPosition(0); } public boolean isDocumentChanged() { return undo.canUndo(); } public void setStyleSheet(Reader r, java.net.URL url) { StyleSheet css = new StyleSheet(); try { css.loadRules(r, url); } catch (Exception ex) { LOG.warn("action failed", ex); } editorKit.setStyleSheet(css); } void doFind() { FindDialog dlg = new FindDialog(); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getSize(); //dlg.setSize(400, 300); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); if (editor.getSelectedText() != null) { dlg.txtSearch.setText(editor.getSelectedText()); } else if (Context.get("LAST_SEARCHED_WORD") != null) { dlg.txtSearch.setText(Context.get("LAST_SEARCHED_WORD").toString()); } dlg.setVisible(true); if (dlg.CANCELLED) { return; } Context.put("LAST_SEARCHED_WORD", dlg.txtSearch.getText()); String repl = null; if (dlg.chkReplace.isSelected()) { repl = dlg.txtReplace.getText(); } Finder finder = new Finder( this, dlg.txtSearch.getText(), dlg.chkWholeWord.isSelected(), dlg.chkCaseSens.isSelected(), dlg.chkRegExp.isSelected(), repl); finder.start(); } }
package com.uguratar.countingtextview; import android.animation.TimeInterpolator; import android.animation.TypeEvaluator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.TextView; public class countingTextView extends TextView { private int startValue = 0; private int endValue = 0; private int duration = 1200; private String format = "%d"; private TimeInterpolator interpolator; public countingTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (isInEditMode()) { setText(getText()); } init(attrs, defStyle); } public countingTextView(Context context, AttributeSet attrs) { super(context, attrs); if (isInEditMode()) { setText(getText()); } init(attrs, 0); } public countingTextView(Context context) { this(context, null); init(null, 0); } /** * Initial method that sets default duration and default interpolator * @param attrs * @param defStyle */ private void init(AttributeSet attrs, int defStyle) { final TypedArray a = getContext().obtainStyledAttributes( attrs, R.styleable.countingTextView, defStyle, 0); duration = a.getInt( R.styleable.countingTextView_duration, 1200); interpolator = new AccelerateDecelerateInterpolator(); } /** * Animates from zero to current endValue, with duration * @param duration */ public void animateFromZerotoCurrentValue(Integer duration) { setDuration(duration); animateText(0, getEndValue()); } /** * Animates from zero to current endValue */ public void animateFromZerotoCurrentValue() { animateText(0, getEndValue()); } /** * Animates from zero to given endValue with given duration * @param endValue * @param duration */ public void animateFromZero(Integer endValue, Integer duration) { setDuration(duration); animateText(0, endValue); } /** * Animates from zero to given endValue * @param endValue */ public void animateFromZero(Integer endValue) { animateText(0, endValue); } /** * Animates from startValue to endValue with given duration * @param duration */ public void animateText(Integer duration) { setDuration(duration); animateText(getStartValue(), getEndValue()); } /** * Animates from startValue to endValue */ public void animateText() { animateText(getStartValue(), getEndValue()); } /** * Actual method that plays the animation with given values * @param startValue * @param endValue */ public void animateText(Integer startValue, Integer endValue) { setStartValue(startValue); setEndValue(endValue); ValueAnimator animator = ValueAnimator.ofInt(startValue, endValue); animator.setInterpolator(getInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { setText(String.format(getFormat(), animation.getAnimatedValue())); } }); animator.setEvaluator(new TypeEvaluator<Integer>() { public Integer evaluate(float fraction, Integer startValue, Integer endValue) { return Math.round(startValue + (endValue - startValue) * fraction); } }); animator.setDuration(getDuration()); animator.start(); } /** * Gets the startValue * @return */ public int getStartValue() { return startValue; } /** * Sets the startValue * @param startValue */ public void setStartValue(int startValue) { this.startValue = startValue; } /** * Gets the endValue * @return */ public int getEndValue() { return endValue; } /** * Sets the endValue * @param endValue */ public void setEndValue(int endValue) { this.endValue = endValue; } /** * Gets the duration * @return */ public int getDuration() { return duration; } /** * Sets the duration * @param duration */ public void setDuration(int duration) { this.duration = duration; } /** * Gets the format, default is %s * @return */ public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } /** * Gets the interpolator * @return */ public TimeInterpolator getInterpolator() { return interpolator; } public void setInterpolator(TimeInterpolator interpolator) { this.interpolator = interpolator; } }
package org.owasp.esapi.util; /** * Conversion to/from byte arrays to/from short, int, long. The assumption * is that they byte arrays are in network byte order (i.e., big-endian * ordered). * * @see org.owasp.esapi.crypto.CipherTextSerializer * @author kevin.w.wall@gmail.com */ public class ByteConversionUtil { ////////// Convert from short, int, long to byte array. ////////// /** * Returns a byte array containing 2 network byte ordered bytes representing * the given {@code short}. * * @param input An {@code short} to convert to a byte array. * @return A byte array representation of an {@code short} in network byte * order (i.e., big-endian order). */ public static byte[] fromShort(short input) { byte[] output = new byte[2]; output[0] = (byte) (input >> 8); output[1] = (byte) input; return output; } /** * Returns a byte array containing 4 network byte-ordered bytes representing the * given {@code int}. * * @param input An {@code int} to convert to a byte array. * @return A byte array representation of an {@code int} in network byte order * (i.e., big-endian order). */ public static byte[] fromInt(int input) { byte[] output = new byte[4]; output[0] = (byte) (input >> 24); output[1] = (byte) (input >> 16); output[2] = (byte) (input >> 8); output[3] = (byte) input; return output; } /** * Returns a byte array containing 8 network byte-ordered bytes representing * the given {@code long}. * * @param input The {@code long} to convert to a {@code byte} array. * @return A byte array representation of a {@code long}. */ public static byte[] fromLong(long input) { byte[] output = new byte[8]; output[0] = (byte) (input >> 56); output[1] = (byte) (input >> 48); output[2] = (byte) (input >> 40); output[3] = (byte) (input >> 32); output[4] = (byte) (input >> 24); output[5] = (byte) (input >> 16); output[6] = (byte) (input >> 8); output[7] = (byte) input; return output; } ////////// Convert from byte array to short, int, long. ////////// /** * Converts a given byte array to an {@code short}. Bytes are expected in * network byte * order. * * @param input A network byte-ordered representation of an {@code short}. * @return The {@code short} value represented by the input array. */ public static short toShort(byte[] input) { assert input.length == 2 : "toShort(): Byte array length must be 2."; short output = 0; output = (short)(((input[0] & 0xff) << 8) | (input[1] & 0xff)); return output; } /** * Converts a given byte array to an {@code int}. Bytes are expected in * network byte order. * * @param input A network byte-ordered representation of an {@code int}. * @return The {@code int} value represented by the input array. */ public static int toInt(byte[] input) { assert input.length == 4 : "toInt(): Byte array length must be 4."; int output = 0; output = ((input[0] & 0xff) << 24) | ((input[1] & 0xff) << 16) | ((input[2] & 0xff) << 8) | (input[3] & 0xff); return output; } /** * Converts a given byte array to a {@code long}. Bytes are expected in * network byte * * @param input A network byte-ordered representation of a {@code long}. * @return The {@code long} value represented by the input array */ public static long toLong(byte[] input) { assert input.length == 8 : "toLong(): Byte array length must be 8."; long output = 0; output = ((long)(input[0] & 0xff) << 56); output |= ((long)(input[1] & 0xff) << 48); output |= ((long)(input[2] & 0xff) << 40); output |= ((long)(input[3] & 0xff) << 32); output |= ((long)(input[4] & 0xff) << 24); output |= ((long)(input[5] & 0xff) << 16); output |= ((long)(input[6] & 0xff) << 8); output |= (input[7] & 0xff); return output; } }
package org.robolectric.shadows; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.widget.ImageView; import org.robolectric.Robolectric; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; @Implements(ImageView.class) public class ShadowImageView extends ShadowView { private Drawable imageDrawable; private Bitmap imageBitmap; private ImageView.ScaleType scaleType; private Matrix matrix; private int imageLevel; @Implementation public void setImageBitmap(Bitmap imageBitmap) { setImageDrawable(new BitmapDrawable(imageBitmap)); this.imageBitmap = imageBitmap; } @Deprecated public Bitmap getImageBitmap() { return imageBitmap; } @Implementation public void setImageDrawable(Drawable drawable) { this.imageDrawable = drawable; } @Implementation public void setImageResource(int resId) { setImageDrawable(resId != 0 ? buildDrawable(resId) : null); } public int getImageResourceId() { ShadowDrawable shadow = Robolectric.shadowOf(imageDrawable); return shadow.getCreatedFromResId(); } @Implementation public ImageView.ScaleType getScaleType() { return scaleType; } @Implementation public void setScaleType(ImageView.ScaleType scaleType) { this.scaleType = scaleType; } @Implementation public Drawable getDrawable() { return imageDrawable; } @Implementation public void setImageMatrix(Matrix matrix) { this.matrix = new Matrix(matrix); } @Implementation public Matrix getImageMatrix() { return matrix; } @Implementation public void draw(Canvas canvas) { if (imageDrawable != null) { imageDrawable.draw(canvas); } } @Implementation public void setImageLevel(int imageLevel) { this.imageLevel = imageLevel; } /** * Non-Android accessor. * * @return the imageLevel set in {@code setImageLevel(int)} */ public int getImageLevel() { return imageLevel; } }
package org.spongepowered.api.entity; /** * Describes a type of entity. */ public interface EntityType { /** * Return the internal ID for the entity type. * * @return The id */ String getId(); /** * Returns the entity class for this type. * * @return The entity class for this type */ Class<? extends Entity> getEntityClass(); }
package de.msquadrat.blobwizard.resources; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.apache.commons.lang3.NotImplementedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.annotation.Timed; import de.msquadrat.blobwizard.BlobStoreManager; @Path("/blob/{store}/{path:.+}") public class BlobResource { private static final Logger LOGGER = LoggerFactory.getLogger(BlobResource.class); public BlobResource(BlobStoreManager storeManager) { } @Deprecated private Object notImplemented(String method, String store, String path) { LOGGER.info("{} on store <{}> via path <{}>", method, store, path); throw new NotImplementedException(method); } @PUT @Timed public void putBlob(@PathParam("store") String store, @PathParam("path") String path) { notImplemented("PUT", store, path); } @GET @Timed public Object getBlob(@PathParam("store") String store, @PathParam("path") String path) { return notImplemented("GET", store, path); } @DELETE @Timed public void deleteBlob(@PathParam("store") String store, @PathParam("path") String path) { notImplemented("DELETE", store, path); } }
package org.telegram.mtproto.secure; import org.telegram.mtproto.secure.aes.AESImplementation; import org.telegram.mtproto.secure.aes.DefaultAESImplementation; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; public class CryptoUtils { private static AESImplementation currentImplementation = new DefaultAESImplementation(); public static void setAESImplementation(AESImplementation implementation) { currentImplementation = implementation; } public static byte[] RSA(byte[] src, BigInteger key, BigInteger exponent) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(new RSAPublicKeySpec(key, exponent)); Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(src); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; } public static void AES256IGEDecryptBig(byte[] src, byte[] dest, int len, byte[] iv, byte[] key) { currentImplementation.AES256IGEDecrypt(src, dest, len, iv, key); } public static byte[] AES256IGEDecrypt(byte[] src, byte[] iv, byte[] key) { byte[] res = new byte[src.length]; currentImplementation.AES256IGEDecrypt(src, res, src.length, iv, key); return res; } public static void AES256IGEDecrypt(File src, File dest, byte[] iv, byte[] key) throws IOException { currentImplementation.AES256IGEDecrypt(src.getAbsolutePath(), dest.getAbsolutePath(), iv, key); } public static void AES256IGEEncrypt(File src, File dest, byte[] iv, byte[] key) throws IOException { currentImplementation.AES256IGEEncrypt(src.getAbsolutePath(), dest.getAbsolutePath(), iv, key); } public static byte[] AES256IGEEncrypt(byte[] src, byte[] iv, byte[] key) { byte[] res = new byte[src.length]; currentImplementation.AES256IGEEncrypt(src, res, src.length, iv, key); return res; } public static String MD5(byte[] src) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.reset(); crypt.update(src); return ToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static String MD5(RandomAccessFile randomAccessFile) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.reset(); byte[] block = new byte[8 * 1024]; for (int i = 0; i < randomAccessFile.length(); i += 8 * 1024) { int len = (int) Math.min(block.length, randomAccessFile.length() - i); randomAccessFile.readFully(block, 0, len); crypt.update(block, 0, len); } return ToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static byte[] MD5Raw(byte[] src) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.reset(); crypt.update(src); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static String ToHex(byte[] src) { String res = ""; for (int i = 0; i < src.length; i++) { res += String.format("%02X", src[i] & 0xFF); } return res.toLowerCase(); } public static byte[] SHA1(InputStream in) throws IOException { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); // Transfer bytes from in to out byte[] buf = new byte[4 * 1024]; int len; while ((len = in.read(buf)) > 0) { Thread.yield(); // out.write(buf, 0, len); crypt.update(buf, 0, len); } in.close(); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static byte[] SHA1(String fileName) throws IOException { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); FileInputStream in = new FileInputStream(fileName); // Transfer bytes from in to out byte[] buf = new byte[4 * 1024]; int len; while ((len = in.read(buf)) > 0) { Thread.yield(); // out.write(buf, 0, len); crypt.update(buf, 0, len); } in.close(); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static byte[] SHA1(byte[] src) { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(src); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static byte[] SHA1(byte[]... src1) { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); for (int i = 0; i < src1.length; i++) { crypt.update(src1[i]); } return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static boolean arrayEq(byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } public static byte[] concat(byte[]... v) { int len = 0; for (int i = 0; i < v.length; i++) { len += v[i].length; } byte[] res = new byte[len]; int offset = 0; for (int i = 0; i < v.length; i++) { System.arraycopy(v[i], 0, res, offset, v[i].length); offset += v[i].length; } return res; } public static byte[] substring(byte[] src, int start, int len) { byte[] res = new byte[len]; System.arraycopy(src, start, res, 0, len); return res; } public static byte[] align(byte[] src, int factor) { if (src.length % factor == 0) { return src; } int padding = factor - src.length % factor; return concat(src, Entropy.generateSeed(padding)); } public static byte[] alignKeyZero(byte[] src, int size) { if (src.length == size) { return src; } if (src.length > size) { return substring(src, src.length - size, size); } else { return concat(new byte[size - src.length], src); } } public static byte[] xor(byte[] a, byte[] b) { byte[] res = new byte[a.length]; for (int i = 0; i < a.length; i++) { res[i] = (byte) (a[i] ^ b[i]); } return res; } public static BigInteger loadBigInt(byte[] data) { return new BigInteger(1, data); } public static byte[] fromBigInt(BigInteger val) { byte[] res = val.toByteArray(); if (res[0] == 0) { byte[] res2 = new byte[res.length - 1]; System.arraycopy(res, 1, res2, 0, res2.length); return res2; } else { return res; } } public static boolean isZero(byte[] src) { for (int i = 0; i < src.length; i++) { if (src[i] != 0) { return false; } } return true; } }
package fi.csc.microarray.client.dataimport; import java.io.File; import fi.csc.microarray.databeans.ContentType; /** * Class to represent a single item (file) which will be imported. All * necessary information of the file (input file, output file, action, content * type) are gathered together to this class. Import items are stored to * list in the ImportSession. * * * @author mkoski * */ public class ImportItem { /** * An enumeration to descripe the action which will be done to file * * @author mkoski * */ public enum Action { DIRECT("Import directly"), CUSTOM("Use Import tool"), IGNORE("Don't import"); private String name; private Action(String name){ this.name = name; } @Override public String toString(){ return name; } } private File input; private File output; private Action action; private ContentType type; /** * Creates a new import item from file. By default the output filename * is same as input filename. * * @param input Input file */ public ImportItem(File input) { this.input = input; // Default output name is same as input name this.output = input.getAbsoluteFile(); } public File getInput(){ return input; } public File getOutput() { return output; } public Action getAction() { return action; } public void setFilename(String output) { this.output = new File(this.output.getParentFile().getPath() + File.separator + output); } public ContentType getType() { return type; } public void setType(ContentType type) { this.type = type; } public void setAction(Action action){ this.action = action; } public String toString(){ return "ImportItem [input: " + input.getName() + ", output: " + output.getName() + ", type: " + type.getType() + ", action: " + action.toString(); } }
package pw.amel.civspell.builtin; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import pw.amel.civspell.spell.CastData; import pw.amel.civspell.spell.Effect; import java.util.HashSet; import java.util.Set; import java.util.UUID; public class CooldownEffect implements Effect { public CooldownEffect(ConfigurationSection config) { double cooldownMinutes = config.getDouble("cooldownMinutes", 0); double cooldownSeconds = config.getDouble("cooldownSeconds", 0); double cooldownTicks = config.getDouble("cooldownTicks", 0); this.cooldownTicks = (int) (cooldownTicks + (cooldownMinutes * 60 * 20) + (cooldownSeconds * 20)); isFancy = config.getBoolean("fancy", true); boolean chatNotificationSet = config.isSet("chatNotification"); if (chatNotificationSet) chatNotification = config.getBoolean("chatNotification"); else chatNotification = this.cooldownTicks >= 30 * 20; } private int cooldownTicks; private boolean isFancy; private boolean chatNotification; private Set<UUID> onCooldown = new HashSet<>(); @Override public void cast(CastData castData) { UUID playerUUID = castData.player.getUniqueId(); if (onCooldown.contains(playerUUID)) { castData.returnCast(); return; } if (isFancy) { BukkitRunnable runnable = new BukkitRunnable() { long progressed = -5; @Override public void run() { progressed += 5; if (progressed > cooldownTicks) { castData.main.getServer().getScheduler().runTask(castData.main, this::cancel); return; } Player player = castData.getNewPlayer(); if (player == null) return; if (!player.getInventory().getItemInMainHand().isSimilar(castData.triggerItem) && !player.getInventory().getItemInOffHand().isSimilar(castData.triggerItem)) return; final int BAR_LENGTH = 60; // generate progress bar float percentComplete = progressed / (float) cooldownTicks; int numberOfColons = (int) (percentComplete * BAR_LENGTH); numberOfColons++; // fix bar never filling up 100% int numberOfSpaces = BAR_LENGTH - numberOfColons; StringBuilder str = new StringBuilder(); for (int i = 0; i < numberOfColons; i++) { str.append("|"); } StringBuilder str2 = new StringBuilder(); for (int i = 0; i < numberOfSpaces; i++) { str2.append("|"); } TextComponent progressBar = new TextComponent("["); TextComponent midPart = new TextComponent(str.toString()); midPart.setColor(ChatColor.AQUA); progressBar.addExtra(midPart); TextComponent spacesPart = new TextComponent(str2.toString()); spacesPart.setColor(ChatColor.GRAY); midPart.addExtra(spacesPart); TextComponent endPart = new TextComponent("]"); endPart.setColor(ChatColor.WHITE); spacesPart.addExtra(endPart); player.spigot().sendMessage(ChatMessageType.ACTION_BAR, progressBar); } }; runnable.runTaskTimer(castData.main, 0, 5); castData.addReturnHook(runnable::cancel); } onCooldown.add(playerUUID); castData.addReturnHook(() -> onCooldown.remove(playerUUID)); castData.main.getServer().getScheduler().runTaskLater(castData.main, () -> { onCooldown.remove(playerUUID); if (!castData.isAlreadyReturned() && chatNotification) castData.getNewPlayer().sendMessage(org.bukkit.ChatColor.BLUE + castData.spellName + org.bukkit.ChatColor.RESET + " is off cooldown"); }, cooldownTicks); } }
package fi.csc.microarray.messaging.message; import java.util.Iterator; import java.util.List; import javax.jms.JMSException; import javax.jms.MapMessage; import org.apache.log4j.Logger; import fi.csc.microarray.analyser.AnalysisDescription; import fi.csc.microarray.analyser.AnalysisDescription.ParameterDescription; /** * For sending jobs to back-end components. * * @author Taavi Hupponen, Aleksi Kallio * */ public class JobMessage extends PayloadMessage { public static interface ParameterSecurityPolicy { public boolean isValueValid(String value, ParameterDescription parameterDescription); } public static class ParameterValidityException extends Exception { public ParameterValidityException(String msg) { super(msg); } } private static final Logger logger = Logger.getLogger(JobMessage.class); private static final String KEY_JOB_ID = "jobID"; private static final String KEY_ANALYSIS_ID = "analysisID"; private String analysisId; private String jobId; /** * For reflection compatibility (newInstance). DO NOT REMOVE! */ public JobMessage() { super(); } public JobMessage(String jobId, String analysisId, List<String> parameters) { super(parameters); this.jobId = jobId; this.analysisId = analysisId; } @Override public void unmarshal(MapMessage from) throws JMSException { super.unmarshal(from); // load ids this.jobId = from.getString(KEY_JOB_ID); this.analysisId = from.getString(KEY_ANALYSIS_ID); logger.debug("Unmarshalled " + KEY_JOB_ID + " : " + jobId); logger.debug("Unmarshalled " + KEY_ANALYSIS_ID + " : " + analysisId); } /** * Construct a MapMessage that can be used to create a new JobMessage. */ @Override public void marshal(MapMessage mapMessage) throws JMSException { super.marshal(mapMessage); logger.debug("Marshalling: " + KEY_JOB_ID + " : " + this.jobId); logger.debug("Marshalling: " + KEY_ANALYSIS_ID + " : " + this.analysisId); // add ids mapMessage.setString(KEY_JOB_ID, this.jobId); mapMessage.setString(KEY_ANALYSIS_ID, this.analysisId); } /** * Returns identifier of the requested job. */ public String getAnalysisId() { return this.analysisId; } /** * @see #getAnalysisId() */ public void setAnalysisId(String id) { this.analysisId = id; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } /** * Gets parameters in the order they were inserted. * Parameters are given by the user and hence * safety policy is required to get access to them. * * @param securityPolicy security policy to check parameters against, cannot be null * @param description description of the analysis operation, cannot be null * * @throws ParameterValidityException if some parameter value fails check by security policy */ public List<String> getParameters(ParameterSecurityPolicy securityPolicy, AnalysisDescription description) throws ParameterValidityException { // Do argument checking first if (securityPolicy == null) { throw new IllegalArgumentException("security policy cannot be null"); } if (description == null) { throw new IllegalArgumentException("analysis description cannot be null"); } // Count parameter descriptions int parameterDescriptionCount = 0; for (Iterator<ParameterDescription> iterator = description.getParameters().iterator(); iterator.hasNext(); iterator.next()) { parameterDescriptionCount++; } // Get the actual values List<String> parameters = super.getParameters(); // Check that description and values match if (parameterDescriptionCount != parameters.size()) { throw new IllegalArgumentException("number of parameter descriptions does not match the number of parameter values"); } // Validate parameters Iterator<ParameterDescription> descriptionIterator = description.getParameters().iterator(); for (String parameter : parameters) { ParameterDescription parameterDescription = descriptionIterator.next(); if (!securityPolicy.isValueValid(parameter, parameterDescription)) { throw new ParameterValidityException("illegal value for parameter " + parameterDescription.getName() + ": " + parameter); } } // Everything was ok, return the parameters return parameters; } }
package seedu.address.logic.commands; import java.util.HashSet; import java.util.Set; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.task.Deadline; import seedu.address.model.task.Description; import seedu.address.model.task.Name; import seedu.address.model.task.IdentificationNumber; import seedu.address.model.task.Task; import seedu.address.model.task.TaskList; import seedu.address.model.tag.Tag; import seedu.address.model.tag.UniqueTagList; /** * Adds a task to the address book. */ public class AddCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to the task manager. " + "Parameters: NAME dl/DEADLINE ds/DESCRIPTION id/IDENTIFICATION NUMBER [t/TAG]....\n" + "Example: " + COMMAND_WORD + " John Doe dl/11/01/2017 ds/buy eggs id/311 t/lunch t/no eggs"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_PERSON = "This task already exists in the address book"; private final Task toAdd; public AddCommand(String name, String deadline, String description, String id, Set<String> tags) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } this.toAdd = new Task( new Name(name), new Deadline(deadline), new Description(description), new IdentificationNumber(id), new UniqueTagList(tagSet) ); } @Override public CommandResult execute() throws CommandException { assert model != null; model.addTask(toAdd); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd)); } }
package info.iconmaster.typhon.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.misc.ParseCancellationException; import info.iconmaster.typhon.TyphonInput; import info.iconmaster.typhon.antlr.TyphonBaseVisitor; import info.iconmaster.typhon.antlr.TyphonLexer; import info.iconmaster.typhon.antlr.TyphonParser; import info.iconmaster.typhon.antlr.TyphonParser.AnnotationContext; import info.iconmaster.typhon.antlr.TyphonParser.ArgDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.ClassDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.ConstructorDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.ConstructorParamContext; import info.iconmaster.typhon.antlr.TyphonParser.ConstructorParamThisContext; import info.iconmaster.typhon.antlr.TyphonParser.ConstructorParamTypedContext; import info.iconmaster.typhon.antlr.TyphonParser.DeclContext; import info.iconmaster.typhon.antlr.TyphonParser.EnumDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.EnumValueDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.FieldDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.GlobalAnnotDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.GlobalAnnotationContext; import info.iconmaster.typhon.antlr.TyphonParser.ImportDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.MethodDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.MultiTypesContext; import info.iconmaster.typhon.antlr.TyphonParser.PackageDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.ParamDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.ParamNameContext; import info.iconmaster.typhon.antlr.TyphonParser.RootContext; import info.iconmaster.typhon.antlr.TyphonParser.SimplePackageDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.SingleTypesContext; import info.iconmaster.typhon.antlr.TyphonParser.StaticInitDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.TemplateDeclContext; import info.iconmaster.typhon.antlr.TyphonParser.TypeContext; import info.iconmaster.typhon.antlr.TyphonParser.TypesContext; import info.iconmaster.typhon.antlr.TyphonParser.VoidTypesContext; import info.iconmaster.typhon.errors.SyntaxError; import info.iconmaster.typhon.model.Constructor.ConstructorParameter; import info.iconmaster.typhon.model.Import.PackageImport; import info.iconmaster.typhon.model.Import.RawImport; import info.iconmaster.typhon.plugins.PluginLoader; import info.iconmaster.typhon.plugins.TyphonPlugin; import info.iconmaster.typhon.types.EnumType; import info.iconmaster.typhon.types.EnumType.EnumChoice; import info.iconmaster.typhon.types.TemplateType; import info.iconmaster.typhon.types.UserType; import info.iconmaster.typhon.util.Box; import info.iconmaster.typhon.util.SourceInfo; /** * This class handles the translation of declarations into the respective language entities. * Use this as the first step for translating Typhon text into Typhon code. * * @author iconmaster * */ public class TyphonModelReader { private TyphonModelReader() {} /** * Reads a source file, and translates it into a Typhon package. * * @param tni * @param file * @return The package the source file encodes. * @throws IOException If the file cannot be read. */ public static Package parseFile(TyphonInput tni, File file) throws IOException { try { TyphonLexer lexer = new TyphonLexer(new ANTLRFileStream(file.getPath())); TyphonParser parser = new TyphonParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { SourceInfo source; if (offendingSymbol instanceof Token) { Token token = ((Token)offendingSymbol); source = new SourceInfo(token); } else { source = new SourceInfo(file.getPath(), -1, -1); } tni.errors.add(new SyntaxError(source, msg)); } }); RootContext root = parser.root(); Package p = new Package(new SourceInfo(root), null, tni.corePackage); p.setRawData(); return readPackage(p, root.tnDecls); } catch (ParseCancellationException e) { return new Package(new SourceInfo(file.getPath(), 0, (int) file.length()-1), null, tni.corePackage); } } /** * Reads a source string, and translates it into a Typhon package. * * @param tni * @param input * @return The package the input encodes. */ public static Package parseString(TyphonInput tni, String input) { TyphonLexer lexer = new TyphonLexer(new ANTLRInputStream(input)); TyphonParser parser = new TyphonParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { SourceInfo source; if (offendingSymbol instanceof Token) { Token token = ((Token)offendingSymbol); source = new SourceInfo(token); } else { source = new SourceInfo(-1, -1); } tni.errors.add(new SyntaxError(source, msg)); } }); try { Package p = new Package(new SourceInfo(0, input.length()-1), null, tni.corePackage); p.setRawData(); return readPackage(p, parser.root().tnDecls); } catch (ParseCancellationException e) { return new Package(new SourceInfo(0, input.length()-1), null, tni.corePackage); } } /** * Adds declarations to a Typhon package based on ANTLR input. * * @param result The package we want to populate with declarations. * @param decls The ANTLR rules for the declarations in this package. * @return The package representing the ANTLR rules given as input. */ public static Package readPackage(Package result, List<DeclContext> decls) { Box<Integer> declIndex = new Box<>(0); Box<Boolean> doneVisiting = new Box<>(false); ArrayList<Annotation> globalAnnots = new ArrayList<>(); TyphonBaseVisitor<Void> visitor = new TyphonBaseVisitor<Void>() { @Override public Void visitPackageDecl(PackageDeclContext decl) { List<String> names = decl.tnName.tnName.stream().map((name)->name.getText()).collect(Collectors.toCollection(()->new ArrayList<>())); String lastName = names.remove(names.size()-1); Package base = result; for (String name : names) { base = readPackage(new Package(new SourceInfo(decl), name, base), new ArrayList<>()); base.setRawData(); } Package p = readPackage(new Package(new SourceInfo(decl), lastName, base), decl.tnDecls); p.setRawData(); p.getAnnots().addAll(readAnnots(result.tni, decl.tnAnnots)); p.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitSimplePackageDecl(SimplePackageDeclContext decl) { List<String> names = decl.tnName.tnName.stream().map((name)->name.getText()).collect(Collectors.toCollection(()->new ArrayList<>())); String lastName = names.remove(names.size()-1); Package base = result; for (String name : names) { base = readPackage(new Package(new SourceInfo(decl), name, base), new ArrayList<>()); base.setRawData(); } List<DeclContext> remainingDecls = decls.subList(declIndex.data+1, decls.size()); Package p = readPackage(new Package(new SourceInfo(decl), lastName, base), remainingDecls); p.setRawData(); p.getAnnots().addAll(readAnnots(result.tni, decl.tnAnnots)); p.getAnnots().addAll(globalAnnots); doneVisiting.data = true; return null; } @Override public Void visitMethodDecl(MethodDeclContext ctx) { Function f = readFunction(result.tni, ctx); result.addFunction(f); f.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitFieldDecl(FieldDeclContext ctx) { for (Field f : readField(result.tni, ctx)) { result.addField(f); f.getAnnots().addAll(globalAnnots); } return null; } @Override public Void visitImportDecl(ImportDeclContext ctx) { Import i = readImport(result.tni, ctx); result.addImport(i); i.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitStaticInitDecl(StaticInitDeclContext ctx) { StaticInitBlock b = readStaticInitBlock(result.tni, ctx); result.addStaticInitBlock(b); b.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitClassDecl(ClassDeclContext ctx) { UserType t = readClass(result.tni, ctx); result.addType(t); t.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitConstructorDecl(ConstructorDeclContext ctx) { Constructor f = readConstructor(result.tni, ctx); result.addFunction(f); f.getAnnots().addAll(globalAnnots); return null; } @Override public Void visitGlobalAnnotDecl(GlobalAnnotDeclContext ctx) { Annotation a = readGlobalAnnot(result.tni, ctx.tnGlobalAnnot); // TODO: Should global annotations be annotatable? If so, how can normal annotations be annotated? // a.getAnnots().addAll(readAnnots(result.tni, ctx.tnAnnots)); globalAnnots.add(a); return null; } @Override public Void visitEnumDecl(EnumDeclContext ctx) { EnumType t = readEnum(result.tni, ctx); result.addType(t); t.getAnnots().addAll(globalAnnots); return null; } }; for (DeclContext decl : decls) { visitor.visit(decl); if (doneVisiting.data) break; declIndex.data++; } return result; } /** * Translates ANTLR rules for annotations into Typhon annotations. * * @param tni * @param rules The list of annotation rules. Cannot be null. * @return A list representing the ANTLR annotations given as input. */ public static List<Annotation> readAnnots(TyphonInput tni, List<AnnotationContext> rules) { return rules.stream().map((rule)->{ Annotation annot = new Annotation(tni, new SourceInfo(rule)); annot.setRawData(rule.tnName); if (rule.tnArgs != null) annot.getArgs().addAll(readArgs(tni, rule.tnArgs.tnArgs)); return annot; }).collect(Collectors.toCollection(()->new ArrayList<>())); } /** * Translates ANTLR rules for global annotations into Typhon annotations. * * @param tni * @param rule The annotation rule. Cannot be null. * @return The annotation representing the ANTLR rule given as input. */ public static Annotation readGlobalAnnot(TyphonInput tni, GlobalAnnotationContext rule) { Annotation annot = new Annotation(tni, new SourceInfo(rule)); annot.setRawData(rule.tnName); if (rule.tnArgs != null) for (ArgDeclContext argRule : rule.tnArgs.tnArgs) { Argument arg = new Argument(tni, new SourceInfo(argRule)); if (argRule.tnKey != null) arg.setLabel(argRule.tnKey.getText()); arg.setRawData(argRule.tnValue); annot.getArgs().add(arg); } return annot; } /** * Translates an ANTLR rule for a function into a Typhon function. * * @param tni * @param rule The method declaration. Cannot be null. * @return The function the input represents. */ public static Function readFunction(TyphonInput tni, MethodDeclContext rule) { Function f = new Function(tni, new SourceInfo(rule), rule.tnName.getText()); if (rule.tnArgs != null) { f.getParams().addAll(readParams(tni, rule.tnArgs.tnArgs)); } if (rule.tnTemplate != null) { f.getTemplate().addAll(readTemplateParams(tni, rule.tnTemplate.tnArgs)); } if (rule.tnExprForm == null && rule.tnStubForm == null) { f.setRawData(readTypes(rule.tnRetType), Function.Form.BLOCK, rule.tnBlockForm); } else if (rule.tnExprForm != null) { f.setRawData(readTypes(rule.tnRetType), Function.Form.EXPR, rule.tnExprForm.tnExprs); } else { f.setRawData(readTypes(rule.tnRetType), Function.Form.STUB, null); } f.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return f; } /** * Translates an ANTLR rule for a field into Typhon fields. * * @param tni * @param rule The field declaration. Cannot be null. * @return The fields the input represents. */ public static List<Field> readField(TyphonInput tni, FieldDeclContext rule) { ArrayList<Field> a = new ArrayList<>(); int i = 0; for (ParamNameContext name : rule.tnNames) { Field f = new Field(tni, new SourceInfo(rule), name.tnName.getText()); if (i < rule.tnValues.size()) { f.setRawData(rule.tnType, rule.tnValues.get(i)); } else { f.setRawData(rule.tnType, null); } f.getAnnots().addAll(readAnnots(tni, name.tnAnnots)); a.add(f); i++; } return a; } public static Import readImport(TyphonInput tni, ImportDeclContext rule) { if (rule.tnRawName == null) { PackageImport i = new PackageImport(tni, new SourceInfo(rule)); i.getPackageName().addAll(rule.tnName.tnName.stream().map((name)->name.getText()).collect(Collectors.toList())); if (rule.tnAlias != null) i.getAliasName().addAll(rule.tnAlias.tnName.stream().map((name)->name.getText()).collect(Collectors.toList())); i.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return i; } else { RawImport i = new RawImport(tni, new SourceInfo(rule)); i.setImportData(rule.tnRawName.getText().substring(1, rule.tnRawName.getText().length()-1)); if (rule.tnAlias != null) i.getAliasName().addAll(rule.tnAlias.tnName.stream().map((name)->name.getText()).collect(Collectors.toList())); i.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return i; } } /** * Translates ANTLR rules for parameters into Typhon parameters. * * @param tni * @param rules The parameters. Cannot be null. * @return The list of parameters the input represents. */ public static List<Parameter> readParams(TyphonInput tni, List<ParamDeclContext> rules) { return rules.stream().map((rule)->{ Parameter p = new Parameter(tni, new SourceInfo(rule)); p.setName(rule.tnName.getText()); p.setRawData(rule.tnType, rule.tnDefaultValue); p.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); p.setRawData(); return p; }).collect(Collectors.toCollection(()->new ArrayList<>())); } /** * Translates ANTLR rules for template parameters into Typhon template parameters. * * @param tni * @param rules The parameters. Cannot be null. * @return The list of parameters the input represents. */ public static List<TemplateType> readTemplateParams(TyphonInput tni, List<TemplateDeclContext> rules) { return rules.stream().map((rule)->{ TemplateType t = new TemplateType(tni, new SourceInfo(rule), rule.tnName.getText()); t.setRawData(rule.tnBaseType, rule.tnDefaultType); t.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return t; }).collect(Collectors.toCollection(()->new ArrayList<>())); } /** * Translates ANTLR rules for arguments into Typhon arguments. * * @param tni * @param rules The arguments. Cannot be null. * @return The list of arguments the input represents. */ public static List<Argument> readArgs(TyphonInput tni, List<ArgDeclContext> rules) { return rules.stream().map((rule)->{ Argument arg = new Argument(tni, new SourceInfo(rule)); if (rule.tnKey != null) arg.setLabel(rule.tnKey.getText()); arg.setRawData(rule.tnValue); return arg; }).collect(Collectors.toCollection(()->new ArrayList<>())); } /** * Parses a return type specification. * Used to ensure 'void' is equivalent to '()', among other things. * * @param rule The return types. * @return The list of actual return types. */ public static List<TypeContext> readTypes(TypesContext rule) { if (rule instanceof SingleTypesContext) { return Arrays.asList(((SingleTypesContext)rule).tnType); } else if (rule instanceof MultiTypesContext) { return ((MultiTypesContext)rule).tnTypes; } else if (rule instanceof VoidTypesContext) { return new ArrayList<>(); } else { throw new IllegalArgumentException("Unknown subclass of TypesContext"); } } /** * Translates ANTLR rules for a static init block into a Typhon static init block. * * @param tni * @param rule The block. Cannot be null. * @return The block the input represents. */ public static StaticInitBlock readStaticInitBlock(TyphonInput tni, StaticInitDeclContext rule) { StaticInitBlock block = new StaticInitBlock(tni, new SourceInfo(rule)); block.setRawData(rule.tnBlock); block.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return block; } /** * Translates ANTLR rules for a class into a Typhon type. * * @param tni * @param rule The class declaration. Cannot be null. * @return The type. */ public static UserType readClass(TyphonInput tni, ClassDeclContext rule) { UserType t = new UserType(tni, new SourceInfo(rule), rule.tnName.getText()); if (rule.tnTemplate != null) t.getTemplates().addAll(readTemplateParams(tni, rule.tnTemplate.tnArgs)); t.setRawData(rule.tnExtends); t.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); readPackage(t.getTypePackage(), rule.tnDecls); if (!t.getTypePackage().getFunctions().stream().anyMatch(f->f instanceof Constructor && f.getFieldOf() == t)) { // add a default constructor Constructor c = new Constructor(tni); c.markAsLibrary(); t.getTypePackage().addFunction(c); PluginLoader.runHook(TyphonPlugin.OnInitDefaultConstructor.class, c); } return t; } /** * Translates ANTLR rules for a constructor into a Typhon function. * * @param tni * @param rule The constructor. Cannot be null. * @return The function. */ public static Constructor readConstructor(TyphonInput tni, ConstructorDeclContext rule) { Constructor f = new Constructor(tni, new SourceInfo(rule)); for (ConstructorParamContext argRule : rule.tnArgs) { ConstructorParameter p = new ConstructorParameter(tni, new SourceInfo(argRule)); if (argRule instanceof ConstructorParamThisContext) { p.isField(true); p.setName(((ConstructorParamThisContext)argRule).tnName.getText()); p.getAnnots().addAll(readAnnots(tni, ((ConstructorParamThisContext)argRule).tnAnnots)); p.setRawData(null, ((ConstructorParamThisContext)argRule).tnDefaultValue); } else if (argRule instanceof ConstructorParamTypedContext) { p.isField(false); p.setName(((ConstructorParamTypedContext)argRule).tnName.getText()); p.getAnnots().addAll(readAnnots(tni, ((ConstructorParamTypedContext)argRule).tnAnnots)); p.setRawData(((ConstructorParamTypedContext)argRule).tnType, ((ConstructorParamTypedContext)argRule).tnDefaultValue); } else { throw new IllegalArgumentException("Unknown subclass of ConstructorParamContext"); } f.getConstParams().add(p); } if (rule.tnExprForm == null && rule.tnStubForm == null) { f.setRawData(Function.Form.BLOCK, rule.tnBlockForm); } else if (rule.tnExprForm != null) { f.setRawData(Function.Form.EXPR, rule.tnExprForm.tnExprs); } else { f.setRawData(Function.Form.STUB, null); } f.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); return f; } /** * Translates ANTLR rules for an enum class into a Typhon type. * * @param tni * @param rule The enum class declaration. Cannot be null. * @return The type. */ public static EnumType readEnum(TyphonInput tni, EnumDeclContext rule) { EnumType t = new EnumType(tni, new SourceInfo(rule), rule.tnName.getText()); t.setRawData(rule.tnExtends); t.getAnnots().addAll(readAnnots(tni, rule.tnAnnots)); readPackage(t.getTypePackage(), rule.tnDecls); for (EnumValueDeclContext choiceRule : rule.tnValues) { EnumChoice choice = new EnumChoice(tni, new SourceInfo(choiceRule), choiceRule.tnName.getText(), t); if (choiceRule.tnArgs != null) choice.getArgs().addAll(readArgs(tni, choiceRule.tnArgs.tnArgs)); choice.getAnnots().addAll(readAnnots(tni, choiceRule.tnAnnots)); t.getChoices().add(choice); } return t; } }
package seedu.malitio.logic.commands; import seedu.malitio.commons.exceptions.IllegalValueException; import seedu.malitio.model.tag.Tag; import seedu.malitio.model.tag.UniqueTagList; import seedu.malitio.model.task.*; import java.util.HashSet; import java.util.Set; /** * Adds a task to Malitio. */ public class AddCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to Malitio.\n" + "Parameters: NAME [by DEADLINE] [start STARTTIME end ENDTIME] [t/TAG]...\n" + "Example: " + COMMAND_WORD + " Pay John $100 by 10112016 2359 t/oweMoney"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Malitio"; private final Task toAdd; public AddCommand(String name, Set<String> tags) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } this.toAdd = new Task( new Name(name), new UniqueTagList(tagSet) ); } public AddCommand(String name, String date, Set<String> tags) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } this.toAdd = new Task( new Name(name), new DateTime(date), new UniqueTagList(tagSet) ); } public AddCommand(String name, String start, String end, Set<String> tags) throws IllegalValueException { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } // check if start < end this.toAdd = new Task( new Name(name), new DateTime(start), new DateTime(end), new UniqueTagList(tagSet) ); } @Override public CommandResult execute() { assert model != null; try { model.addTask(toAdd); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd)); } catch (UniqueTaskList.DuplicateTaskException e) { return new CommandResult(MESSAGE_DUPLICATE_TASK); } } }
package info.magnolia.image.tagging; import info.magnolia.context.Context; import info.magnolia.jcr.util.NodeUtil; import info.magnolia.module.ModuleLifecycle; import info.magnolia.module.ModuleLifecycleContext; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.commons.predicate.Predicate; import org.datavec.image.loader.NativeImageLoader; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.modelimport.keras.InvalidKerasConfigurationException; import org.deeplearning4j.nn.modelimport.keras.UnsupportedKerasConfigurationException; import org.deeplearning4j.zoo.ZooModel; import org.deeplearning4j.zoo.model.ResNet50; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.api.preprocessor.VGG16ImagePreProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; /** * Magnolia module which queries {@link #DAM_WORKSPACE dam workspace} and tags images if they are not tagged already. */ public class ImageTaggingModule implements ModuleLifecycle { private static final Logger log = LoggerFactory.getLogger(ImageTaggingModule.class); private static final String IMAGE_TAGS_PROPERTY = "imageTags"; private static final String DAM_WORKSPACE = "dam"; private final Context context; private final VGG16ImagePreProcessor scaler; private final ComputationGraph computationGraph; private final ImageNetLabels imageNetLabels; @Inject public ImageTaggingModule(Context context) throws IOException, InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { this.context = context; ZooModel zooModel = new ResNet50(); this.computationGraph = (ComputationGraph) zooModel.initPretrained(); this.scaler = new VGG16ImagePreProcessor(); this.imageNetLabels = new ImageNetLabels(); } private List<ImageNetLabels.Result> process(Binary node) throws IOException, RepositoryException { INDArray indArray = new NativeImageLoader(224, 224, 3).asMatrix(node.getStream()); scaler.transform(indArray); INDArray[] output = computationGraph.output(false, indArray); return imageNetLabels.decodePredictions(output[0]); } @Override public void start(ModuleLifecycleContext moduleLifecycleContext) { try { //TODO: Might want to use some threading here Session damSession = context.getJCRSession(DAM_WORKSPACE); List<Node> allImagesWithoutPresentTag = Lists.newArrayList(NodeUtil.collectAllChildren(damSession.getRootNode(), notTaggedImagesPredicate())); for (Node node : allImagesWithoutPresentTag) { try { List<ImageNetLabels.Result> results = process(node.getNode("jcr:content").getProperty("jcr:data").getBinary()); List<String> tags = results.stream().filter(result -> result.getProbability() > 30).map(ImageNetLabels.Result::getPrediction).collect(Collectors.toList()); node.setProperty(IMAGE_TAGS_PROPERTY, StringUtils.join(tags)); node.getSession().save(); } catch (Exception e) { log.error("An error occurred while tagging images", e); } } } catch (Exception e) { log.error("An error occurred while tagging images", e); } } /** * A {@link Predicate} for finding not tagged images. */ private static Predicate notTaggedImagesPredicate() { return object -> { Node node = (Node) object; try { return !node.hasProperty(IMAGE_TAGS_PROPERTY) && node.getPrimaryNodeType().getName().equals("mgnl:asset"); } catch (RepositoryException e) { e.printStackTrace(); } return false; }; } @Override public void stop(ModuleLifecycleContext moduleLifecycleContext) { } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; import seedu.todo.commons.EphemeralDB; import seedu.todo.commons.exceptions.InvalidNaturalDateException; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.DateParser; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.models.CalendarItem; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * @@author A0093907W * * Controller to update a CalendarItem. */ public class UpdateController implements Controller { private static final String NAME = "Update"; private static final String DESCRIPTION = "Updates a task by listed index."; private static final String COMMAND_SYNTAX = "update <index> <task> by <deadline>"; private static final String MESSAGE_UPDATE_SUCCESS = "Item successfully updated!"; private static final String STRING_WHITESPACE = ""; private static final String UPDATE_EVENT_TEMPLATE = "update %s [name \"%s\"] [from \"%s\" to \"%s\"]"; private static final String UPDATE_TASK_TEMPLATE = "update %s [name \"%s\"] [by \"%s\"]"; private static final String START_TIME_FIELD = "<start time>"; private static final String END_TIME_FIELD = "<end time>"; private static final String DEADLINE_FIELD = "<deadline>"; private static final String NAME_FIELD = "<name>"; private static final String INDEX_FIELD = "<index>"; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { // TODO return (input.toLowerCase().startsWith("update")) ? 1 : 0; } /** * Get the token definitions for use with <code>tokenizer</code>.<br> * This method exists primarily because Java does not support HashMap * literals... * * @return tokenDefinitions */ private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"update"}); tokenDefinitions.put("name", new String[] {"name"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "before", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to" }); return tokenDefinitions; } @Override public void process(String input) throws ParseException { // TODO: Example of last minute work Map<String, String[]> parsedResult; parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); // Name String name = parseName(parsedResult); // Time String[] naturalDates = DateParser.extractDatePair(parsedResult); String naturalFrom = naturalDates[0]; String naturalTo = naturalDates[1]; // Record index Integer recordIndex = null; try { recordIndex = parseIndex(parsedResult); } catch (NumberFormatException e) { recordIndex = null; // Later then disambiguate } // Parse natural date using Natty. LocalDateTime dateFrom; LocalDateTime dateTo; try { dateFrom = naturalFrom == null ? null : DateParser.parseNatural(naturalFrom); dateTo = naturalTo == null ? null : DateParser.parseNatural(naturalTo); } catch (InvalidNaturalDateException e) { renderDisambiguation(true, recordIndex, name, naturalFrom, naturalTo); return; } // Retrieve record and check if task or event EphemeralDB edb = EphemeralDB.getInstance(); CalendarItem calendarItem = null; boolean isTask; try { calendarItem = edb.getCalendarItemsByDisplayedId(recordIndex); isTask = calendarItem.getClass() == Task.class; } catch (NullPointerException e) { // Assume task for disambiguation purposes since we can't tell renderDisambiguation(true, recordIndex, name, naturalFrom, naturalTo); return; } // Validate isTask, name and times. if (!validateParams(isTask, calendarItem, name, dateFrom, dateTo)) { renderDisambiguation(isTask, (int) recordIndex, name, naturalFrom, naturalTo); return; } // Update and persist task / event. TodoListDB db = TodoListDB.getInstance(); updateCalendarItem(db, calendarItem, isTask, name, dateFrom, dateTo); // Re-render Renderer.renderIndex(db, MESSAGE_UPDATE_SUCCESS); } /** * Extracts the record index from parsedResult. * * @param parsedResult * @return Integer index if parse was successful, null otherwise. */ private Integer parseIndex(Map<String, String[]> parsedResult) { String indexStr = null; if (parsedResult.get("default") != null && parsedResult.get("default")[1] != null) { indexStr = parsedResult.get("default")[1].trim(); return Integer.decode(indexStr); } else { return null; } } /** * Extracts the name to be updated from parsedResult. * * @param parsedResult * @return String name if found, null otherwise. */ private String parseName(Map<String, String[]> parsedResult) { if (parsedResult.get("name") != null && parsedResult.get("name")[1] != null) { return parsedResult.get("name")[1]; } return null; } /** * Updates and persists a CalendarItem to the DB. * * @param db * TodoListDB instance * @param record * Record to update * @param isTask * true if CalendarItem is a Task, false if Event * @param name * Display name of CalendarItem object * @param dateFrom * Due date for Task or start date for Event * @param dateTo * End date for Event */ private void updateCalendarItem(TodoListDB db, CalendarItem record, boolean isTask, String name, LocalDateTime dateFrom, LocalDateTime dateTo) { // Update name if not null if (name != null) { record.setName(name); } // Update time if (isTask) { Task task = (Task) record; if (dateFrom != null) { task.setDueDate(dateFrom); } } else { Event event = (Event) record; if (dateFrom != null) { event.setStartDate(dateFrom); } if (dateTo != null) { event.setEndDate(dateTo); } } // Persist db.save(); } /** * Validate that applying the update changes to the record will not result in an inconsistency. * * <ul> * <li>Fail if name is invalid</li> * <li>Fail if no update changes</li> * </ul> * * Tasks: * <ul> * <li>Fail if task has a dateTo</li> * </ul> * * Events: * <ul> * <li>Fail if event does not have both dateFrom and dateTo</li> * <li>Fail if event has a dateTo that is before dateFrom</li> * </ul> * * @param isTask * @param name * @param dateFrom * @param dateTo * @return */ private boolean validateParams(boolean isTask, CalendarItem record, String name, LocalDateTime dateFrom, LocalDateTime dateTo) { // TODO: Not enough sleep // We really need proper ActiveRecord validation and rollback, sigh... if (name == null && dateFrom == null && dateTo == null) { return false; } if (isTask) { // Fail if task has a dateTo if (dateTo != null) { return false; } } else { Event event = (Event) record; // Take union of existing fields and update params LocalDateTime newDateFrom = (dateFrom == null) ? event.getStartDate() : dateFrom; LocalDateTime newDateTo = (dateTo == null) ? event.getEndDate() : dateTo; if (newDateFrom == null || newDateTo == null) { return false; } if (newDateTo.isBefore(newDateFrom)) { return false; } } return true; } /** * Renders disambiguation with best-effort input matching to template. * * @param isTask * @param name * @param naturalFrom * @param naturalTo */ private void renderDisambiguation(boolean isTask, Integer recordIndex, String name, String naturalFrom, String naturalTo) { name = StringUtil.replaceEmpty(name, NAME_FIELD); String disambiguationString; String errorMessage = STRING_WHITESPACE; // TODO String indexStr = (recordIndex == null) ? INDEX_FIELD : recordIndex.toString(); if (isTask) { naturalFrom = StringUtil.replaceEmpty(naturalFrom, DEADLINE_FIELD); disambiguationString = String.format(UPDATE_TASK_TEMPLATE, indexStr, name, naturalFrom); } else { naturalFrom = StringUtil.replaceEmpty(naturalFrom, START_TIME_FIELD); naturalTo = StringUtil.replaceEmpty(naturalTo, END_TIME_FIELD); disambiguationString = String.format(UPDATE_EVENT_TEMPLATE, indexStr, name, naturalFrom, naturalTo); } // Show an error in the console Renderer.renderDisambiguation(disambiguationString, errorMessage); } }
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Map; /** * <p>Zips two characters.</p> * @see CharOperation * @author Innovimax * @version 1.0 */ public class DefaultCharZipping extends AbstractCharOperation { private final static String DEFAULT_ZIP_SEPARATOR = ""; /** * Constructor * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public DefaultCharZipping(Map<RuleParam, ParamValue> params) { super(params); } @Override public int[] process(int c1, int c2) throws MixException, ProcessException { if (c1 == -1 || c2 == -1) { throw new ProcessException(); } String sep = DEFAULT_ZIP_SEPARATOR; if (this.params.containsKey(RuleParam._ZIP_SEP)) { sep = this.params.get(RuleParam._ZIP_SEP).asString(); } int[] zip = new int[2 + sep.length()]; int index = 0; zip[index++] = c1; for (int n = 0; n < sep.length(); n++) { int cn = sep.codePointAt(n); zip[index++] = cn; } zip[index] = c2; return zip; } }
package stopheracleum.validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import stopheracleum.model.User; import stopheracleum.service.UserService; import java.util.Objects; import java.util.regex.Pattern; /** * Validator for sign up form * implements {@link Validator} interface. */ @Component public class SignUpValidator implements Validator { @Autowired private UserService userService; // regular expression for username validation private static final String USERNAME_PATTERN = "^[a-z0-9_-]{4,32}$"; @Override public boolean supports(Class<?> aClass) { return User.class.equals(aClass); } @Override public void validate(Object o, Errors errors) { User user = (User) o; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "Required"); if (user.getUsername().length() < 4 || user.getUsername().length() > 32) { errors.rejectValue("username", "Size.userForm.username"); } else if (userService.findByUsername(user.getUsername()) != null) { errors.rejectValue("username", "Duplicate.userForm.username"); } //validate with regular expression else if (!Pattern.compile(USERNAME_PATTERN).matcher(user.getUsername()).matches()) { errors.rejectValue("username", "Invalid.userForm.username"); } if (!user.getConfirmPassword().equals(user.getPassword())) { errors.rejectValue("confirmPassword", "Different.userForm.password"); } } }
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.ParamValue; import innovimax.mixthem.arguments.RuleParam; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * <p>Joins two or more lines on a common field.</p> * <p>Joining stops when no common field is found.</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public class DefaultLineJoining extends AbstractLineOperation { private final int col1; private final int col2; /** * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.operation.RuleParam * @see innovimax.mixthem.operation.ParamValue */ public DefaultLineJoining(final Map<RuleParam, ParamValue> params) { super(params); this.col1 = this.params.getOrDefault(RuleParam.JOIN_COL1, JoinOperation.DEFAULT_JOIN_COLUMN.getValue()).asInt(); this.col2 = this.params.getOrDefault(RuleParam.JOIN_COL2, JoinOperation.DEFAULT_JOIN_COLUMN.getValue()).asInt(); } @Override public void process(final String line1, final String line2, final LineResult result) throws MixException { final boolean firstPreserved = !result.readingRangeLine(0); final boolean secondPreserved = !result.readingRangeLine(1); result.reset(); if (line1 != null && line2 != null) { final List<String> list1 = Arrays.asList(line1.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.toString())); final List<String> list2 = Arrays.asList(line2.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.toString())); final String cell1 = list1.size() >= this.col1 ? list1.get(this.col1 - 1) : null; final String cell2 = list2.size() >= this.col2 ? list2.get(this.col2 - 1) : null; if (cell1 != null && cell2 != null) { final List<String> prevList1 = result.hasRangeLine(0) ? Arrays.asList(result.getRangeLine(0).split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString())) : Collections.emptyList(); final List<String> prevList2 = result.hasRangeLine(1) ? Arrays.asList(result.getRangeLine(1).split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString())) : Collections.emptyList(); final String prevCell1 = prevList1.size() >= this.col1 ? prevList1.get(this.col1 - 1) : null; final String prevCell2 = prevList2.size() >= this.col2 ? prevList2.get(this.col2 - 1) : null; /*System.out.println("LINE1=" + line1 + " / CELL1=" + cell1); System.out.println("LINE2=" + line2 + " / CELL2=" + cell2); System.out.println("PVLINE1=" + result.getRangeLine(0) + " / PVCELL1=" + prevCell1); System.out.println("PVLINE2=" + result.getRangeLine(1) + " / PVCELL2=" + prevCell2);*/ if (cell2.equals(prevCell2) && !secondPreserved) { //System.out.println("PREVIOUS 2"); joinLines(prevList1, list2, result); result.setRangeLineReading(0, false); result.keepRangeLine(0, line1); result.setRangeLine(1, line2); } else if (cell1.equals(prevCell1) && !firstPreserved) { //System.out.println("PREVIOUS 1"); joinLines(list1, prevList2, result); result.setRangeLineReading(1, false); result.setRangeLine(0, line1); result.keepRangeLine(1, line2); } else { switch (Integer.signum(cell1.compareTo(cell2))) { case 0: //System.out.println("EQUALS"); joinLines(list1, list2, result); break; case 1: //System.out.println("PRESERVE 1"); result.setRangeLineReading(0, false); break; default: //System.out.println("PRESERVE 2"); result.setRangeLineReading(1, false); } result.setRangeLine(0, line1); result.setRangeLine(1, line2); } } } } @Override public void process(final List<String> lineRange, final LineResult result) throws MixException { //process(lineRange.get(0), lineRange.get(1), result); System.out.println("LINES="+lineRange.toString()); final List<Boolean> linePreservationRange = getLinePreservationRange(result, lineRange.size()); System.out.println("PRESERVED="+linePreservationRange.toString()); result.reset(); if (linesJoinable(lineRange)) { final List<List<String>> lineCellsRange = getLineCellsRange(lineRange); if (linesComparable(lineCellsRange)) { System.out.println("> COMPARABLE"); final List<Integer> lineComparaisonRange = getLineComparaisonRange(lineCellsRange); System.out.println("COMPARAISON="+lineComparaisonRange.toString()); if (linesJoined(lineComparaisonRange)) { System.out.println("> JOINED"); //TODO } else { System.out.println("> NOT JOINED"); //TODO } } else { System.out.println("> NOT COMPARABLE"); } } } private List<Boolean> getLinePreservationRange(final LineResult result, final int size) { final List<Boolean> linePreservationRange = new ArrayList<Boolean>(); for (int i=0; i < size; i++) { linePreservationRange.add(Boolean.valueOf(!result.readingRangeLine(i))); } return linePreservationRange; } private boolean linesJoinable(final List<String> lineRange) { for (int i=0; i < lineRange.size(); i++) { if (lineRange.get(i) == null) { return false; } } return true; } private List<List<String>> getLineCellsRange(final List<String> lineRange) { final List<List<String>> lineCellsRange = new ArrayList<List<String>>(); for (String line : lineRange) { lineCellsRange.add(Arrays.asList(line.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString()))); } return lineCellsRange; } private boolean linesComparable(final List<List<String>> lineCellsRange) { for (List<String> lineCells : lineCellsRange) { //TODO: manage join index col from params if (lineCells.size() < this.col1) { return false; } } return true; } private List<Integer> getLineComparaisonRange(final List<List<String>> lineCellsRange) { final List<Integer> lineComparaisonRange = new ArrayList<Integer>(); String join = null; for (List<String> lineCells : lineCellsRange) { //TODO: manage join index col from params final String cell = lineCells.get(this.col1); if (join == null) { join = cell; } lineComparaisonRange.add(Integer.valueOf(Integer.signum(join.compareTo(cell)))); } return lineComparaisonRange; } private boolean linesJoined(final List<Integer> lineComparaisonRange) { for (Integer lineComparaison : lineComparaisonRange) { if (lineComparaison.intValue() != 0) { return false; } } return true; } private void joinLines(final List<String> list1, final List<String> list2, final LineResult result) { final String part1 = list1.get(this.col1 - 1); final String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString())); final String part3 = list2.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString())); result.setResult(part1 + CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString() + part2 + CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString() + part3); } }
package uk.ac.soton.ecs.comp3005; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.TextField; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.openimaj.content.slideshow.Slide; import org.openimaj.content.slideshow.SlideshowApplication; import org.openimaj.image.DisplayUtilities; import org.openimaj.image.DisplayUtilities.ImageComponent; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.ColourSpace; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.renderer.RenderHints; import org.openimaj.math.geometry.point.Point2dImpl; import org.openimaj.math.geometry.shape.Ellipse; import org.openimaj.math.geometry.shape.EllipseUtilities; import org.openimaj.math.geometry.transforms.TransformUtilities; import org.openimaj.math.statistics.distribution.CachingMultivariateGaussian; import Jama.Matrix; public class CovarianceDemo implements Slide { private Matrix covariance; private BufferedImage bimg; private MBFImage image; private ImageComponent imageComp; private JSlider xxSlider; private JSlider yySlider; private JSlider xySlider; private TextField xxField; private TextField xyField; private TextField yxField; private TextField yyField; @Override public Component getComponent(int width, int height) throws IOException { covariance = Matrix.identity(2, 2); final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height)); base.setLayout(new GridBagLayout()); image = new MBFImage(400, 400, ColourSpace.RGB); imageComp = new DisplayUtilities.ImageComponent(true); imageComp.setShowPixelColours(false); imageComp.setShowXYPosition(false); imageComp.setAllowZoom(false); imageComp.setAllowPanning(false); base.add(imageComp); xxSlider = new JSlider(); yySlider = new JSlider(); xySlider = new JSlider(); xySlider.setMinimum(-50); xySlider.setMaximum(50); xySlider.setValue(0); xxSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { setXX(); } }); yySlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { setYY(); } }); xySlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { setXY(); } }); final Font fnt = Font.decode("Monaco-48"); final GridBagConstraints c = new GridBagConstraints(); final JPanel matrix = new JPanel(new GridBagLayout()); c.gridwidth = 1; c.gridheight = 1; c.gridy = 0; c.gridx = 0; matrix.add(xxField = new TextField(5), c); xxField.setFont(fnt); xxField.setEditable(false); c.gridx = 1; matrix.add(xyField = new TextField(5), c); xyField.setFont(fnt); xyField.setEditable(false); c.gridy = 1; c.gridx = 0; matrix.add(yxField = new TextField(5), c); yxField.setFont(fnt); yxField.setEditable(false); c.gridx = 1; matrix.add(yyField = new TextField(5), c); yyField.setFont(fnt); yyField.setEditable(false); final JPanel controls = new JPanel(new GridBagLayout()); c.gridwidth = 1; c.gridheight = 1; c.gridy = 0; controls.add(matrix, c); c.gridy = 1; c.gridx = 0; controls.add(new JLabel("XX"), c); c.gridx = 1; controls.add(xxSlider, c); c.gridy = 2; c.gridx = 0; controls.add(new JLabel("YY"), c); c.gridx = 1; controls.add(yySlider, c); c.gridy = 3; c.gridx = 0; controls.add(new JLabel("XY"), c); c.gridx = 1; controls.add(xySlider, c); base.add(controls); updateImage(); return base; } private void updateImage() { xxField.setText(String.format("%2.2f", covariance.get(0, 0))); xyField.setText(String.format("%2.2f", covariance.get(0, 1))); yxField.setText(String.format("%2.2f", covariance.get(1, 0))); yyField.setText(String.format("%2.2f", covariance.get(1, 1))); image.fill(RGBColour.WHITE); image.drawLine(image.getWidth() / 2, 0, image.getWidth() / 2, image.getHeight(), 3, RGBColour.BLACK); image.drawLine(0, image.getHeight() / 2, image.getWidth(), image.getHeight() / 2, 3, RGBColour.BLACK); Ellipse e = EllipseUtilities.ellipseFromCovariance(image.getWidth() / 2, image.getHeight() / 2, covariance, 100); e = e.transformAffine(TransformUtilities.scaleMatrixAboutPoint(1, -1, image.getWidth() / 2, image.getHeight() / 2)); if (!Double.isNaN(e.getMajor()) && !Double.isNaN(e.getMinor()) && covariance.rank() == 2) { final Matrix mean = new Matrix(new double[][] { { image.getWidth() / 2, image.getHeight() / 2 } }); final CachingMultivariateGaussian gauss = new CachingMultivariateGaussian(mean, covariance); final Random rng = new Random(); for (int i = 0; i < 1000; i++) { final double[] sample = gauss.sample(rng); Point2dImpl pt = new Point2dImpl((float) sample[0], (float) sample[1]); pt = pt.transform(TransformUtilities.scaleMatrixAboutPoint(40, -40, image.getWidth() / 2, image.getHeight() / 2)); image.drawPoint(pt, RGBColour.BLUE, 3); } image.createRenderer(RenderHints.ANTI_ALIASED).drawShape(e, 3, RGBColour.RED); } this.imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg)); } protected void setYY() { covariance.set(1, 1, yySlider.getValue() / 100d); updateImage(); } protected void setXY() { covariance.set(1, 0, xySlider.getValue() / 100d); covariance.set(0, 1, xySlider.getValue() / 100d); updateImage(); } protected void setXX() { covariance.set(0, 0, xxSlider.getValue() / 100d); updateImage(); } @Override public void close() { // do nothing } public static void main(String[] args) throws IOException { new SlideshowApplication(new CovarianceDemo(), 1024, 768); } }
package io.github.deathcap.bukkit2sponge; import com.google.common.base.Throwables; import com.google.inject.Guice; import com.google.inject.Injector; import io.github.deathcap.bukkit2sponge.event.GraniteEventFactory; import io.github.deathcap.bukkit2sponge.guice.ShinyGuiceModule; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.spongepowered.api.event.state.ConstructionEvent; import org.spongepowered.api.event.state.PreInitializationEvent; import org.spongepowered.api.event.state.StateEvent; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; public class Bukkit2Sponge extends JavaPlugin { public static Bukkit2Sponge instance = null; public Injector getInjector() { return injector; } private Injector injector; private ShinyGame game; @Override public void onDisable() { getLogger().info("Goodbye world!"); } @Override public void onEnable() { Bukkit2Sponge.instance = this; PluginDescriptionFile pdfFile = this.getDescription(); getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" ); load(); } public Collection<URL> load() { Collection<URL> loadedPluginURLs = null; try { injector = Guice.createInjector(new ShinyGuiceModule()); /* CONSTRUCTION, LOAD_COMPLETE, PRE_INITIALIZATION, INITIALIZATION, POST_INITIALIZATION, SERVER_ABOUT_TO_START, SERVER_STARTING, SERVER_STARTED, SERVER_STOPPING, SERVER_STOPPED */ getLogger().info("Loading Bukkit2Sponge..."); this.game = injector.getInstance(ShinyGame.class); getLogger().info("Bukkit2Sponge " + this.game.getImplementationVersion() + " is starting..."); getLogger().info("SpongeAPI version: " + this.game.getApiVersion()); getLogger().info("Loading plugins..."); loadedPluginURLs = this.game.getPluginManager().loadPlugins(); postState(ConstructionEvent.class); getLogger().info("Initializing " + loadedPluginURLs.size() + " SpongeAPI plugins..."); postState(PreInitializationEvent.class); } catch (IOException e) { throw Throwables.propagate(e); } return loadedPluginURLs; } public ShinyGame getGame() { return this.game; } public void postState(Class<? extends StateEvent> type) { this.game.getEventManager().post(GraniteEventFactory.createStateEvent(type, this.game)); } // Sponge directories relative to our own Bukkit plugin data folder public File getPluginsDirectory() { return new File(this.getDataFolder(), "plugins"); } public File getConfigDirectory() { return new File(this.getDataFolder(), "config"); } }
package io.jenkins.plugins.analysis.core.model; import java.util.stream.Collectors; import io.jenkins.plugins.analysis.core.views.ResultAction; import static j2html.TagCreator.*; import j2html.tags.ContainerTag; import edu.hm.hafner.util.VisibleForTesting; /** * Summary message of a static analysis run. This message is shown as part of the 'summary.jelly' information of the * associated {@link ResultAction}. * <pre> * Tool Name: %d issues from %d analyses * - Results from analyses {%s, ... %s} * - %d new issues (since build %d) * - %d outstanding issues * - %d fixed issues * - No issues since build %d * - Quality gates: passed (Reference build %d) * </pre> * * @author Ullrich Hafner */ // FIXME: is the number of parsed reports available yet? public class Summary { private final StaticAnalysisLabelProvider labelProvider; private final AnalysisResult analysisRun; private final LabelProviderFactoryFacade facade; public Summary(final StaticAnalysisLabelProvider labelProvider, final AnalysisResult analysisRun) { this(labelProvider, analysisRun, new LabelProviderFactoryFacade()); } @VisibleForTesting Summary(final StaticAnalysisLabelProvider labelProvider, final AnalysisResult analysisRun, final LabelProviderFactoryFacade facade) { this.labelProvider = labelProvider; this.analysisRun = analysisRun; this.facade = facade; } /** * Creates the summary as HTML string. * * @return the summary */ public String create() { return div(labelProvider.getTitle(analysisRun, !analysisRun.getErrorMessages().isEmpty()), createDescription()) .withId(labelProvider.getId() + "-summary") .renderFormatted(); } private ContainerTag createDescription() { int currentBuild = analysisRun.getBuild().getNumber(); return ul() .condWith(analysisRun.getSizePerOrigin().size() > 1, li(getToolNames())) .condWith(analysisRun.getTotalSize() == 0 && currentBuild > analysisRun.getNoIssuesSinceBuild(), li(labelProvider.getNoIssuesSinceLabel(currentBuild, analysisRun.getNoIssuesSinceBuild()))) .condWith(analysisRun.getNewSize() > 0, li(labelProvider.getNewIssuesLabel(analysisRun.getNewSize()))) .condWith(analysisRun.getFixedSize() > 0, li(labelProvider.getFixedIssuesLabel(analysisRun.getFixedSize()))) .condWith(analysisRun.getQualityGate().isEnabled(), li(labelProvider.getQualityGateResult(analysisRun.getOverallResult(), analysisRun.getReferenceBuild()))); } private String getToolNames() { String tools = analysisRun.getSizePerOrigin() .keySet() .stream() .map((id) -> facade.get(id).getName()) .collect(Collectors.joining(", ")); return Messages.Tool_ParticipatingTools(tools); } static class LabelProviderFactoryFacade { public StaticAnalysisLabelProvider get(final String id) { return new LabelProviderFactory().create(id); } } }
package jp.gr.java_conf.dangan.util.lha; import java.io.InputStream; import java.io.OutputStream; import java.util.Hashtable; import java.util.Properties; final class CompressMethod { /** * LH0 "-lh0-" */ public static final String LH0 = "-lh0-"; /** * LH1 460 LZSS "-lh1-" */ public static final String LH1 = "-lh1-"; /** * LH2 8256 LZSS "-lh2-" LH1 LH5 */ public static final String LH2 = "-lh2-"; /** * LH3 8256 LZSS "-lh3-" LH1 LH5 */ public static final String LH3 = "-lh3-"; /** * LH4 4256 LZSS "-lh4-" 1990 LH5 */ public static final String LH4 = "-lh4-"; /** * LH5 8256 LZSS "-lh5-" LHA */ public static final String LH5 = "-lh5-"; /** * LH6 32256 LZSS "-lh6-" "-lh6-" LH7 LHA "-lh6-" LH7 10 */ public static final String LH6 = "-lh6-"; /** * LH7 64256 LZSS "-lh7-" 10 */ public static final String LH7 = "-lh7-"; /** * LHD "-lhd-" */ public static final String LHD = "-lhd-"; /** * LZS 217 LZSS "-lzs-" "-lzs-" LHA Larc */ public static final String LZS = "-lzs-"; /** * LZ4 "-lz4-" "-lz4-" LHA Larc */ public static final String LZ4 = "-lz4-"; /** * LZ5 417 LZSS "-lz5-" "-lz5-" LHA Larc */ public static final String LZ5 = "-lz5-"; private CompressMethod() {} // convert to LZSS parameter /** * * * @param method * @return */ public static int toDictionarySize(final String method) { if (LZS.equalsIgnoreCase(method)) { return 2048; } else if (LZ5.equalsIgnoreCase(method)) { return 4096; } else if (LH1.equalsIgnoreCase(method)) { return 4096; } else if (LH2.equalsIgnoreCase(method)) { return 8192; } else if (LH3.equalsIgnoreCase(method)) { return 8192; } else if (LH4.equalsIgnoreCase(method)) { return 4096; } else if (LH5.equalsIgnoreCase(method)) { return 8192; } else if (LH6.equalsIgnoreCase(method)) { return 32768; } else if (LH7.equalsIgnoreCase(method)) { return 65536; } else if (LZ4.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LH0.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LHD.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (method == null) { throw new NullPointerException("method"); } else { throw new IllegalArgumentException("Unknown compress method. " + method); } } /** * / * * @param method * @return / */ public static int toThreshold(final String method) { if (LZS.equalsIgnoreCase(method)) { return 2; } else if (LZ5.equalsIgnoreCase(method)) { return 3; } else if (LH1.equalsIgnoreCase(method)) { return 3; } else if (LH2.equalsIgnoreCase(method)) { return 3; } else if (LH3.equalsIgnoreCase(method)) { return 3; } else if (LH4.equalsIgnoreCase(method)) { return 3; } else if (LH5.equalsIgnoreCase(method)) { return 3; } else if (LH6.equalsIgnoreCase(method)) { return 3; } else if (LH7.equalsIgnoreCase(method)) { return 3; } else if (LZ4.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LH0.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LHD.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (method == null) { throw new NullPointerException("method"); } else { throw new IllegalArgumentException("Unknown compress method. " + method); } } /** * * * @param method * @return */ public static int toMaxMatch(final String method) { if (LZS.equalsIgnoreCase(method)) { return 17; } else if (LZ5.equalsIgnoreCase(method)) { return 18; } else if (LH1.equalsIgnoreCase(method)) { return 60; } else if (LH2.equalsIgnoreCase(method)) { return 256; } else if (LH3.equalsIgnoreCase(method)) { return 256; } else if (LH4.equalsIgnoreCase(method)) { return 256; } else if (LH5.equalsIgnoreCase(method)) { return 256; } else if (LH6.equalsIgnoreCase(method)) { return 256; } else if (LH7.equalsIgnoreCase(method)) { return 256; } else if (LZ4.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LH0.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (LHD.equalsIgnoreCase(method)) { throw new IllegalArgumentException(method + " means no compress."); } else if (method == null) { throw new NullPointerException("method"); } else { throw new IllegalArgumentException("Unknown compress method. " + method); } } // shared method /** * property method out * * @param out * @param method * @param property * @return method out */ public static OutputStream connectEncoder(final OutputStream out, final String method, final Properties property) { final String key = "lha." + getCore(method) + ".encoder"; String generator = property.getProperty(key); if (generator == null) { generator = LhaProperty.getProperty(key); } String packages = property.getProperty("lha.packages"); if (packages == null) { packages = LhaProperty.getProperty("lha.packages"); } final Hashtable<String, Object> substitute = new Hashtable<String, Object>(); substitute.put("out", out); return (OutputStream) LhaProperty.parse(generator, substitute, packages); } /** * property in method * * @param in * @param method * @param property * @return in method */ public static InputStream connectDecoder(final InputStream in, final String method, final Properties property, final long length) { final String key = "lha." + getCore(method) + ".decoder"; String generator = property.getProperty(key); if (generator == null) { generator = LhaProperty.getProperty(key); } String packages = property.getProperty("lha.packages"); if (packages == null) { packages = LhaProperty.getProperty("lha.packages"); } final Hashtable<String, Object> substitute = new Hashtable<String, Object>(); substitute.put("in", in); substitute.put("length", new Long(length)); return (InputStream) LhaProperty.parse(generator, substitute, packages); } // local method /** * '-' LhaProperty lha.???.encoder / lha.???.decoder ??? * * @param method * @return */ private static String getCore(final String method) { if (method.startsWith("-") && method.endsWith("-")) { return method.substring(1, method.lastIndexOf('-')).toLowerCase(); } throw new IllegalArgumentException(""); } }
package ml.duncte123.skybot.exceptions; /** * Made this for the memes * * @author Duncan "duncte123" Sterken */ public class VRCubeException extends SecurityException { private static final long serialVersionUID = -1411788219603361967L; public VRCubeException() { super(); } public VRCubeException(String message) { super(message); } public VRCubeException(String message, Throwable cause) { super(message, cause); } public VRCubeException(Throwable cause) { super(cause); } }
package name.vitaly.burlai; import com.atlassian.confluence.security.PermissionManager; import com.atlassian.confluence.user.AuthenticatedUserThreadLocal; import com.atlassian.confluence.user.ConfluenceUser; import com.atlassian.json.jsonorg.JSONObject; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Servlet providing REST-ful API to the storage * (Requires Confluence Admin privileges) * * url-prefix = /plugins/servlet/confluence-admin-notes/ * * GET [url-prefix]/ * shows the whole config * * GET [url-prefix]/plugins/ * shows config for plugins * * GET [url-prefix]/plugings/[key] * shows config for the specified plugin * * PUT [url-prefix]/plugings/[key] * from=[existing value or empty string ""] * to=[new value] * sets/updates config for the specified plugin * * DELETE [url-prefix]/plugings/[key]?value=[existing value] * removes config for the specified plugin */ public class ConfluenceAdminNotesServlet extends HttpServlet { private PermissionManager permissionManager; private ConfluenceAdminNotesStorage storage; private String urlPrefix; public ConfluenceAdminNotesServlet (PermissionManager pm, ConfluenceAdminNotesStorage storage) { this.permissionManager = pm; this.storage = storage; } public void doGet (HttpServletRequest req, HttpServletResponse resp) { urlPrefix = getInitParameter("url-prefix"); if( ! isConfluenceAdmin() ) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // url starts with prefix
package net.floodlightcontroller.flowcache; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Collections; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.INetMapStorage; import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowEntry; import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowPath; import net.floodlightcontroller.core.INetMapTopologyService.ITopoRouteService; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.flowcache.IFlowService; import net.floodlightcontroller.flowcache.web.FlowWebRoutable; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.util.CallerId; import net.floodlightcontroller.util.DataPath; import net.floodlightcontroller.util.Dpid; import net.floodlightcontroller.util.DataPathEndpoints; import net.floodlightcontroller.util.FlowEntry; import net.floodlightcontroller.util.FlowEntryAction; import net.floodlightcontroller.util.FlowEntryId; import net.floodlightcontroller.util.FlowEntryMatch; import net.floodlightcontroller.util.FlowEntrySwitchState; import net.floodlightcontroller.util.FlowEntryUserState; import net.floodlightcontroller.util.FlowId; import net.floodlightcontroller.util.FlowPath; import net.floodlightcontroller.util.IPv4Net; import net.floodlightcontroller.util.MACAddress; import net.floodlightcontroller.util.OFMessageDamper; import net.floodlightcontroller.util.Port; import net.floodlightcontroller.util.SwitchPort; import net.onrc.onos.util.GraphDBConnection; import net.onrc.onos.util.GraphDBConnection.Transaction; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFType; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FlowManager implements IFloodlightModule, IFlowService, INetMapStorage { public GraphDBConnection conn; protected IRestApiService restApi; protected IFloodlightProviderService floodlightProvider; protected FloodlightModuleContext context; protected OFMessageDamper messageDamper; // TODO: Values copied from elsewhere (class LearningSwitch). // The local copy should go away! protected static final int OFMESSAGE_DAMPER_CAPACITY = 50000; // TODO: find sweet spot protected static final int OFMESSAGE_DAMPER_TIMEOUT = 250; public static final short FLOWMOD_DEFAULT_IDLE_TIMEOUT = 0; // infinity public static final short FLOWMOD_DEFAULT_HARD_TIMEOUT = 0; // infinite public static final short PRIORITY_DEFAULT = 100; private static long nextFlowEntryId = 1; private static long measurementFlowId = 100000; private static String measurementFlowIdStr = "0x186a0"; // 100000 private long modifiedMeasurementFlowTime = 0; /** The logger. */ private static Logger log = LoggerFactory.getLogger(FlowManager.class); // The periodic task(s) private final ScheduledExecutorService measureShortestPathScheduler = Executors.newScheduledThreadPool(1); private final ScheduledExecutorService measureMapReaderScheduler = Executors.newScheduledThreadPool(1); private final ScheduledExecutorService mapReaderScheduler = Executors.newScheduledThreadPool(1); private BlockingQueue<Runnable> shortestPathQueue = new LinkedBlockingQueue<Runnable>(); private ThreadPoolExecutor shortestPathExecutor = new ThreadPoolExecutor(10, 10, 5, TimeUnit.SECONDS, shortestPathQueue); class ShortestPathTask implements Runnable { private int hint; private ITopoRouteService topoRouteService; private ArrayList<DataPath> dpList; public ShortestPathTask(int hint, ITopoRouteService topoRouteService, ArrayList<DataPath> dpList) { this.hint = hint; this.topoRouteService = topoRouteService; this.dpList = dpList; } @Override public void run() { /* String logMsg = "MEASUREMENT: Running Thread hint " + this.hint; log.debug(logMsg); long startTime = System.nanoTime(); */ for (DataPath dp : this.dpList) { topoRouteService.getTopoShortestPath(dp.srcPort(), dp.dstPort()); } /* long estimatedTime = System.nanoTime() - startTime; double rate = (estimatedTime > 0)? ((double)dpList.size() * 1000000000) / estimatedTime: 0.0; logMsg = "MEASUREMENT: Computed Thread hint " + hint + ": " + dpList.size() + " shortest paths in " + (double)estimatedTime / 1000000000 + " sec: " + rate + " flows/s"; log.debug(logMsg); */ } } final Runnable measureShortestPath = new Runnable() { public void run() { log.debug("Recomputing Shortest Paths from the Network Map Flows..."); if (floodlightProvider == null) { log.debug("FloodlightProvider service not found!"); return; } ITopoRouteService topoRouteService = context.getServiceImpl(ITopoRouteService.class); if (topoRouteService == null) { log.debug("Topology Route Service not found"); return; } int leftoverQueueSize = shortestPathExecutor.getQueue().size(); if (leftoverQueueSize > 0) { String logMsg = "MEASUREMENT: Leftover Shortest Path Queue Size: " + leftoverQueueSize; log.debug(logMsg); return; } log.debug("MEASUREMENT: Beginning Shortest Path Computation"); // Recompute the Shortest Paths for all Flows int counter = 0; int hint = 0; ArrayList<DataPath> dpList = new ArrayList<DataPath>(); long startTime = System.nanoTime(); topoRouteService.prepareShortestPathTopo(); Iterable<IFlowPath> allFlowPaths = conn.utils().getAllFlowPaths(conn); for (IFlowPath flowPathObj : allFlowPaths) { FlowId flowId = new FlowId(flowPathObj.getFlowId()); // log.debug("Found Path {}", flowId.toString()); Dpid srcDpid = new Dpid(flowPathObj.getSrcSwitch()); Port srcPort = new Port(flowPathObj.getSrcPort()); Dpid dstDpid = new Dpid(flowPathObj.getDstSwitch()); Port dstPort = new Port(flowPathObj.getDstPort()); SwitchPort srcSwitchPort = new SwitchPort(srcDpid, srcPort); SwitchPort dstSwitchPort = new SwitchPort(dstDpid, dstPort); /* DataPath dp = new DataPath(); dp.setSrcPort(srcSwitchPort); dp.setDstPort(dstSwitchPort); dpList.add(dp); if ((dpList.size() % 10) == 0) { shortestPathExecutor.execute( new ShortestPathTask(hint, topoRouteService, dpList)); dpList = new ArrayList<DataPath>(); hint++; } */ DataPath dataPath = topoRouteService.getTopoShortestPath(srcSwitchPort, dstSwitchPort); counter++; } if (dpList.size() > 0) { shortestPathExecutor.execute( new ShortestPathTask(hint, topoRouteService, dpList)); } /* // Wait for all tasks to finish try { while (shortestPathExecutor.getQueue().size() > 0) { Thread.sleep(100); } } catch (InterruptedException ex) { log.debug("MEASUREMENT: Shortest Path Computation interrupted"); } */ conn.endTx(Transaction.COMMIT); topoRouteService.dropShortestPathTopo(); long estimatedTime = System.nanoTime() - startTime; double rate = (estimatedTime > 0)? ((double)counter * 1000000000) / estimatedTime: 0.0; String logMsg = "MEASUREMENT: Computed " + counter + " shortest paths in " + (double)estimatedTime / 1000000000 + " sec: " + rate + " flows/s"; log.debug(logMsg); } }; final Runnable measureMapReader = new Runnable() { public void run() { if (floodlightProvider == null) { log.debug("FloodlightProvider service not found!"); return; } // Fetch all Flow Entries int counter = 0; long startTime = System.nanoTime(); Iterable<IFlowEntry> allFlowEntries = conn.utils().getAllFlowEntries(conn); for (IFlowEntry flowEntryObj : allFlowEntries) { counter++; FlowEntryId flowEntryId = new FlowEntryId(flowEntryObj.getFlowEntryId()); String userState = flowEntryObj.getUserState(); String switchState = flowEntryObj.getSwitchState(); } conn.endTx(Transaction.COMMIT); long estimatedTime = System.nanoTime() - startTime; double rate = (estimatedTime > 0)? ((double)counter * 1000000000) / estimatedTime: 0.0; String logMsg = "MEASUREMENT: Fetched " + counter + " flow entries in " + (double)estimatedTime / 1000000000 + " sec: " + rate + " entries/s"; log.debug(logMsg); } }; final Runnable mapReader = new Runnable() { public void run() { // log.debug("Reading Flow Entries from the Network Map..."); if (floodlightProvider == null) { log.debug("FloodlightProvider service not found!"); return; } Map<Long, IOFSwitch> mySwitches = floodlightProvider.getSwitches(); Map<Long, IFlowEntry> myFlowEntries = new TreeMap<Long, IFlowEntry>(); // Fetch all Flow Entries and select only my Flow Entries Iterable<IFlowEntry> allFlowEntries = conn.utils().getAllFlowEntries(conn); for (IFlowEntry flowEntryObj : allFlowEntries) { FlowEntryId flowEntryId = new FlowEntryId(flowEntryObj.getFlowEntryId()); String userState = flowEntryObj.getUserState(); String switchState = flowEntryObj.getSwitchState(); /** log.debug("Found Flow Entry {}: {}", flowEntryId.toString(), "User State: " + userState + " Switch State: " + switchState); */ if (! switchState.equals("FE_SWITCH_NOT_UPDATED")) { // Ignore the entry: nothing to do continue; } Dpid dpid = new Dpid(flowEntryObj.getSwitchDpid()); IOFSwitch mySwitch = mySwitches.get(dpid.value()); if (mySwitch == null) { log.debug("Flow Entry ignored: not my switch (FlowEntryId = {} DPID = {})", flowEntryId.toString(), dpid.toString()); continue; } myFlowEntries.put(flowEntryId.value(), flowEntryObj); } // Process my Flow Entries Boolean processed_measurement_flow = false; for (Map.Entry<Long, IFlowEntry> entry : myFlowEntries.entrySet()) { IFlowEntry flowEntryObj = entry.getValue(); // Code for measurement purpose { IFlowPath flowObj = conn.utils().getFlowPathByFlowEntry(conn, flowEntryObj); if ((flowObj != null) && flowObj.getFlowId().equals(measurementFlowIdStr)) { processed_measurement_flow = true; } } // TODO: Eliminate the re-fetching of flowEntryId, // userState, switchState, and dpid from the flowEntryObj. FlowEntryId flowEntryId = new FlowEntryId(flowEntryObj.getFlowEntryId()); Dpid dpid = new Dpid(flowEntryObj.getSwitchDpid()); String userState = flowEntryObj.getUserState(); String switchState = flowEntryObj.getSwitchState(); IOFSwitch mySwitch = mySwitches.get(dpid.value()); if (mySwitch == null) { log.debug("Flow Entry ignored: not my switch"); continue; } // Create the Open Flow Flow Modification Entry to push OFFlowMod fm = (OFFlowMod) floodlightProvider.getOFMessageFactory() .getMessage(OFType.FLOW_MOD); long cookie = flowEntryId.value(); short flowModCommand = OFFlowMod.OFPFC_ADD; if (userState.equals("FE_USER_ADD")) { flowModCommand = OFFlowMod.OFPFC_ADD; } else if (userState.equals("FE_USER_MODIFY")) { flowModCommand = OFFlowMod.OFPFC_MODIFY_STRICT; } else if (userState.equals("FE_USER_DELETE")) { flowModCommand = OFFlowMod.OFPFC_DELETE_STRICT; } else { // Unknown user state. Ignore the entry log.debug("Flow Entry ignored (FlowEntryId = {}): unknown user state {}", flowEntryId.toString(), userState); continue; } // Fetch the match conditions OFMatch match = new OFMatch(); match.setWildcards(OFMatch.OFPFW_ALL); Short matchInPort = flowEntryObj.getMatchInPort(); if (matchInPort != null) { match.setInputPort(matchInPort); match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_IN_PORT); } Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType(); if (matchEthernetFrameType != null) { match.setDataLayerType(matchEthernetFrameType); match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_TYPE); } String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net(); if (matchSrcIPv4Net != null) { match.setFromCIDR(matchSrcIPv4Net, OFMatch.STR_NW_SRC); } String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net(); if (matchDstIPv4Net != null) { match.setFromCIDR(matchDstIPv4Net, OFMatch.STR_NW_DST); } String matchSrcMac = flowEntryObj.getMatchSrcMac(); if (matchSrcMac != null) { match.setDataLayerSource(matchSrcMac); match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_SRC); } String matchDstMac = flowEntryObj.getMatchDstMac(); if (matchDstMac != null) { match.setDataLayerDestination(matchDstMac); match.setWildcards(match.getWildcards() & ~OFMatch.OFPFW_DL_DST); } // Fetch the actions List<OFAction> actions = new ArrayList<OFAction>(); Short actionOutputPort = flowEntryObj.getActionOutput(); if (actionOutputPort != null) { OFActionOutput action = new OFActionOutput(); // XXX: The max length is hard-coded for now action.setMaxLength((short)0xffff); action.setPort(actionOutputPort); actions.add(action); } fm.setIdleTimeout(FLOWMOD_DEFAULT_IDLE_TIMEOUT) .setHardTimeout(FLOWMOD_DEFAULT_HARD_TIMEOUT) .setPriority(PRIORITY_DEFAULT) .setBufferId(OFPacketOut.BUFFER_ID_NONE) .setCookie(cookie) .setCommand(flowModCommand) .setMatch(match) .setActions(actions) .setLengthU(OFFlowMod.MINIMUM_LENGTH+OFActionOutput.MINIMUM_LENGTH); fm.setOutPort(OFPort.OFPP_NONE.getValue()); if ((flowModCommand == OFFlowMod.OFPFC_DELETE) || (flowModCommand == OFFlowMod.OFPFC_DELETE_STRICT)) { if (actionOutputPort != null) fm.setOutPort(actionOutputPort); } // TODO: Set the following flag // fm.setFlags(OFFlowMod.OFPFF_SEND_FLOW_REM); // See method ForwardingBase::pushRoute() try { messageDamper.write(mySwitch, fm, null); mySwitch.flush(); flowEntryObj.setSwitchState("FE_SWITCH_UPDATED"); if (userState.equals("FE_USER_DELETE")) { // Delete the entry IFlowPath flowObj = null; flowObj = conn.utils().getFlowPathByFlowEntry(conn, flowEntryObj); if (flowObj != null) log.debug("Found FlowPath to be deleted"); else log.debug("Did not find FlowPath to be deleted"); flowObj.removeFlowEntry(flowEntryObj); conn.utils().removeFlowEntry(conn, flowEntryObj); // Test whether the last flow entry Iterable<IFlowEntry> tmpflowEntries = flowObj.getFlowEntries(); boolean found = false; for (IFlowEntry tmpflowEntryObj : tmpflowEntries) { found = true; break; } if (! found) { // Remove the Flow Path as well conn.utils().removeFlowPath(conn, flowObj); } } } catch (IOException e) { log.error("Failure writing flow mod from network map", e); } } conn.endTx(Transaction.COMMIT); if (processed_measurement_flow) { long estimatedTime = System.nanoTime() - modifiedMeasurementFlowTime; String logMsg = "MEASUREMENT: Pushed Flow delay: " + (double)estimatedTime / 1000000000 + " sec"; log.debug(logMsg); } } }; /* final ScheduledFuture<?> measureShortestPathHandle = measureShortestPathScheduler.scheduleAtFixedRate(measureShortestPath, 10, 10, TimeUnit.SECONDS); */ /* final ScheduledFuture<?> measureMapReaderHandle = measureMapReaderScheduler.scheduleAtFixedRate(measureMapReader, 10, 10, TimeUnit.SECONDS); */ final ScheduledFuture<?> mapReaderHandle = mapReaderScheduler.scheduleAtFixedRate(mapReader, 3, 3, TimeUnit.SECONDS); @Override public void init(String conf) { conn = GraphDBConnection.getInstance(conf); } public void finalize() { close(); } @Override public void close() { conn.close(); } @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFlowService.class); return l; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); m.put(IFlowService.class, this); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(IFloodlightProviderService.class); l.add(IRestApiService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { this.context = context; floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); restApi = context.getServiceImpl(IRestApiService.class); messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY, EnumSet.of(OFType.FLOW_MOD), OFMESSAGE_DAMPER_TIMEOUT); // TODO: An ugly hack! String conf = "/tmp/cassandra.titan"; this.init(conf); } @Override public void startUp(FloodlightModuleContext context) { restApi.addRestletRoutable(new FlowWebRoutable()); // Extract all flow entries and assign the next Flow Entry ID // to be larger than the largest Flow Entry ID Iterable<IFlowEntry> allFlowEntries = conn.utils().getAllFlowEntries(conn); for (IFlowEntry flowEntryObj : allFlowEntries) { FlowEntryId flowEntryId = new FlowEntryId(flowEntryObj.getFlowEntryId()); if (flowEntryId.value() >= nextFlowEntryId) nextFlowEntryId = flowEntryId.value() + 1; } conn.endTx(Transaction.COMMIT); } /** * Add a flow. * * Internally, ONOS will automatically register the installer for * receiving Flow Path Notifications for that path. * * @param flowPath the Flow Path to install. * @param flowId the return-by-reference Flow ID as assigned internally. * @return true on success, otherwise false. */ @Override public boolean addFlow(FlowPath flowPath, FlowId flowId) { if (flowPath.flowId().value() == measurementFlowId) { modifiedMeasurementFlowTime = System.nanoTime(); } // Assign the FlowEntry IDs // Right now every new flow entry gets a new flow entry ID // TODO: This needs to be redesigned! for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) { long id = nextFlowEntryId++; flowEntry.setFlowEntryId(new FlowEntryId(id)); } IFlowPath flowObj = null; try { if ((flowObj = conn.utils().searchFlowPath(conn, flowPath.flowId())) != null) { log.debug("Adding FlowPath with FlowId {}: found existing FlowPath", flowPath.flowId().toString()); } else { flowObj = conn.utils().newFlowPath(conn); log.debug("Adding FlowPath with FlowId {}: creating new FlowPath", flowPath.flowId().toString()); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":addFlow FlowId:{} failed", flowPath.flowId().toString()); } if (flowObj == null) { conn.endTx(Transaction.COMMIT); return false; } // Set the Flow key: // - flowId flowObj.setFlowId(flowPath.flowId().toString()); flowObj.setType("flow"); // Set the Flow attributes: // - flowPath.installerId() // - flowPath.dataPath().srcPort() // - flowPath.dataPath().dstPort() flowObj.setInstallerId(flowPath.installerId().toString()); flowObj.setSrcSwitch(flowPath.dataPath().srcPort().dpid().toString()); flowObj.setSrcPort(flowPath.dataPath().srcPort().port().value()); flowObj.setDstSwitch(flowPath.dataPath().dstPort().dpid().toString()); flowObj.setDstPort(flowPath.dataPath().dstPort().port().value()); // Flow edges: // HeadFE // Flow Entries: // flowPath.dataPath().flowEntries() for (FlowEntry flowEntry : flowPath.dataPath().flowEntries()) { IFlowEntry flowEntryObj = null; boolean found = false; try { if ((flowEntryObj = conn.utils().searchFlowEntry(conn, flowEntry.flowEntryId())) != null) { log.debug("Adding FlowEntry with FlowEntryId {}: found existing FlowEntry", flowEntry.flowEntryId().toString()); found = true; } else { flowEntryObj = conn.utils().newFlowEntry(conn); log.debug("Adding FlowEntry with FlowEntryId {}: creating new FlowEntry", flowEntry.flowEntryId().toString()); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":addFlow FlowEntryId:{} failed", flowEntry.flowEntryId().toString()); } if (flowEntryObj == null) { conn.endTx(Transaction.COMMIT); return false; } // Set the Flow Entry key: // - flowEntry.flowEntryId() flowEntryObj.setFlowEntryId(flowEntry.flowEntryId().toString()); flowEntryObj.setType("flow_entry"); // Set the Flow Entry attributes: // - flowEntry.flowEntryMatch() // - flowEntry.flowEntryActions() // - flowEntry.dpid() // - flowEntry.flowEntryUserState() // - flowEntry.flowEntrySwitchState() // - flowEntry.flowEntryErrorState() // - flowEntry.matchInPort() // - flowEntry.matchEthernetFrameType() // - flowEntry.matchSrcIPv4Net() // - flowEntry.matchDstIPv4Net() // - flowEntry.matchSrcMac() // - flowEntry.matchDstMac() // - flowEntry.actionOutput() flowEntryObj.setSwitchDpid(flowEntry.dpid().toString()); if (flowEntry.flowEntryMatch().matchInPort()) flowEntryObj.setMatchInPort(flowEntry.flowEntryMatch().inPort().value()); if (flowEntry.flowEntryMatch().matchEthernetFrameType()) flowEntryObj.setMatchEthernetFrameType(flowEntry.flowEntryMatch().ethernetFrameType()); if (flowEntry.flowEntryMatch().matchSrcIPv4Net()) flowEntryObj.setMatchSrcIPv4Net(flowEntry.flowEntryMatch().srcIPv4Net().toString()); if (flowEntry.flowEntryMatch().matchDstIPv4Net()) flowEntryObj.setMatchDstIPv4Net(flowEntry.flowEntryMatch().dstIPv4Net().toString()); if (flowEntry.flowEntryMatch().matchSrcMac()) flowEntryObj.setMatchSrcMac(flowEntry.flowEntryMatch().srcMac().toString()); if (flowEntry.flowEntryMatch().matchDstMac()) flowEntryObj.setMatchDstMac(flowEntry.flowEntryMatch().dstMac().toString()); for (FlowEntryAction fa : flowEntry.flowEntryActions()) { if (fa.actionOutput() != null) flowEntryObj.setActionOutput(fa.actionOutput().port().value()); } // TODO: Hacks with hard-coded state names! if (found) flowEntryObj.setUserState("FE_USER_MODIFY"); else flowEntryObj.setUserState("FE_USER_ADD"); flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED"); // TODO: Take care of the FlowEntryMatch, FlowEntryAction set, // and FlowEntryErrorState. // Flow Entries edges: // Flow // NextFE // InPort // OutPort // Switch if (! found) flowObj.addFlowEntry(flowEntryObj); } conn.endTx(Transaction.COMMIT); // TODO: We need a proper Flow ID allocation mechanism. flowId.setValue(flowPath.flowId().value()); return true; } /** * Delete a previously added flow. * * @param flowId the Flow ID of the flow to delete. * @return true on success, otherwise false. */ @Override public boolean deleteFlow(FlowId flowId) { if (flowId.value() == measurementFlowId) { modifiedMeasurementFlowTime = System.nanoTime(); } IFlowPath flowObj = null; // We just mark the entries for deletion, // and let the switches remove each individual entry after // it has been removed from the switches. try { if ((flowObj = conn.utils().searchFlowPath(conn, flowId)) != null) { log.debug("Deleting FlowPath with FlowId {}: found existing FlowPath", flowId.toString()); } else { log.debug("Deleting FlowPath with FlowId {}: FlowPath not found", flowId.toString()); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":deleteFlow FlowId:{} failed", flowId.toString()); } if (flowObj == null) { conn.endTx(Transaction.COMMIT); return true; // OK: No such flow } // Find and mark for deletion all Flow Entries Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries(); boolean empty = true; // TODO: an ugly hack for (IFlowEntry flowEntryObj : flowEntries) { empty = false; // flowObj.removeFlowEntry(flowEntryObj); // conn.utils().removeFlowEntry(conn, flowEntryObj); flowEntryObj.setUserState("FE_USER_DELETE"); flowEntryObj.setSwitchState("FE_SWITCH_NOT_UPDATED"); } // Remove from the database empty flows if (empty) conn.utils().removeFlowPath(conn, flowObj); conn.endTx(Transaction.COMMIT); return true; } /** * Clear the state for a previously added flow. * * @param flowId the Flow ID of the flow to clear. * @return true on success, otherwise false. */ @Override public boolean clearFlow(FlowId flowId) { IFlowPath flowObj = null; try { if ((flowObj = conn.utils().searchFlowPath(conn, flowId)) != null) { log.debug("Clearing FlowPath with FlowId {}: found existing FlowPath", flowId.toString()); } else { log.debug("Clearing FlowPath with FlowId {}: FlowPath not found", flowId.toString()); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":clearFlow FlowId:{} failed", flowId.toString()); } if (flowObj == null) { conn.endTx(Transaction.COMMIT); return true; // OK: No such flow } // Remove all Flow Entries Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries(); for (IFlowEntry flowEntryObj : flowEntries) { flowObj.removeFlowEntry(flowEntryObj); conn.utils().removeFlowEntry(conn, flowEntryObj); } // Remove the Flow itself conn.utils().removeFlowPath(conn, flowObj); conn.endTx(Transaction.COMMIT); return true; } /** * Get a previously added flow. * * @param flowId the Flow ID of the flow to get. * @return the Flow Path if found, otherwise null. */ @Override public FlowPath getFlow(FlowId flowId) { IFlowPath flowObj = null; try { if ((flowObj = conn.utils().searchFlowPath(conn, flowId)) != null) { log.debug("Get FlowPath with FlowId {}: found existing FlowPath", flowId.toString()); } else { log.debug("Get FlowPath with FlowId {}: FlowPath not found", flowId.toString()); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":getFlow FlowId:{} failed", flowId.toString()); } if (flowObj == null) { conn.endTx(Transaction.COMMIT); return null; // Flow not found } // Extract the Flow state FlowPath flowPath = extractFlowPath(flowObj); conn.endTx(Transaction.COMMIT); return flowPath; } /** * Get all previously added flows by a specific installer for a given * data path endpoints. * * @param installerId the Caller ID of the installer of the flow to get. * @param dataPathEndpoints the data path endpoints of the flow to get. * @return the Flow Paths if found, otherwise null. */ @Override public ArrayList<FlowPath> getAllFlows(CallerId installerId, DataPathEndpoints dataPathEndpoints) { // TODO: The implementation below is not optimal: // We fetch all flows, and then return only the subset that match // the query conditions. // We should use the appropriate Titan/Gremlin query to filter-out // the flows as appropriate. ArrayList<FlowPath> allFlows = getAllFlows(); if (allFlows == null) { log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints); return null; } ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>(); for (FlowPath flow : allFlows) { // TODO: String-based comparison is sub-optimal. // We are using it for now to save us the extra work of // implementing the "equals()" and "hashCode()" methods. if (! flow.installerId().toString().equals(installerId.toString())) continue; if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) { continue; } if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) { continue; } flowPaths.add(flow); } if (flowPaths.isEmpty()) { log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: no FlowPaths found", installerId, dataPathEndpoints); flowPaths = null; } else { log.debug("Get FlowPaths for installerId{} and dataPathEndpoints{}: FlowPaths are found", installerId, dataPathEndpoints); } return flowPaths; } /** * Get all installed flows by all installers for given data path endpoints. * * @param dataPathEndpoints the data path endpoints of the flows to get. * @return the Flow Paths if found, otherwise null. */ @Override public ArrayList<FlowPath> getAllFlows(DataPathEndpoints dataPathEndpoints) { // TODO: The implementation below is not optimal: // We fetch all flows, and then return only the subset that match // the query conditions. // We should use the appropriate Titan/Gremlin query to filter-out // the flows as appropriate. ArrayList<FlowPath> allFlows = getAllFlows(); if (allFlows == null) { log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints); return null; } ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>(); for (FlowPath flow : allFlows) { // TODO: String-based comparison is sub-optimal. // We are using it for now to save us the extra work of // implementing the "equals()" and "hashCode()" methods. if (! flow.dataPath().srcPort().toString().equals(dataPathEndpoints.srcPort().toString())) { continue; } if (! flow.dataPath().dstPort().toString().equals(dataPathEndpoints.dstPort().toString())) { continue; } flowPaths.add(flow); } if (flowPaths.isEmpty()) { log.debug("Get FlowPaths for dataPathEndpoints{}: no FlowPaths found", dataPathEndpoints); flowPaths = null; } else { log.debug("Get FlowPaths for dataPathEndpoints{}: FlowPaths are found", dataPathEndpoints); } return flowPaths; } /** * Get summary of all installed flows by all installers in a given range * * @param flowId the data path endpoints of the flows to get. * @param maxFlows: the maximum number of flows to be returned * @return the Flow Paths if found, otherwise null. */ @Override public ArrayList<FlowPath> getAllFlowsSummary(FlowId flowId, int maxFlows) { // TODO: The implementation below is not optimal: // We fetch all flows, and then return only the subset that match // the query conditions. // We should use the appropriate Titan/Gremlin query to filter-out // the flows as appropriate. ArrayList<FlowPath> allFlows = getAllFlows(); if (allFlows == null) { log.debug("Get FlowPathsSummary for {} {}: no FlowPaths found", flowId, maxFlows); return null; } Collections.sort(allFlows); ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>(); for (FlowPath flow : allFlows) { // start from desired flowId if (flow.flowId().value() < flowId.value()) { continue; } // Summarize by making null flow entry fields that are not relevant to report for (FlowEntry flowEntry : flow.dataPath().flowEntries()) { flowEntry.setFlowEntryActions(null); flowEntry.setFlowEntryMatch(null); } flowPaths.add(flow); if (maxFlows != 0 && flowPaths.size() >= maxFlows) { break; } } if (flowPaths.isEmpty()) { log.debug("Get FlowPathsSummary {} {}: no FlowPaths found", flowId, maxFlows); flowPaths = null; } else { log.debug("Get FlowPathsSummary for {} {}: FlowPaths were found", flowId, maxFlows); } return flowPaths; } /** * Get all installed flows by all installers. * * @return the Flow Paths if found, otherwise null. */ @Override public ArrayList<FlowPath> getAllFlows() { Iterable<IFlowPath> flowPathsObj = null; try { if ((flowPathsObj = conn.utils().getAllFlowPaths(conn)) != null) { log.debug("Get all FlowPaths: found FlowPaths"); } else { log.debug("Get all FlowPaths: no FlowPaths found"); } } catch (Exception e) { // TODO: handle exceptions conn.endTx(Transaction.ROLLBACK); log.error(":getAllFlowPaths failed"); } if ((flowPathsObj == null) || (flowPathsObj.iterator().hasNext() == false)) { conn.endTx(Transaction.COMMIT); return null; // No Flows found } ArrayList<FlowPath> flowPaths = new ArrayList<FlowPath>(); for (IFlowPath flowObj : flowPathsObj) { // Extract the Flow state FlowPath flowPath = extractFlowPath(flowObj); flowPaths.add(flowPath); } conn.endTx(Transaction.COMMIT); return flowPaths; } /** * Extract Flow Path State from a Titan Database Object @ref IFlowPath. * * @param flowObj the object to extract the Flow Path State from. * @return the extracted Flow Path State. */ private FlowPath extractFlowPath(IFlowPath flowObj) { FlowPath flowPath = new FlowPath(); // Extract the Flow state flowPath.setFlowId(new FlowId(flowObj.getFlowId())); flowPath.setInstallerId(new CallerId(flowObj.getInstallerId())); flowPath.dataPath().srcPort().setDpid(new Dpid(flowObj.getSrcSwitch())); flowPath.dataPath().srcPort().setPort(new Port(flowObj.getSrcPort())); flowPath.dataPath().dstPort().setDpid(new Dpid(flowObj.getDstSwitch())); flowPath.dataPath().dstPort().setPort(new Port(flowObj.getDstPort())); // Extract all Flow Entries Iterable<IFlowEntry> flowEntries = flowObj.getFlowEntries(); for (IFlowEntry flowEntryObj : flowEntries) { FlowEntry flowEntry = new FlowEntry(); flowEntry.setFlowEntryId(new FlowEntryId(flowEntryObj.getFlowEntryId())); flowEntry.setDpid(new Dpid(flowEntryObj.getSwitchDpid())); // Extract the match conditions FlowEntryMatch match = new FlowEntryMatch(); Short matchInPort = flowEntryObj.getMatchInPort(); if (matchInPort != null) match.enableInPort(new Port(matchInPort)); Short matchEthernetFrameType = flowEntryObj.getMatchEthernetFrameType(); if (matchEthernetFrameType != null) match.enableEthernetFrameType(matchEthernetFrameType); String matchSrcIPv4Net = flowEntryObj.getMatchSrcIPv4Net(); if (matchSrcIPv4Net != null) match.enableSrcIPv4Net(new IPv4Net(matchSrcIPv4Net)); String matchDstIPv4Net = flowEntryObj.getMatchDstIPv4Net(); if (matchDstIPv4Net != null) match.enableDstIPv4Net(new IPv4Net(matchDstIPv4Net)); String matchSrcMac = flowEntryObj.getMatchSrcMac(); if (matchSrcMac != null) match.enableSrcMac(MACAddress.valueOf(matchSrcMac)); String matchDstMac = flowEntryObj.getMatchDstMac(); if (matchDstMac != null) match.enableDstMac(MACAddress.valueOf(matchDstMac)); flowEntry.setFlowEntryMatch(match); // Extract the actions ArrayList<FlowEntryAction> actions = new ArrayList<FlowEntryAction>(); Short actionOutputPort = flowEntryObj.getActionOutput(); if (actionOutputPort != null) { FlowEntryAction action = new FlowEntryAction(); action.setActionOutput(new Port(actionOutputPort)); actions.add(action); } flowEntry.setFlowEntryActions(actions); String userState = flowEntryObj.getUserState(); flowEntry.setFlowEntryUserState(FlowEntryUserState.valueOf(userState)); String switchState = flowEntryObj.getSwitchState(); flowEntry.setFlowEntrySwitchState(FlowEntrySwitchState.valueOf(switchState)); // TODO: Take care of the FlowEntryMatch, FlowEntryAction set, // and FlowEntryErrorState. flowPath.dataPath().flowEntries().add(flowEntry); } return flowPath; } }
package net.floodlightcontroller.randomizer; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.staticentry.IStaticEntryPusherService; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.action.OFActionOutput; import org.projectfloodlight.openflow.protocol.action.OFActionSetField; import org.projectfloodlight.openflow.protocol.action.OFActions; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.protocol.oxm.OFOxms; import org.projectfloodlight.openflow.types.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Randomizer implements IOFMessageListener, IFloodlightModule { //region Properties private ScheduledExecutorService executorService; private IFloodlightProviderService floodlightProvider; private IStaticEntryPusherService staticEntryPusherService; private static Logger log; private List<IPv4Address> whiteListedHostsIPv4; private List<IPv6Address> whiteListedHostsIPv6; private static boolean LOCAL_HOST_IS_RANDOMIZED = false; //endregion //region Helper Functions private void insertDestinationEncryptFlow(IOFSwitch sw, IPv4 l3) { OFFactory factory = sw.getOFFactory(); Match match = factory.buildMatch() //.setExact(MatchField.IN_PORT, inPort) .setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IPV4_DST, l3.getDestinationAddress()) .build(); ArrayList<OFAction> actionList = new ArrayList<>(); OFActions actions = factory.actions(); OFOxms oxms = factory.oxms(); /* Use OXM to modify network layer dest field. */ OFActionSetField setNwDst = actions.buildSetField() .setField( oxms.buildIpv4Dst() .setValue(generateRandomIPv4Address()) .build() ) .build(); actionList.add(setNwDst); /* Output to a port is also an OFAction, not an OXM. */ OFActionOutput output = actions.buildOutput() .setMaxLen(0xFFffFFff) .setPort(OFPort.of(1)) .build(); actionList.add(output); OFFlowAdd flowAdd = factory.buildFlowAdd() .setBufferId(OFBufferId.NO_BUFFER) .setHardTimeout(30) .setIdleTimeout(30) .setPriority(32768) .setMatch(match) .setActions(actionList) //.setTableId(TableId.of(1)) .build(); sw.write(flowAdd); } private void insertDestinationDecryptFlow(IOFSwitch sw, IPv4 l3) { OFFactory factory = sw.getOFFactory(); Match match = factory.buildMatch() //.setExact(MatchField.IN_PORT, inPort) .setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IPV4_DST, generateRandomIPv4Address()) //TODO Pull this from a map .build(); ArrayList<OFAction> actionList = new ArrayList<>(); OFActions actions = factory.actions(); OFOxms oxms = factory.oxms(); /* Use OXM to modify network layer dest field. */ OFActionSetField setNwDst = actions.buildSetField() .setField( oxms.buildIpv4Dst() .setValue(l3.getDestinationAddress()) .build() ) .build(); actionList.add(setNwDst); /* Output to a port is also an OFAction, not an OXM. */ OFActionOutput output = actions.buildOutput() .setMaxLen(0xFFffFFff) .setPort(OFPort.LOCAL) .build(); actionList.add(output); OFFlowAdd flowAdd = factory.buildFlowAdd() .setBufferId(OFBufferId.NO_BUFFER) .setHardTimeout(30) .setIdleTimeout(30) .setPriority(32768) .setMatch(match) .setActions(actionList) //.setTableId(TableId.of(1)) .build(); sw.write(flowAdd);} private void insertSourceEncryptFlow(IOFSwitch sw, IPv4 l3) { OFFactory factory = sw.getOFFactory(); Match match = factory.buildMatch() //.setExact(MatchField.IN_PORT, inPort) .setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IPV4_SRC, l3.getSourceAddress()) .build(); ArrayList<OFAction> actionList = new ArrayList<>(); OFActions actions = factory.actions(); OFOxms oxms = factory.oxms(); /* Use OXM to modify network layer dest field. */ OFActionSetField setNwSrc = actions.buildSetField() .setField( oxms.buildIpv4Src() .setValue(generateRandomIPv4Address()) .build() ) .build(); actionList.add(setNwSrc); /* Output to a port is also an OFAction, not an OXM. */ OFActionOutput output = actions.buildOutput() .setMaxLen(0xFFffFFff) .setPort(OFPort.of(1)) .build(); actionList.add(output); OFFlowAdd flowAdd = factory.buildFlowAdd() .setBufferId(OFBufferId.NO_BUFFER) .setHardTimeout(30) .setIdleTimeout(30) .setPriority(32768) .setMatch(match) .setActions(actionList) //.setTableId(TableId.of(1)) .build(); sw.write(flowAdd);} private void insertSourceDecryptFlow(IOFSwitch sw, IPv4 l3) { OFFactory factory = sw.getOFFactory(); Match match = factory.buildMatch() //.setExact(MatchField.IN_PORT, inPort) .setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IPV4_SRC, generateRandomIPv4Address()) .build(); ArrayList<OFAction> actionList = new ArrayList<>(); OFActions actions = factory.actions(); OFOxms oxms = factory.oxms(); /* Use OXM to modify network layer dest field. */ OFActionSetField setNwSrc = actions.buildSetField() .setField( oxms.buildIpv4Src() .setValue(l3.getSourceAddress()) .build() ) .build(); actionList.add(setNwSrc); /* Output to a port is also an OFAction, not an OXM. */ OFActionOutput output = actions.buildOutput() .setMaxLen(0xFFffFFff) .setPort(OFPort.LOCAL) .build(); actionList.add(output); OFFlowAdd flowAdd = factory.buildFlowAdd() .setBufferId(OFBufferId.NO_BUFFER) .setHardTimeout(30) .setIdleTimeout(30) .setPriority(32768) .setMatch(match) .setActions(actionList) //.setTableId(TableId.of(1)) .build(); sw.write(flowAdd);} private IPv4Address generateRandomIPv4Address() { int minutes = LocalDateTime.now().getMinute(); int seconds = LocalDateTime.now().getSecond(); return IPv4Address.of(10, 0, 0, minutes); } private IPv6Address generateRandomIPv6Address() { return IPv6Address.of(new Random().nextLong(), new Random().nextLong()); } private void startTest() { executorService.scheduleAtFixedRate((Runnable) () -> { log.info("{}", generateRandomIPv4Address()); }, 0L, 20L, TimeUnit.SECONDS); whiteListedHostsIPv4.add(IPv4Address.of(10, 0, 0, 2)); } //endregion //region IOFMessageListener Implementation @Override public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { OFPacketIn pi = (OFPacketIn) msg; OFPort inPort = (pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT)); Ethernet l2 = IFloodlightProviderService.bcStore.get(cntx, IFloodlightProviderService.CONTEXT_PI_PAYLOAD); if (l2.getEtherType() == EthType.IPv4) { IPv4 l3 = (IPv4) l2.getPayload(); if (LOCAL_HOST_IS_RANDOMIZED) { log.info("IPv4 packet seen on Randomized host."); if (inPort.equals(OFPort.LOCAL)) { log.info("LOCAL! Inserting flow to encrypt the source IP."); insertSourceEncryptFlow(sw, l3); } else { log.info("Other! Inserting flow to decrypt the destination IP."); insertDestinationDecryptFlow(sw, l3); } } else { log.info("IPv4 packet seen on non-Randomized host."); if (inPort.equals(OFPort.LOCAL)) { log.info("LOCAL! Inserting flow to encrypt the destination IP."); insertDestinationEncryptFlow(sw, l3); } else { log.info("Other! Inserting flow to decrypt the source IP."); insertSourceDecryptFlow(sw, l3); } } } return Command.CONTINUE; } @Override public String getName() { return Randomizer.class.getSimpleName(); } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return false; } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { if (type.equals(OFType.PACKET_IN) && (name.equals("forwarding"))) { log.trace("Randomizer is telling Forwarding to run later."); return true; } else { return false; } } //endregion //region IFloodlightModule Implementation @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { return null; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { return null; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<>(); l.add(IFloodlightProviderService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { executorService = Executors.newSingleThreadScheduledExecutor(); floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); staticEntryPusherService = context.getServiceImpl(IStaticEntryPusherService.class); log = LoggerFactory.getLogger(Randomizer.class); Map<String, String> configParameters = context.getConfigParams(this); String tmp = configParameters.get("randomize-host"); log.info("tmp is {}", tmp); if (tmp != null) { tmp = tmp.trim().toLowerCase(); if (tmp.contains("yes") || tmp.contains("true")) { LOCAL_HOST_IS_RANDOMIZED = true; log.info("Local host will be treated as having randomized addresses."); } else { LOCAL_HOST_IS_RANDOMIZED = false; log.info("Local host will be treated as having a static address."); } } whiteListedHostsIPv4 = new ArrayList<>(); whiteListedHostsIPv6 = new ArrayList<>(); } @Override public void startUp(FloodlightModuleContext context) throws FloodlightModuleException { floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); startTest(); } //endregion }
package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import java.nio.BufferUnderflowException; import static net.openhft.chronicle.wire.Wires.*; public class ReadDocumentContext implements DocumentContext { private final InternalWire wire; private boolean data; private boolean present; private long readPosition, readLimit; public ReadDocumentContext(Wire wire) { this.wire = (InternalWire) wire; } @Override public boolean isMetaData() { return !data && present; } @Override public boolean isPresent() { return present; } public void closeReadPosition(long readPosition) { this.readPosition = readPosition; } public void closeReadLimit(long readLimit) { this.readLimit = readLimit; } @Override public boolean isData() { return data && present; } @Override public Wire wire() { return wire; } @Override public void close() { if (readLimit > 0) { final Bytes<?> bytes = wire.bytes(); bytes.readPosition(readPosition); bytes.readLimit(readLimit); } } public void start() { final Bytes<?> bytes = wire.bytes(); if (bytes.readRemaining() < 4) { present = false; readPosition = readLimit = -1; return; } long position = bytes.readPosition(); int header = bytes.readVolatileInt(position); if (!isKnownLength(header) || !isReady(header)) { present = false; return; } bytes.readSkip(4); final boolean ready = isReady(header); final int len = lengthOf(header); assert len > 0 : "len=" + len; data = Wires.isData(header); wire.setReady(ready); if (len > bytes.readRemaining()) throw new BufferUnderflowException(); readLimit = bytes.readLimit(); readPosition = bytes.readPosition() + len; bytes.readLimit(readPosition); present = true; } }
// OO2PdfConverterUnoImpl.java package net.sf.sze.service.impl; import net.sf.sze.service.api.OO2PdfConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.star.beans.PropertyValue; import com.sun.star.comp.helper.Bootstrap; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XStorable; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; import com.sun.star.util.XCloseable; import java.io.File; import java.io.IOException; public class OO2PdfConverterUnoImpl implements OO2PdfConverter { /** The log. */ private final Logger log = LoggerFactory.getLogger( OO2PdfConverterUnoImpl.class.getName()); /** * Main-Methode. * @param args argumente. */ public static void main(String[] args) { final File sourceFile = new File( "D:\\sandboxes\\schule_ppi\\sze\\oofiles\\templates\\fsn.odt"); final File outputFile = new File( "D:\\sandboxes\\schule_ppi\\sze\\pdffiles\\fsn.pdf"); final OO2PdfConverter unoC = new OO2PdfConverterUnoImpl(); unoC.convert(sourceFile, outputFile); System.exit(0); } /* * (non-Javadoc) * @see net.sf.sze.ootools.PdfConverter#convert(java.io.File, java.io.File) */ @Override public void convert(File sourceFile, File outputFile) { try { // get the remote office component context XComponentContext xContext = Bootstrap.bootstrap(); // get the remote office service manager XMultiComponentFactory xMCF = xContext.getServiceManager(); Object oDesktop = xMCF.createInstanceWithContext( "com.sun.star.frame.Desktop", xContext); XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime .queryInterface(XComponentLoader.class, oDesktop); log.info("OO ist initialisiert"); StringBuffer sLoadUrl = new StringBuffer("file: sLoadUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); StringBuffer sSaveUrl = new StringBuffer("file: sSaveUrl.append(outputFile.getCanonicalPath().replace('\\', '/')); PropertyValue[] propertyValue = new PropertyValue[1]; propertyValue[0] = new PropertyValue(); propertyValue[0].Name = "Hidden"; propertyValue[0].Value = Boolean.TRUE; Object oDocToStore = xCompLoader.loadComponentFromURL(sLoadUrl .toString(), "_blank", 0, propertyValue); log.info("Dokument geladen."); XStorable xStorable = (XStorable) UnoRuntime.queryInterface( XStorable.class, oDocToStore); propertyValue = new PropertyValue[2]; propertyValue[0] = new PropertyValue(); propertyValue[0].Name = "Overwrite"; propertyValue[0].Value = Boolean.TRUE; propertyValue[1] = new PropertyValue(); propertyValue[1].Name = "FilterName"; propertyValue[1].Value = "writer_pdf_Export"; xStorable.storeToURL(sSaveUrl.toString(), propertyValue); log.info("Dokument " + sSaveUrl + " gespeichert."); XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface( XCloseable.class, oDocToStore); if (xCloseable != null) { xCloseable.close(false); } else { XComponent xComp = (XComponent) UnoRuntime.queryInterface( XComponent.class, oDocToStore); xComp.dispose(); } } catch (BootstrapException e) { String message = "Die Remote-Komponenten konnte nicht kontaktiert werden."; log.warn(message, e); throw new ConvertionException(message, e); } catch (com.sun.star.uno.Exception e) { String message = "Konnte den Office-Service nicht starten."; log.warn(message, e); throw new ConvertionException(message, e); } catch (IOException e) { String message = "Canonicalname konnte nicht ermittelt werden"; log.warn(message, e); throw new ConvertionException(message, e); } } /** * The convertion of the file was failed. * @author niels * */ public static class ConvertionException extends RuntimeException { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new convertion exception. * * @param message the message * @param cause the cause */ public ConvertionException(String message, java.lang.Exception cause) { super(message, cause); } } @Override public void closeConnection() { // Nichts zu tun hier. } @Override public void init() { // Nichts zu tun hier. } }
package net.snowflake.client.jdbc; import net.snowflake.client.core.ParameterBindingDTO; import net.snowflake.client.core.ResultUtil; import net.snowflake.client.core.SFBaseResultSet; import net.snowflake.client.core.SFException; import net.snowflake.client.core.SFStatement; import net.snowflake.client.core.StmtUtil; import net.snowflake.client.log.ArgSupplier; import net.snowflake.client.log.SFLogger; import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.client.util.SecretDetector; import net.snowflake.client.util.VariableTypeArray; import net.snowflake.common.core.SqlState; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import static net.snowflake.client.jdbc.ErrorCode.FEATURE_UNSUPPORTED; /** * Snowflake statement */ class SnowflakeStatementV1 implements Statement, SnowflakeStatement { static final SFLogger logger = SFLoggerFactory.getLogger(SnowflakeStatementV1.class); private static final long NO_UPDATES = -1; protected final SnowflakeConnectionV1 connection; protected final int resultSetType; protected final int resultSetConcurrency; protected final int resultSetHoldability; /* * The maximum number of rows this statement ( should return (0 => all rows). */ private int maxRows = 0; // Refer to all open resultSets from this statement private final Set<ResultSet> openResultSets = Collections.synchronizedSet(new HashSet<>()); // result set currently in use private ResultSet resultSet = null; private int fetchSize = 50; private Boolean isClosed = false; private long updateCount = NO_UPDATES; // timeout in seconds private int queryTimeout = 0; // max field size limited to 16MB private final int maxFieldSize = 16777216; SFStatement sfStatement; private boolean poolable; /** * Snowflake query ID from the latest executed query */ private String queryID; /** * Snowflake query IDs from the latest executed batch */ private List<String> batchQueryIDs = new LinkedList<>(); /** * batch of sql strings added by addBatch */ protected final List<BatchEntry> batch = new ArrayList<>(); private SQLWarning sqlWarnings; /** * Construct SnowflakeStatementV1 * * @param connection connection object * @param resultSetType result set type: ResultSet.TYPE_FORWARD_ONLY. * @param resultSetConcurrency result set concurrency: ResultSet.CONCUR_READ_ONLY. * @param resultSetHoldability result set holdability: ResultSet.CLOSE_CURSORS_AT_COMMIT * @throws SQLException if any SQL error occurs. */ SnowflakeStatementV1( SnowflakeConnectionV1 connection, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { logger.debug( " public SnowflakeStatement(SnowflakeConnectionV1 conn)"); this.connection = connection; if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) { throw new SQLFeatureNotSupportedException( String.format("ResultSet type %d is not supported.", resultSetType), FEATURE_UNSUPPORTED.getSqlState(), FEATURE_UNSUPPORTED.getMessageCode()); } if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) { throw new SQLFeatureNotSupportedException( String.format("ResultSet concurrency %d is not supported.", resultSetConcurrency), FEATURE_UNSUPPORTED.getSqlState(), FEATURE_UNSUPPORTED.getMessageCode()); } if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) { throw new SQLFeatureNotSupportedException( String.format("ResultSet holdability %d is not supported.", resultSetHoldability), FEATURE_UNSUPPORTED.getSqlState(), FEATURE_UNSUPPORTED.getMessageCode()); } this.resultSetType = resultSetType; this.resultSetConcurrency = resultSetConcurrency; this.resultSetHoldability = resultSetHoldability; sfStatement = new SFStatement(connection.getSfSession()); } protected void raiseSQLExceptionIfStatementIsClosed() throws SQLException { if (isClosed) { throw new SnowflakeSQLException(ErrorCode.STATEMENT_CLOSED); } } /** * Execute SQL query * * @param sql sql statement * @return ResultSet * @throws SQLException if @link{#executeQueryInternal(String, Map)} throws an exception */ @Override public ResultSet executeQuery(String sql) throws SQLException { raiseSQLExceptionIfStatementIsClosed(); return executeQueryInternal(sql, null); } /** * Execute an update statement * * @param sql sql statement * @return number of rows updated * @throws SQLException if @link{#executeUpdateInternal(String, Map)} throws exception */ @Override public int executeUpdate(String sql) throws SQLException { return (int) executeUpdateInternal(sql, null, true); } long executeUpdateInternal(String sql, Map<String, ParameterBindingDTO> parameterBindings, boolean updateQueryRequired) throws SQLException { raiseSQLExceptionIfStatementIsClosed(); /* If sql command is a staging command that has parameter binding, throw an exception because parameter binding is not supported for staging commands. */ if (StmtUtil.checkStageManageCommand(sql) != null && parameterBindings != null) { throw new SnowflakeSQLException( ErrorCode.UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API, StmtUtil.truncateSQL(sql)); } SFBaseResultSet sfResultSet; try { sfResultSet = sfStatement.execute(sql, parameterBindings, SFStatement.CallingMethod.EXECUTE_UPDATE); sfResultSet.setSession(this.connection.getSfSession()); updateCount = ResultUtil.calculateUpdateCount(sfResultSet); queryID = sfResultSet.getQueryId(); } catch (SFException ex) { throw new SnowflakeSQLException(ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } finally { if (resultSet != null) { openResultSets.add(resultSet); } resultSet = null; } if (updateCount == NO_UPDATES && updateQueryRequired) { throw new SnowflakeSQLException( ErrorCode.UNSUPPORTED_STATEMENT_TYPE_IN_EXECUTION_API, StmtUtil.truncateSQL(sql)); } return updateCount; } /** * Internal method for executing a query with bindings accepted. * * @param sql sql statement * @param parameterBindings parameters bindings * @return query result set * @throws SQLException if @link{SFStatement.execute(String)} throws exception */ ResultSet executeQueryInternal( String sql, Map<String, ParameterBindingDTO> parameterBindings) throws SQLException { SFBaseResultSet sfResultSet; try { sfResultSet = sfStatement.execute(sql, parameterBindings, SFStatement.CallingMethod.EXECUTE_QUERY); sfResultSet.setSession(this.connection.getSfSession()); } catch (SFException ex) { throw new SnowflakeSQLException(ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } if (resultSet != null) { openResultSets.add(resultSet); } resultSet = new SnowflakeResultSetV1(sfResultSet, this); return getResultSet(); } /** * Execute sql * * @param sql sql statement * @param parameterBindings a map of binds to use for this query * @return whether there is result set or not * @throws SQLException if @link{#executeQuery(String)} throws exception */ boolean executeInternal(String sql, Map<String, ParameterBindingDTO> parameterBindings) throws SQLException { raiseSQLExceptionIfStatementIsClosed(); connection.injectedDelay(); logger.debug("execute: {}", (ArgSupplier) () -> SecretDetector.maskSecrets(sql)); String trimmedSql = sql.trim(); if (trimmedSql.length() >= 20 && trimmedSql.toLowerCase().startsWith("set-sf-property")) { // deprecated: sfsql executeSetProperty(sql); return false; } SFBaseResultSet sfResultSet; try { sfResultSet = sfStatement.execute(sql, parameterBindings, SFStatement.CallingMethod.EXECUTE); sfResultSet.setSession(this.connection.getSfSession()); if (resultSet != null) { openResultSets.add(resultSet); } resultSet = new SnowflakeResultSetV1(sfResultSet, this); queryID = sfResultSet.getQueryId(); // Legacy behavior treats update counts as result sets for single- // statement execute, so we only treat update counts as update counts // if CLIENT_SFSQL is not set, or if a statement // is multi-statement if (!sfResultSet.getStatementType().isGenerateResultSet() && (!connection.getSfSession().isSfSQLMode() || sfStatement.hasChildren())) { updateCount = ResultUtil.calculateUpdateCount(sfResultSet); if (resultSet != null) { openResultSets.add(resultSet); } resultSet = null; return false; } updateCount = NO_UPDATES; return true; } catch (SFException ex) { throw new SnowflakeSQLException( ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } } /** * @return the query ID of the latest executed query */ public String getQueryID() { // return the queryID for the query executed last time return queryID; } /** * @return the query IDs of the latest executed batch queries */ public List<String> getBatchQueryIDs() { return Collections.unmodifiableList(batchQueryIDs); } /** * Execute sql * * @param sql sql statement * @return whether there is result set or not * @throws SQLException if @link{#executeQuery(String)} throws exception */ @Override public boolean execute(String sql) throws SQLException { return executeInternal(sql, null); } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { logger.debug( "public int execute(String sql, int autoGeneratedKeys)"); if (autoGeneratedKeys == Statement.NO_GENERATED_KEYS) { return execute(sql); } else { throw new SQLFeatureNotSupportedException(); } } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { logger.debug( "public boolean execute(String sql, int[] columnIndexes)"); throw new SQLFeatureNotSupportedException(); } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { logger.debug( "public boolean execute(String sql, String[] columnNames)"); throw new SQLFeatureNotSupportedException(); } /** * Batch Execute. If one of the commands in the batch failed, JDBC will * continuing processing and throw BatchUpdateException after all commands * are processed. * * @return an array of update counts * @throws SQLException if any error occurs. */ @Override public int[] executeBatch() throws SQLException { logger.debug("public int[] executeBatch()"); return executeBatchInternal(false).intArr; } /** * Batch Execute. If one of the commands in the batch failed, JDBC will * continuing processing and throw BatchUpdateException after all commands * are processed. * * @return an array of update counts * @throws SQLException if any error occurs. */ @Override public long[] executeLargeBatch() throws SQLException { logger.debug("public int[] executeBatch()"); return executeBatchInternal(true).longArr; } /** * This method will iterate through batch and provide sql and bindings to * underlying SFStatement to get result set. * <p> * Note, array binds use a different code path since only one network * roundtrip in the array bind execution case. * * @return the number of updated rows * @throws SQLException raises if statement is closed or any db error occurs */ VariableTypeArray executeBatchInternal(boolean isLong) throws SQLException { raiseSQLExceptionIfStatementIsClosed(); SQLException exceptionReturned = null; VariableTypeArray updateCounts; if (isLong) { long[] arr = new long[batch.size()]; updateCounts = new VariableTypeArray(null, arr); } else { int size = batch.size(); int[] arr = new int[size]; updateCounts = new VariableTypeArray(arr, null); } batchQueryIDs.clear(); for (int i = 0; i < batch.size(); i++) { BatchEntry b = batch.get(i); try { long cnt = this.executeUpdateInternal( b.getSql(), b.getParameterBindings(), false); if (cnt == NO_UPDATES) { // in executeBatch we set updateCount to SUCCESS_NO_INFO // for successful query with no updates cnt = SUCCESS_NO_INFO; } if (isLong) { updateCounts.longArr[i] = cnt; } else if (cnt <= Integer.MAX_VALUE) { updateCounts.intArr[i] = (int) cnt; } else { throw new SnowflakeSQLException(SqlState.NUMERIC_VALUE_OUT_OF_RANGE, ErrorCode.EXECUTE_BATCH_INTEGER_OVERFLOW.getMessageCode(), i); } batchQueryIDs.add(queryID); } catch (SQLException e) { exceptionReturned = exceptionReturned == null ? e : exceptionReturned; if (isLong) { updateCounts.longArr[i] = (long) EXECUTE_FAILED; } else { updateCounts.intArr[i] = EXECUTE_FAILED; } } } if (exceptionReturned != null && isLong) { throw new BatchUpdateException(exceptionReturned.getLocalizedMessage(), exceptionReturned.getSQLState(), exceptionReturned.getErrorCode(), updateCounts.longArr, exceptionReturned); } else if (exceptionReturned != null) { throw new BatchUpdateException(exceptionReturned.getLocalizedMessage(), exceptionReturned.getSQLState(), exceptionReturned.getErrorCode(), updateCounts.intArr, exceptionReturned); } return updateCounts; } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { logger.debug( "public int executeUpdate(String sql, int autoGeneratedKeys)"); if (autoGeneratedKeys == Statement.NO_GENERATED_KEYS) { return executeUpdate(sql); } else { throw new SQLFeatureNotSupportedException(); } } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { logger.debug( "public int executeUpdate(String sql, int[] columnIndexes)"); throw new SQLFeatureNotSupportedException(); } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { logger.debug( "public int executeUpdate(String sql, String[] columnNames)"); throw new SQLFeatureNotSupportedException(); } @Override public Connection getConnection() throws SQLException { logger.debug("public Connection getConnection()"); raiseSQLExceptionIfStatementIsClosed(); return connection; } @Override public int getFetchDirection() throws SQLException { logger.debug("public int getFetchDirection()"); raiseSQLExceptionIfStatementIsClosed(); return ResultSet.FETCH_FORWARD; } @Override public int getFetchSize() throws SQLException { logger.debug("public int getFetchSize()"); raiseSQLExceptionIfStatementIsClosed(); return fetchSize; } @Override public ResultSet getGeneratedKeys() throws SQLException { logger.debug("public ResultSet getGeneratedKeys()"); raiseSQLExceptionIfStatementIsClosed(); return new SnowflakeResultSetV1.EmptyResultSet(); } @Override public int getMaxFieldSize() throws SQLException { logger.debug("public int getMaxFieldSize()"); raiseSQLExceptionIfStatementIsClosed(); return maxFieldSize; } @Override public int getMaxRows() throws SQLException { logger.debug("public int getMaxRows()"); raiseSQLExceptionIfStatementIsClosed(); return maxRows; } @Override public boolean getMoreResults() throws SQLException { logger.debug("public boolean getMoreResults()"); return getMoreResults(Statement.CLOSE_CURRENT_RESULT); } @Override public boolean getMoreResults(int current) throws SQLException { logger.debug("public boolean getMoreResults(int current)"); raiseSQLExceptionIfStatementIsClosed(); // clean up the current result set, if it exists if (resultSet != null && (current == Statement.CLOSE_CURRENT_RESULT || current == Statement.CLOSE_ALL_RESULTS)) { resultSet.close(); } boolean hasResultSet = sfStatement.getMoreResults(current); SFBaseResultSet sfResultSet = sfStatement.getResultSet(); if (hasResultSet) // result set returned { sfResultSet.setSession(this.connection.getSfSession()); if (resultSet != null) { openResultSets.add(resultSet); } resultSet = new SnowflakeResultSetV1(sfResultSet, this); updateCount = NO_UPDATES; return true; } else if (sfResultSet != null) // update count returned { if (resultSet != null) { openResultSets.add(resultSet); } resultSet = null; try { updateCount = ResultUtil.calculateUpdateCount(sfResultSet); } catch (SFException ex) { throw new SnowflakeSQLException(ex); } return false; } else // no more results { updateCount = NO_UPDATES; return false; } } @Override public int getQueryTimeout() throws SQLException { logger.debug("public int getQueryTimeout()"); raiseSQLExceptionIfStatementIsClosed(); return this.queryTimeout; } @Override public ResultSet getResultSet() throws SQLException { logger.debug("public ResultSet getResultSet()"); raiseSQLExceptionIfStatementIsClosed(); return resultSet; } @Override public int getResultSetConcurrency() throws SQLException { logger.debug("public int getResultSetConcurrency()"); raiseSQLExceptionIfStatementIsClosed(); return resultSetConcurrency; } @Override public int getResultSetHoldability() throws SQLException { logger.debug("public int getResultSetHoldability()"); raiseSQLExceptionIfStatementIsClosed(); return resultSetHoldability; } @Override public int getResultSetType() throws SQLException { logger.debug("public int getResultSetType()"); raiseSQLExceptionIfStatementIsClosed(); return this.resultSetType; } @Override public int getUpdateCount() throws SQLException { logger.debug("public int getUpdateCount()"); return (int) getUpdateCountIfDML(); } @Override public long getLargeUpdateCount() throws SQLException { logger.debug("public long getLargeUpdateCount()"); return getUpdateCountIfDML(); } private long getUpdateCountIfDML() throws SQLException { raiseSQLExceptionIfStatementIsClosed(); if (updateCount != -1 && sfStatement.getResultSet().getStatementType().isDML()) { return updateCount; } return -1; } @Override public SQLWarning getWarnings() throws SQLException { logger.debug("public SQLWarning getWarnings()"); raiseSQLExceptionIfStatementIsClosed(); return sqlWarnings; } @Override public boolean isClosed() throws SQLException { logger.debug("public boolean isClosed()"); return isClosed; // no exception } @Override public boolean isPoolable() throws SQLException { logger.debug("public boolean isPoolable()"); raiseSQLExceptionIfStatementIsClosed(); return poolable; } @Override public void setCursorName(String name) throws SQLException { logger.debug("public void setCursorName(String name)"); throw new SQLFeatureNotSupportedException(); } @Override public void setEscapeProcessing(boolean enable) throws SQLException { logger.debug("public void setEscapeProcessing(boolean enable)"); // NOTE: We could raise an exception here, because not implemented // but it may break the existing applications. For now returning nothnig. // we should revisit. raiseSQLExceptionIfStatementIsClosed(); } @Override public void setFetchDirection(int direction) throws SQLException { logger.debug("public void setFetchDirection(int direction)"); raiseSQLExceptionIfStatementIsClosed(); if (direction != ResultSet.FETCH_FORWARD) { throw new SQLFeatureNotSupportedException(); } } @Override public void setFetchSize(int rows) throws SQLException { logger.debug("public void setFetchSize(int rows), rows={}", rows); raiseSQLExceptionIfStatementIsClosed(); fetchSize = rows; } @Override public void setMaxFieldSize(int max) throws SQLException { logger.debug("public void setMaxFieldSize(int max)"); throw new SQLFeatureNotSupportedException(); } @Override public void setMaxRows(int max) throws SQLException { logger.debug("public void setMaxRows(int max)"); raiseSQLExceptionIfStatementIsClosed(); this.maxRows = max; try { if (this.sfStatement != null) { this.sfStatement.addProperty("rows_per_resultset", max); } } catch (SFException ex) { throw new SnowflakeSQLException( ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } } @Override public void setPoolable(boolean poolable) throws SQLException { logger.debug("public void setPoolable(boolean poolable)"); raiseSQLExceptionIfStatementIsClosed(); if (poolable) { throw new SQLFeatureNotSupportedException(); } this.poolable = poolable; } /** * Sets a parameter at the statement level. Used for internal testing. * * @param name parameter name. * @param value parameter value. * @throws SQLException if any SQL error occurs. */ void setParameter(String name, Object value) throws SQLException { logger.debug("public void setParameter"); try { if (this.sfStatement != null) { this.sfStatement.addProperty(name, value); } } catch (SFException ex) { throw new SnowflakeSQLException(ex); } } @Override public void setQueryTimeout(int seconds) throws SQLException { logger.debug("public void setQueryTimeout(int seconds)"); raiseSQLExceptionIfStatementIsClosed(); this.queryTimeout = seconds; try { if (this.sfStatement != null) { this.sfStatement.addProperty("query_timeout", seconds); } } catch (SFException ex) { throw new SnowflakeSQLException( ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { logger.debug("public boolean isWrapperFor(Class<?> iface)"); return iface.isInstance(this); } @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { logger.debug("public <T> T unwrap(Class<T> iface)"); if (!iface.isInstance(this)) { throw new SQLException( this.getClass().getName() + " not unwrappable from " + iface .getName()); } return (T) this; } @Override public void closeOnCompletion() throws SQLException { logger.debug("public void closeOnCompletion()"); throw new SQLFeatureNotSupportedException(); } @Override public boolean isCloseOnCompletion() throws SQLException { logger.debug("public boolean isCloseOnCompletion()"); throw new SQLFeatureNotSupportedException(); } @Override public void close() throws SQLException { close(true); } public void close(boolean removeClosedStatementFromConnection) throws SQLException { logger.debug("public void close()"); // No exception is raised even if the statement is closed. if (resultSet != null) { resultSet.close(); resultSet = null; } isClosed = true; batch.clear(); // also make sure to close all created resultSets from this statement synchronized (openResultSets) { for (ResultSet rs : openResultSets) { if (rs != null && !rs.isClosed()) { if (rs.isWrapperFor(SnowflakeResultSetV1.class)) { rs.unwrap(SnowflakeResultSetV1.class).close(false); } else { rs.close(); } } } openResultSets.clear(); } sfStatement.close(); if (removeClosedStatementFromConnection) { connection.removeClosedStatement(this); } } @Override public void cancel() throws SQLException { logger.debug("public void cancel()"); raiseSQLExceptionIfStatementIsClosed(); try { sfStatement.cancel(); } catch (SFException ex) { throw new SnowflakeSQLException(ex, ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } } @Override public void clearWarnings() throws SQLException { logger.debug("public void clearWarnings()"); raiseSQLExceptionIfStatementIsClosed(); sqlWarnings = null; } @Override public void addBatch(String sql) throws SQLException { logger.debug("public void addBatch(String sql)"); raiseSQLExceptionIfStatementIsClosed(); batch.add(new BatchEntry(sql, null)); } @Override public void clearBatch() throws SQLException { logger.debug("public void clearBatch()"); raiseSQLExceptionIfStatementIsClosed(); batch.clear(); } private void executeSetProperty(final String sql) { logger.debug("setting property"); // tokenize the sql String[] tokens = sql.split("\\s+"); if (tokens.length < 2) { return; } if ("tracing".equalsIgnoreCase(tokens[1])) { if (tokens.length >= 3) { /*connection.tracingLevel = Level.parse(tokens[2].toUpperCase()); if (connection.tracingLevel != null) { Logger snowflakeLogger = Logger.getLogger("net.snowflake"); snowflakeLogger.setLevel(connection.tracingLevel); }*/ } } else { this.sfStatement.executeSetProperty(sql); } } public SFStatement getSfStatement() { return sfStatement; } public void removeClosedResultSet(ResultSet rs) { openResultSets.remove(rs); } final class BatchEntry { private final String sql; private final Map<String, ParameterBindingDTO> parameterBindings; BatchEntry(String sql, Map<String, ParameterBindingDTO> parameterBindings) { this.sql = sql; this.parameterBindings = parameterBindings; } public String getSql() { return sql; } public Map<String, ParameterBindingDTO> getParameterBindings() { return parameterBindings; } } }
package net.timbusproject.extractors.helpers; import java.io.InputStream; import java.io.IOException; import java.util.UUID; public class MachineID { String hostid, hostname; private static String exec(String command) throws IOException { Process p = Runtime.getRuntime().exec(command); String stdout = drain(p.getInputStream()); String stderr = drain(p.getErrorStream()); return stdout; // TODO: return stderr also... } private static String drain(InputStream in) throws IOException { int b = -1; StringBuilder buf = new StringBuilder(); while ((b = in.read()) != -1) buf.append((char) b); return buf.toString(); } public MachineID() { try { this.hostname = exec("hostname").trim(); this.hostid = exec("hostid").trim(); } catch (Exception E) { } } public MachineID(String hostid, String hostname) { this.hostid = hostid; this.hostname = hostname; } public String getXRI() { return "xri://" + getIDString(); } public String getXRN() { return "xrn://" + getIDString(); } private String getIDString() { return "+machine?+hostid=" + hostid + "/+hostname=" + hostname; } public String toString() { return getXRI(); } public String getUUID() { byte[] id = (hostname + hostid).getBytes(); byte[] id_with_namespace; id_with_namespace = new byte[id.length + 16]; System.arraycopy(id, 0, id_with_namespace, 16, id.length); return "urn:uuid:" + UUID.nameUUIDFromBytes(id_with_namespace); } public static void main(String args[]) { System.out.println(new MachineID()); } }
package nl.hsac.fitnesse.junit; import fitnesse.components.PluginsClassLoader; import fitnesse.junit.JUnitHelper; import fitnesse.junit.JUnitXMLTestListener; import fitnesse.junit.JavaFormatter; import java.io.File; import java.io.IOException; /** * Helper to run Fitnesse tests from JUnit tests. */ public class FitnesseFromJUnitRunner { private boolean loadPlugins = true; private String fitnesseRoot = "."; private String xmlOutputPath = "../target/failsafe-reports"; private String htmlOutputPath = "../target/fitnesse-results"; /** * Runs a suite of Fitnesse tests. One JUnit test will be reported for each page executed. * @param suiteName name of suite to run * @throws Exception */ public void assertSuitePasses(String suiteName) throws Exception { if (loadPlugins) { loadPlugins(); } JUnitXMLTestListener resultsListener = new JUnitXMLTestListener(xmlOutputPath); JUnitHelper jUnitHelper = new JUnitHelper(fitnesseRoot, htmlOutputPath, resultsListener); try { jUnitHelper.assertSuitePasses(suiteName); } finally { addFilesToHtmlOutput(); } } protected void addFilesToHtmlOutput() throws IOException { copyResourceToHtmlOutput("css/fitnesse.css"); copyResourceToHtmlOutput("css/fitnesse_pages.css"); copyResourceToHtmlOutput("css/fitnesse_wiki.css"); copyResourceToHtmlOutput("css/fitnesse_straight.css"); } protected void copyResourceToHtmlOutput(String resource) throws IOException { String src = "/fitnesse/resources/" + resource; String dest = htmlOutputPath + "/" + resource; File target = new File(dest); JavaFormatter.FileCopier.copy(src, target); } /** * Adds Fitnesse plugins to classpath. */ protected void loadPlugins() { try { new PluginsClassLoader().addPluginsToClassLoader(); } catch (Exception e) { throw new RuntimeException("Unable to adds plugins to classpath", e); } } /** * @return whether Fitnesse's plugins will be added to classpath of test run. */ public boolean isLoadPlugins() { return loadPlugins; } /** * @param loadPlugins whether Fitnesse's plugins will be added to classpath of test run. */ public void setLoadPlugins(boolean loadPlugins) { this.loadPlugins = loadPlugins; } /** * @return (relative) location of Fitnesse's wiki pages to current directory of JVM. */ public String getFitnesseRoot() { return fitnesseRoot; } /** * @param fitnesseRoot (relative) location of Fitnesse's wiki pages to current directory of JVM. */ public void setFitnesseRoot(String fitnesseRoot) { this.fitnesseRoot = fitnesseRoot; } /** * @return (relative) location where XML files will be written describing results of Fitnesse tests. */ public String getXmlOutputPath() { return xmlOutputPath; } /** * @param xmlOutputPath (relative) location where XML files will be written describing results of Fitnesse tests. */ public void setXmlOutputPath(String xmlOutputPath) { this.xmlOutputPath = xmlOutputPath; } /** * @return (relative) location where HTML files will be written describing results of Fitnesse tests (similar to * output of test execution from Wiki). */ public String getHtmlOutputPath() { return htmlOutputPath; } /** * @param htmlOutputPath (relative) location where HTML files will be written describing results of Fitnesse tests * (similar to output of test execution from Wiki). */ public void setHtmlOutputPath(String htmlOutputPath) { this.htmlOutputPath = htmlOutputPath; } }
package nl.vu.datalayer.hbase.sail; import info.aduna.iteration.CloseableIteration; import info.aduna.iteration.CloseableIteratorIteration; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import nl.vu.datalayer.hbase.HBaseClientSolution; import nl.vu.datalayer.hbase.HBaseFactory; import nl.vu.datalayer.hbase.connection.HBaseConnection; import nl.vu.datalayer.hbase.schema.HBHexastoreSchema; import org.openrdf.model.Namespace; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.BNodeImpl; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.Dataset; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.Var; import org.openrdf.query.impl.MapBindingSet; import org.openrdf.query.impl.TupleQueryResultImpl; import org.openrdf.sail.NotifyingSailConnection; import org.openrdf.sail.SailException; import org.openrdf.sail.helpers.NotifyingSailConnectionBase; import org.openrdf.sail.helpers.SailBase; import org.openrdf.sail.memory.MemoryStore; public class HBaseSailConnection extends NotifyingSailConnectionBase { MemoryStore memStore; NotifyingSailConnection memStoreCon; HBaseClientSolution hbase; //Builder to write the query to bit by bit StringBuilder queryString = new StringBuilder(); public HBaseSailConnection(SailBase sailBase) { super(sailBase); // System.out.println("SailConnection created"); hbase = ((HBaseSail)sailBase).getHBase(); memStore = new MemoryStore(); try { memStore.initialize(); memStoreCon = memStore.getConnection(); } catch (SailException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void addStatementInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { ArrayList<Statement> myList = new ArrayList(); Statement s = new StatementImpl(arg0, arg1, arg2); myList.add(s); // TODO: update method for adding quads // try { // HBaseClientSolution sol = HBaseFactory.getHBaseSolution(HBHexastoreSchema.SCHEMA_NAME, con, myList); // sol.schema.create(); // sol.util.populateTables(myList); // catch (Exception e) { // e.printStackTrace(); // // TODO error handling } @Override protected void clearInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void clearNamespacesInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void closeInternal() throws SailException { memStoreCon.close(); } @Override protected void commitInternal() throws SailException { // TODO Auto-generated method stub } @Override protected CloseableIteration<? extends Resource, SailException> getContextIDsInternal() throws SailException { // TODO Auto-generated method stub return null; } @Override protected String getNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub return null; } @Override protected CloseableIteration<? extends Namespace, SailException> getNamespacesInternal() throws SailException { // TODO Auto-generated method stub return null; } protected CloseableIteration<? extends Statement, SailException> getStatementsInternal( Resource arg0, URI arg1, Value arg2, boolean arg3, Set<URI> contexts) throws SailException { try { // String s = null; // String p = null; // String o = null; ArrayList<Value> g = new ArrayList(); // if (arg0 != null) { // s = arg0.stringValue(); // else { // if (arg1 != null) { // p = arg1.stringValue(); // else { // if (arg2 != null) { // o = arg2.stringValue(); // else { if (contexts != null && contexts.size() != 0) { for (Resource r : contexts) { g.add(r); } } else { g.add(null); } ArrayList<Statement> myList = new ArrayList(); for (Value graph : g) { System.out.println("HBase Query: " + arg0 + " - " + arg1 + " - " + arg2 + " - " + graph); Value []query = {arg0, arg1, arg2, graph}; ArrayList<ArrayList<Value>> result = hbase.util.getResults(query); // for (ArrayList<String> tr : triples) { // for (String st : tr) { // System.out.print(st + " "); // System.out.print("\n"); // System.out.println("Raw triples: " + triples); myList.addAll(reconstructTriples(result, query)); } // System.out.println("Triples retrieved:"); // System.out.println(myList.toString()); Iterator it = myList.iterator(); CloseableIteration<Statement, SailException> ci = new CloseableIteratorIteration<Statement, SailException>(it); return ci; } catch (Exception e) { Exception ex = new SailException("HBase connection error: " + e.getMessage()); try { throw ex; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return null; } protected ArrayList<Statement> reconstructTriples(ArrayList<ArrayList<Value>> result, Value[] triple) throws SailException { ArrayList<Statement> list = new ArrayList(); for (ArrayList<Value> arrayList : result) { int index = 0; Resource s = null; URI p = null; Value o = null; Resource c = null; for (Value value : arrayList) { if (index == 0) { // s = (Resource)getSubject(value); s = (Resource)value; } else if (index == 1) { // p = (URI) getPredicate(value); p = (URI)value; } else if (index == 2) { // o = getObject(value); o = value; } else { // c = (Resource)getContext(value); c = (Resource)value; Statement statement = new ContextStatementImpl(s, p, o, c); list.add(statement); } index++; } } return list; } Value getSubject(String s) { System.out.println("SUBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } return new URIImpl(s); } Value getPredicate(String s) { System.out.println("PREDICATE: " + s); return new URIImpl(s); } Value getObject(String s) { System.out.println("OBJECT: " + s); if (s.startsWith("_")) { return new BNodeImpl(s.substring(2)); } else if (s.startsWith("\"")) { String literal = ""; String language = ""; String datatype = ""; for (int i = 1; i < s.length(); i++) { while (s.charAt(i) != '"') { // read literal value literal += s.charAt(i); if (s.charAt(i) == '\\') { i++; literal += s.charAt(i); } i++; if (i == s.length()) { // EOF exception } } // System.out.println(literal); // charAt(i) = '"', read next char i++; if (s.charAt(i) == '@') { // read language // System.out.println("reading language"); i++; while (i < s.length()) { language += s.charAt(i); i++; } // System.out.println(language); return new LiteralImpl(literal, language); } else if (s.charAt(i) == '^') { // read datatype i++; // check for second '^' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '^') { // incorrect formatting exception } i++; // check for '<' if (i == s.length()) { // EOF exception } else if (s.charAt(i) != '<') { // incorrect formatting exception } i++; while (s.charAt(i) != '>') { datatype += s.charAt(i); i++; if (i == s.length()) { // EOF exception } } // System.out.println(datatype); return new LiteralImpl(literal, new URIImpl(datatype)); } else { return new LiteralImpl(literal); } } } Value object; try { object = new URIImpl(s); } catch (Exception e) { object = new LiteralImpl(s); } return object; } Value getContext(String s) { System.out.println("GRAPH: " + s); return new URIImpl(s); } @Override protected void removeNamespaceInternal(String arg0) throws SailException { // TODO Auto-generated method stub } @Override protected void removeStatementsInternal(Resource arg0, URI arg1, Value arg2, Resource... arg3) throws SailException { // TODO Auto-generated method stub } @Override protected void rollbackInternal() throws SailException { // TODO Auto-generated method stub } @Override protected void setNamespaceInternal(String arg0, String arg1) throws SailException { // TODO Auto-generated method stub } @Override protected long sizeInternal(Resource... arg0) throws SailException { // TODO Auto-generated method stub return 0; } @Override protected void startTransactionInternal() throws SailException { // TODO Auto-generated method stub } /** * This functions returns a List of all RDF statements in HBase * that are needed in the query. * * @param arg0 * @return * @throws SailException */ protected ArrayList<Statement> evaluateInternal(TupleExpr arg0, Dataset context) throws SailException { ArrayList<Statement> result = new ArrayList(); try { ArrayList<ArrayList<Var>> statements = HBaseQueryVisitor.convertToStatements(arg0, null, null); // System.out.println("StatementPatterns: " + statements.size()); // ArrayList<Var> contexts = HBaseQueryVisitor.getContexts(arg0); // ArrayList<Resource> cons = new ArrayList(); // Iterator qt = contexts.iterator(); // while (qt.hasNext()) { // Var context = (Var)qt.next(); // if (context != null) { // System.out.println(context.toString()); Set<URI> contexts; try { contexts = context.getNamedGraphs(); } catch (Exception e) { contexts = new HashSet(); } if (contexts != null && contexts.size() != 0) { for (URI gr : contexts) { System.out.println("CONTEXT FOUND: " + gr.stringValue()); } } Iterator it = statements.iterator(); while (it.hasNext()) { ArrayList<Var> sp = (ArrayList<Var>)it.next(); // System.out.println("CONTEXTS:"); // if (contexts != null) { // for (Var con : contexts) { // System.out.println("CONTEXT: " + con.toString()); // // cons.add((Resource)new URIImpl(con.)); Resource subj = null; URI pred = null; Value obj = null; Iterator jt = sp.iterator(); int index = 0; while (jt.hasNext()) { Var var = (Var)jt.next(); if (index == 0) { if (var.hasValue()) { subj = (Resource)getSubject(var.getValue().stringValue()); } else if (var.isAnonymous()) { subj = (Resource)getSubject(var.getName()); } } else if (index == 1) { if (var.hasValue()) { pred = (URI)getPredicate(var.getValue().stringValue()); } } else { if (var.hasValue()) { obj = (Value)getObject(var.getValue().stringValue()); } else if (var.isAnonymous()) { obj = (Value)getObject(var.getName()); } } index += 1; } CloseableIteration ci = getStatementsInternal(subj, pred, obj, false, contexts); while (ci.hasNext()) { Statement statement = (Statement)ci.next(); result.add(statement); } } } catch (Exception e) { throw new SailException(e); } return result; } /** * This function retrieves all the triples from HBase that * match with StatementPatterns in the SPARQL query, without * executing the SPARQL query on them. */ @Override protected CloseableIteration<? extends BindingSet, QueryEvaluationException> evaluateInternal( TupleExpr arg0, Dataset arg1, BindingSet arg2, boolean arg3) throws SailException { return null; } /** * This function retrieves the relevant triples from HBase, * loads them into an in-memory store, then evaluates the SPARQL query on them. * * @param tupleExpr * @param dataset * @param bindings * @param includeInferred * @return * @throws SailException */ public TupleQueryResult query(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { // System.out.println("Evaluating query"); // System.out.println("EVALUATE:" + tupleExpr.toString()); try { ArrayList<Statement> statements = evaluateInternal(tupleExpr, dataset); System.out.println("POST EVAL STATEMENTS"); // System.out.println("Statements retrieved: " + statements.size()); Iterator it = statements.iterator(); while (it.hasNext()) { Statement statement = (Statement)it.next(); Resource[] context = {new URIImpl("http://hbase.sail.vu.nl")}; memStoreCon.addStatement(statement.getSubject(), statement.getPredicate(), statement.getObject(), context); } CloseableIteration<? extends BindingSet, QueryEvaluationException> ci = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); CloseableIteration<? extends BindingSet, QueryEvaluationException> cj = memStoreCon.evaluate(tupleExpr, dataset, bindings, includeInferred); List<String> bindingList = new ArrayList<String>(); int index = 0; while (ci.hasNext()) { index++; BindingSet bs = (BindingSet)ci.next(); // System.out.println("Binding size(" + index + "): " + bs.getBindingNames().size()); Set<String> localBindings = bs.getBindingNames(); Iterator jt = localBindings.iterator(); while (jt.hasNext()) { String binding = (String)jt.next(); if (bindingList.contains(binding) == false) { bindingList.add(binding); // System.out.println("Added binding: " + binding); } } } // System.out.println("Results retrieved from memory store: " + index); // System.out.println("Bindings retrieved from memory store: " + bindingList.size()); TupleQueryResult result = new TupleQueryResultImpl(bindingList, cj); // int ressize = 0; // while (result.hasNext()) { // BindingSet binding = result.next(); // System.out.println("x = " + binding.getValue("x").stringValue()); // ressize += 1; // System.out.println("TupleQueryResult size: " + ressize); return result; } catch (SailException e) { e.printStackTrace(); throw e; } catch (QueryEvaluationException e) { // TODO Auto-generated catch block throw new SailException(e); } } @Override protected CloseableIteration<? extends Statement, SailException> getStatementsInternal( Resource arg0, URI arg1, Value arg2, boolean arg3, Resource... arg4) throws SailException { // TODO Auto-generated method stub return null; } }
package no.ntnu.okse.protocol.wsn; import java.io.*; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.google.common.io.ByteStreams; import no.ntnu.okse.Application; import no.ntnu.okse.core.CoreService; import no.ntnu.okse.core.messaging.Message; import no.ntnu.okse.core.subscription.SubscriptionService; import no.ntnu.okse.protocol.AbstractProtocolServer; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.util.InputStreamContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.xml.XmlConfiguration; import org.ntnunotif.wsnu.base.internal.ServiceConnection; import org.ntnunotif.wsnu.base.net.NuNamespaceContextResolver; import org.ntnunotif.wsnu.base.util.InternalMessage; import org.ntnunotif.wsnu.base.util.RequestInformation; import org.ntnunotif.wsnu.services.general.WsnUtilities; import org.oasis_open.docs.wsn.b_2.NotificationMessageHolderType; import org.oasis_open.docs.wsn.b_2.Notify; import org.oasis_open.docs.wsn.b_2.TopicExpressionType; import sun.net.www.http.ChunkedInputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.XMLConstants; import javax.xml.namespace.QName; public class WSNotificationServer extends AbstractProtocolServer { // Runstate variables private static boolean _invoked, _running; // Path to internal configuration file on classpath private static final String wsnInternalConfigFile = "/config/wsnserver.xml"; // Internal Default Values private static final String DEFAULT_HOST = "0.0.0.0"; private static final int DEFAULT_PORT = 61000; private static final Long DEFAULT_CONNECTION_TIMEOUT = 5L; private static final Integer DEFAULT_HTTP_CLIENT_DISPATCHER_POOL_SIZE = 50; private static final String DEFAULT_MESSAGE_CONTENT_WRAPPER_NAME = "Content"; // Flag and defaults for operation behind NAT private static boolean behindNAT = false; private static String publicWANHost = "0.0.0.0"; private static Integer publicWANPort = 61000; // HTTP Client fields private static Long connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; private static Integer clientPoolSize = DEFAULT_HTTP_CLIENT_DISPATCHER_POOL_SIZE; // The singleton containing the WSNotificationServer instance private static WSNotificationServer _singleton; // Non-XMl Content Wrapper Name private static String contentWrapperElementName = DEFAULT_MESSAGE_CONTENT_WRAPPER_NAME; // Instance fields private Server _server; private WSNRequestParser _requestParser; private WSNCommandProxy _commandProxy; private final ArrayList<Connector> _connectors = new ArrayList(); private HttpClient _client; private HttpHandler _handler; private HashSet<ServiceConnection> _services; private ExecutorService clientPool; private Properties config; /** * Empty constructor, uses internal defaults or provided from config file */ private WSNotificationServer() { // Check config file config = Application.readConfigurationFiles(); String configHost = config.getProperty("WSN_HOST", DEFAULT_HOST); Integer configPort = null; try { configPort = Integer.parseInt(config.getProperty("WSN_PORT", Integer.toString(DEFAULT_PORT))); } catch (NumberFormatException e) { log.error("Failed to parse WSN Port from config file! Using default: " + DEFAULT_PORT); } // Call init with what the results were this.init(configHost, configPort); _running = false; _invoked = true; } /** * Constructor that takes in a port that the WSNServer jetty instance should * listen to. * <p> * @param host A string representing the host the WSNServer should bind to * @param port An integer representing the port the WSNServer should bind to. */ private WSNotificationServer(String host, Integer port) { // Check config file config = Application.readConfigurationFiles(); this.init(host, port); } /** * Factory method providing an instance of WSNotificationServer, adhering to the * singleton pattern. (Using default port from config file.) * <p> * @return: The WSNotification instance. */ public static WSNotificationServer getInstance() { if (!_invoked) _singleton = new WSNotificationServer(); return _singleton; } /** * Factory method providing an instance of WSNotificationServer, adhering to the * singleton pattern. This method allows overriding of host and port defined in the * config file. * * @param host A string representing the hostname the server should bind to * @param port An integer representing the port WSNServer should bind to. * * @return: The WSNotification instance. */ public static WSNotificationServer getInstance(String host, Integer port) { if (!_invoked) _singleton = new WSNotificationServer(host, port); return _singleton; } /** * Initialization method that reads the wsnserver.xml configuration file and constructs * a jetty server instance. * * @param port: An integer representing the port WSNServer should bind to. */ protected void init(String host, Integer port) { log = Logger.getLogger(WSNotificationServer.class.getName()); // Set the servertype protocolServerType = "WSNotification"; // Declare HttpClient field _client = null; // Attempt to fetch connection timeout from settings, otherwise use 5 seconds as default try { connectionTimeout = Long.parseLong(config.getProperty("WSN_CONNECTION_TIMEOUT", connectionTimeout.toString())); } catch (NumberFormatException e) { log.error("Failed to parse WSN Connection Timeout, using default: " + connectionTimeout); } // Attempt to fetch the HTTP Client pool size from settings, otherwise use default try { clientPoolSize = Integer.parseInt(config.getProperty("WSN_POOL_SIZE", Integer.toString(DEFAULT_HTTP_CLIENT_DISPATCHER_POOL_SIZE))); } catch (NumberFormatException e) { log.error("Failed to parse WSN Client pool size from config file! Using default: " + DEFAULT_HTTP_CLIENT_DISPATCHER_POOL_SIZE); } clientPool = Executors.newFixedThreadPool(clientPoolSize); // If a default message content wrapper name is specified in config, set it, otherwise use default contentWrapperElementName = config.getProperty("WSN_MESSAGE_CONTENT_ELEMENT_NAME", DEFAULT_MESSAGE_CONTENT_WRAPPER_NAME); if (contentWrapperElementName.contains("<") || contentWrapperElementName.contains(">")) { log.warn("Non-XML message payload element wrapper name cannot contain XML element characters (< or >)," + " using default: " + DEFAULT_MESSAGE_CONTENT_WRAPPER_NAME); contentWrapperElementName = DEFAULT_MESSAGE_CONTENT_WRAPPER_NAME; } // If we have host or port provided, set them, otherwise use internal defaults this.port = port == null ? DEFAULT_PORT : port; this.host = host == null ? DEFAULT_HOST : host; /* Check if config file specifies that we are behind NAT, and update the provided WAN IP and PORT */ // Check for use NAT flag if (config.getProperty("WSN_USES_NAT", "false").equalsIgnoreCase("true")) behindNAT = true; else behindNAT = false; // Check for WAN_HOST publicWANHost = config.getProperty("WSN_WAN_HOST", publicWANHost); // Check for WAN_PORT try { publicWANPort = Integer.parseInt(config.getProperty("WSN_WAN_PORT", publicWANPort.toString())); } catch (NumberFormatException e) { log.error("Failed to parse WSN WAN Port, using default: " + publicWANPort); } // Declare configResource (Fetched from classpath as a Resource from system) Resource configResource; try { // Try to parse the configFile for WSNServer to set up the Server instance configResource = Resource.newSystemResource(wsnInternalConfigFile); XmlConfiguration config = new XmlConfiguration(configResource.getInputStream()); this._server = (Server)config.configure(); // Remove the xmlxonfig connector this._server.removeConnector(this._server.getConnectors()[0]); // Add a the serverconnector log.debug("Adding WSNServer connector"); this.addStandardConnector(this.host, this.port); // Initialize the RequestParser for WSNotification this._requestParser = new WSNRequestParser(this); // Initialize the collection of ServiceConnections this._services = new HashSet<>(); // Initialize and set the HTTPHandler for the Server instance HttpHandler handler = new WSNotificationServer.HttpHandler(); this._server.setHandler(handler); log.debug("XMLConfig complete, server instanciated."); } catch (Exception e) { log.error("Unable to start WSNotificationServer: " + e.getMessage()); } } /** * The primary boot method for starting a WSNServer instance. Will only perform actions if the * server instance is not already running. * <p> * Initializes a HttpClient, and starts it. Also adds predefined connectors to the jetty server * instance. Constructs a new serverThread and starts the jetty server instance in this new thread. * </p> */ public void boot() { log.info("Booting WSNServer."); if (!_running) { try { // Initialize a plain HttpClient this._client = new HttpClient(); // Turn off following HTTP 30x redirects for the client this._client.setFollowRedirects(false); this._client.start(); log.info("Started WSNServer HTTPClient"); // For all registered connectors in WSNotificationServer, add these to the Jetty Server this._connectors.stream().forEach(c -> this._server.addConnector(c)); /* OKSE custom WS-Nu web services */ // Initialize the CommandProxy WSNCommandProxy broker = new WSNCommandProxy(); _commandProxy = broker; // Initialize the WSN SubscriptionManager and PublisherRegistrationManager WSNSubscriptionManager subscriptionManager = new WSNSubscriptionManager(); WSNRegistrationManager registrationManager = new WSNRegistrationManager(); // Add listener support from the OKSE SubscriptionService SubscriptionService.getInstance().addSubscriptionChangeListener(subscriptionManager); SubscriptionService.getInstance().addPublisherChangeListener(registrationManager); // QuickBuild the broker broker.quickBuild("broker", this._requestParser); // QuickBuild the WSN SubManager subscriptionManager.quickBuild("subscriptionManager", this._requestParser); subscriptionManager.initCoreSubscriptionService(SubscriptionService.getInstance()); // QuickBuild the WSN PubRegManager registrationManager.quickBuild("registrationManager", this._requestParser); registrationManager.initCoreSubscriptionService(SubscriptionService.getInstance()); // Register the WSN managers to the command proxy (proxied broker) broker.setSubscriptionManager(subscriptionManager); broker.setRegistrationManager(registrationManager); // Create a new thread for the Jetty Server to run in this._serverThread = new Thread(() -> { this.run(); }); this._serverThread.setName("WSNServer"); // Start the Jetty Server this._serverThread.start(); WSNotificationServer._running = true; log.info("WSNServer Thread started successfully."); } catch (Exception e) { totalErrors.incrementAndGet(); log.trace(e.getStackTrace()); } } } /** * This interface method should contain the main run loop initialization */ @Override public void run() { try { WSNotificationServer.this._server.start(); WSNotificationServer.this._server.join(); } catch (Exception serverError) { totalErrors.incrementAndGet(); log.trace(serverError.getStackTrace()); } } /** * Fetch the HashSet containing all WebServices registered to the protocol server * @return A HashSet of ServiceConnections for all the registered web services. */ public HashSet<ServiceConnection> getServices() { return _services; } /** * This method stops the execution of the WSNotificationServer instance. */ @Override public void stopServer() { try { log.info("Stopping WSNServer..."); // Removing all subscribers _commandProxy.getAllRecipients().forEach(s -> { _commandProxy.getProxySubscriptionManager().removeSubscriber(s); }); // Removing all publishers _commandProxy.getProxyRegistrationManager().getAllPublishers().forEach(p -> { _commandProxy.getProxyRegistrationManager().removePublisher(p); }); // Stop the HTTP Client this._client.stop(); // Stop the ServerConnector this._server.stop(); this._serverThread = null; // Reset flags this._singleton = null; this._invoked = false; log.info("WSNServer Client and ServerThread stopped"); } catch (Exception e) { totalErrors.incrementAndGet(); log.trace(e.getStackTrace()); } } /** * Fetches the specified String representation of the Protocol that this ProtocolServer handles. * @return A string representing the name of the protocol that this ProtocolServer handles. */ @Override public String getProtocolServerType() { return protocolServerType; } /** * Support method to allow other classes in the wsn package to increment total messages received */ protected void incrementTotalMessagesReceived() { totalMessagesReceived.incrementAndGet(); } /** * Retrieve the default element name for non-XML messages that are to be wrapped in a soap enveloped * WSNotification Notify element. This element will be the first and only child of the Message element. * @return The default name of the content wrapper element */ public static String getMessageContentWrapperElementName() { return contentWrapperElementName; } /** * This interface method must take in an instance of Message, which contains the appropriate references * and flags needed to distribute the message to consumers. Implementation specific details can vary from * protocol to protocol, but the end result of a method call to sendMessage is that the message is delivered, * or an error is logged. * * @param message An instance of Message containing the required data to distribute a message. */ @Override public void sendMessage(Message message) { log.debug("WSNServer received message for distribution"); if (!message.getOriginProtocol().equals(protocolServerType) || message.getAttribute("duplicate") != null) { log.debug("The message originated from other protocol than WSNotification"); WSNTools.NotifyWithContext notifywrapper = WSNTools.buildNotifyWithContext(message.getMessage(), message.getTopic(), null, null); // If it contained XML, we need to create properly marshalled jaxb node structure if (message.getMessage().contains("<") || message.getMessage().contains(">")) { // Unmarshal from raw XML Notify notify = WSNTools.createNotify(message); // If it was malformed, or maybe just a message containing < or >, build it as generic content element if (notify == null) { WSNTools.injectMessageContentIntoNotify(WSNTools.buildGenericContentElement(message.getMessage()), notifywrapper.notify); // Else inject the unmarshalled XML nodes into the Notify message attribute } else { WSNTools.injectMessageContentIntoNotify(WSNTools.extractMessageContentFromNotify(notify), notifywrapper.notify); } } /* Start to resolve recipients. The reason we cannot re-use the WSNCommandProxy's sendNotification method is that it will inject the message to the MessageService for relay thus creating duplicate messages. */ NuNamespaceContextResolver namespaceContextResolver = notifywrapper.nuNamespaceContextResolver; // bind namespaces to topics for (NotificationMessageHolderType holderType : notifywrapper.notify.getNotificationMessage()) { // Extract the topic TopicExpressionType topic = holderType.getTopic(); if (holderType.getTopic() != null) { NuNamespaceContextResolver.NuResolvedNamespaceContext context = namespaceContextResolver.resolveNamespaceContext(topic); if (context == null) { continue; } context.getAllPrefixes().forEach(prefix -> { // check if this is the default xmlns attribute if (!prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) { // add namespace context to the expression node topic.getOtherAttributes().put(new QName("xmlns:" + prefix), context.getNamespaceURI(prefix)); } }); } } // For all valid recipients for (String recipient : _commandProxy.getAllRecipients()) { // If the subscription has expired, continue if (_commandProxy.getProxySubscriptionManager().getSubscriber(recipient).hasExpired()) continue; // Filter do filter handling, if any Notify toSend = _commandProxy.getRecipientFilteredNotify(recipient, notifywrapper.notify, namespaceContextResolver); // If any message was left to send, send it if (toSend != null) { InternalMessage outMessage = new InternalMessage( InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE | InternalMessage.STATUS_ENDPOINTREF_IS_SET, toSend ); // Update the requestinformation outMessage.getRequestInformation().setEndpointReference(_commandProxy.getEndpointReferenceOfRecipient(recipient)); // Check if the subscriber has requested raw message format // If the recipient has requested UseRaw, remove Notify payload wrapping if (_commandProxy .getProxySubscriptionManager() .getSubscriber(recipient) .getAttribute(WSNSubscriptionManager.WSN_USERAW_TOKEN) != null) { Object content = WSNTools.extractMessageContentFromNotify(toSend); // Update the InternalMessage with the content of the NotificationMessage outMessage.setMessage(content); } // Pass it along to the request parser wrapped as a thread pool executed job clientPool.execute(() -> _requestParser.acceptLocalMessage(outMessage)); } } } else { log.debug("Message originated from WSN protocol, already processed"); } } /** * Fetches the complete URI of this ProtocolServer * @return A string representing the complete URI of this ProtocolServer */ public String getURI() { // Check if we are behind NAT if (behindNAT) { return "http://" + publicWANHost + ":" + publicWANPort; } // If somehow URI could not be retrieved if (_singleton._server.getURI() == null) { _singleton.log.warn("Failed to fetch URI of server"); return "http://" + DEFAULT_HOST + ":" + DEFAULT_PORT; } // Return the server connectors registered host and port return "http://" + _singleton._server.getURI().getHost()+ ":" + (_singleton._server.getURI().getPort() > -1 ? _singleton._server.getURI().getPort() : DEFAULT_PORT); } /** * Returns the public WAN Host if behindNAT is true. If behindNAT is false, the value of host is returned. * @return The public WAN Host */ public String getPublicWANHost() { if (behindNAT) return publicWANHost; return host; } /** * Returns the public WAN Port if behindNAT is true. If behindNAT is false, the value of port is returned. * @return The public WAN Port */ public Integer getPublicWANPort() { if (behindNAT) return publicWANPort; return port; } /** * Registers the specified ServiceConnection to the ProtocolServer * @param webServiceConnector: The ServiceConnection you wish to register. */ public synchronized void registerService(ServiceConnection webServiceConnector) { _services.add(webServiceConnector); } /** * Unregisters the specified ServiceConnection from the ProtocolServer * @param webServiceConnector: The ServiceConnection you wish to remove. */ public synchronized void removeService(ServiceConnection webServiceConnector) { _services.remove(webServiceConnector); } /** * Add a standard serverconnector to the server instance. * @param address The IP address you wish to bind the serverconnector to * @param port The port you with to bind the serverconnector to */ public void addStandardConnector(String address, int port){ ServerConnector connector = new ServerConnector(_server); connector.setHost(address); if(port == 80){ log.warn("You have requested to use port 80. This will not work unless you are running as root." + "Are you running as root? You shouldn't. Reroute port 80 to 8080 instead."); } connector.setPort(port); _connectors.add(connector); _server.addConnector(connector); } /** * Add a predefined serverconnector to the server instance. * @param connector A jetty ServerConnector */ public void addConnector(Connector connector){ _connectors.add(connector); this._server.addConnector(connector); } /** * Fetch the WSNRequestParser object * @return WSNRequestParser */ public WSNRequestParser getRequestParser() { return this._requestParser; } // This is the HTTP Handler that the WSNServer uses to process all incoming requests private class HttpHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("HttpHandle invoked on target: " + target); // Do some stats. totalRequests.incrementAndGet(); boolean isChunked = false; Enumeration headerNames = request.getHeaderNames(); log.debug("Checking headers..."); // Check the request headers, check for chunked encoding while(headerNames.hasMoreElements()) { String outMessage = (String)headerNames.nextElement(); Enumeration returnMessage = request.getHeaders(outMessage); while(returnMessage.hasMoreElements()) { String inputStream = (String)returnMessage.nextElement(); if(outMessage.equals("Transfer-Encoding") && inputStream.equals("chunked")) { log.debug("Found Transfer-Encoding was chunked."); isChunked = true; } } } log.debug("Accepted message, trying to instantiate WSNu InternalMessage"); // Get message content, if any InternalMessage outgoingMessage; if (request.getContentLength() > 0) { log.debug("Content length was: " + request.getContentLength()); InputStream inputStream = request.getInputStream(); outgoingMessage = new InternalMessage(InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE | InternalMessage.STATUS_MESSAGE_IS_INPUTSTREAM, inputStream); } else if (isChunked) { log.debug("Chunked transfer encoding!"); InputStream chunkedInputStream = request.getInputStream(); outgoingMessage = new InternalMessage( InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE | InternalMessage.STATUS_MESSAGE_IS_INPUTSTREAM, chunkedInputStream); } else { outgoingMessage = new InternalMessage(InternalMessage.STATUS_OK, null); } log.debug("WSNInternalMessage: " + outgoingMessage); // Update the request information object outgoingMessage.getRequestInformation().setEndpointReference(request.getRemoteHost()); outgoingMessage.getRequestInformation().setRequestURL(request.getRequestURI()); outgoingMessage.getRequestInformation().setParameters(request.getParameterMap()); log.debug("EndpointReference: " + outgoingMessage.getRequestInformation().getEndpointReference()); log.debug("Request URI: " + outgoingMessage.getRequestInformation().getRequestURL()); log.debug("Forwarding message to requestParser..."); // Push the outgoingMessage to the request parser. Based on the status flags of the return message // we should know what has happened, and which response we should send. InternalMessage returnMessage = null; try { returnMessage = WSNotificationServer.this._requestParser.parseMessage(outgoingMessage, response.getOutputStream()); } catch (Exception e) { log.error("Uncaught exception: " + e.getMessage()); log.trace(e.getStackTrace()); } // Improper response from WSNRequestParser! FC WHAT DO? if (returnMessage == null) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); totalErrors.incrementAndGet(); baseRequest.setHandled(true); returnMessage = new InternalMessage(InternalMessage.STATUS_FAULT_INTERNAL_ERROR, null); } /* Handle possible errors */ if ((returnMessage.statusCode & InternalMessage.STATUS_FAULT) > 0) { /* Have we got an error message to return? */ if ((returnMessage.statusCode & InternalMessage.STATUS_HAS_MESSAGE) > 0) { response.setContentType("application/soap+xml;charset=utf-8"); // Declare input and output streams InputStream inputStream = (InputStream)returnMessage.getMessage(); OutputStream outputStream = response.getOutputStream(); // Pipe the data from input to output stream ByteStreams.copy(inputStream, outputStream); // Set proper HTTP status, flush the output stream and set the handled flag response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); outputStream.flush(); baseRequest.setHandled(true); totalErrors.incrementAndGet(); outputStream.close(); return; } /* If no valid destination was found for the request (Endpoint non-existant) */ if ((returnMessage.statusCode & InternalMessage.STATUS_FAULT_INVALID_DESTINATION) > 0) { response.setStatus(HttpStatus.NOT_FOUND_404); baseRequest.setHandled(true); totalBadRequests.incrementAndGet(); return; /* If there was an internal server error */ } else if ((returnMessage.statusCode & InternalMessage.STATUS_FAULT_INTERNAL_ERROR) > 0) { response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); baseRequest.setHandled(true); totalErrors.incrementAndGet(); return; /* If there was syntactical errors or otherwise malformed request content */ } else if ((returnMessage.statusCode & InternalMessage.STATUS_FAULT_INVALID_PAYLOAD) > 0) { response.setStatus(HttpStatus.BAD_REQUEST_400); baseRequest.setHandled(true); totalBadRequests.incrementAndGet(); return; /* If the requested method or access to endpoint is forbidden */ } else if ((returnMessage.statusCode & InternalMessage.STATUS_FAULT_ACCESS_NOT_ALLOWED) > 0) { response.setStatus(HttpStatus.FORBIDDEN_403); baseRequest.setHandled(true); totalBadRequests.incrementAndGet(); return; } /* Otherwise, there has been an exception of some sort with no message attached, and we will reply with a server error */ response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); baseRequest.setHandled(true); totalErrors.incrementAndGet(); // Check if we have status=OK and also we have a message } else if (((InternalMessage.STATUS_OK & returnMessage.statusCode) > 0) && (InternalMessage.STATUS_HAS_MESSAGE & returnMessage.statusCode) > 0){ /* Liar liar pants on fire */ if (returnMessage.getMessage() == null) { log.error("The HAS_RETURNING_MESSAGE flag was checked, but there was no returning message content"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); baseRequest.setHandled(true); totalErrors.incrementAndGet(); return; } // Prepare the response content type response.setContentType("application/soap+xml;charset=utf-8"); // Allocate the input and output streams InputStream inputStream = (InputStream)returnMessage.getMessage(); OutputStream outputStream = response.getOutputStream(); /* Copy the contents of the input stream into the output stream */ ByteStreams.copy(inputStream, outputStream); /* Set proper OK status and flush out the stream for response to be sent */ response.setStatus(HttpStatus.OK_200); outputStream.flush(); baseRequest.setHandled(true); /* Everything is fine, and nothing is expected */ } else if ((InternalMessage.STATUS_OK & returnMessage.statusCode) > 0) { response.setStatus(HttpStatus.OK_200); baseRequest.setHandled(true); } else { // We obviously should never land in this block, hence we set the 500 status. log.error("HandleMessage: The message returned to the WSNotificationServer was not flagged with either STATUS_OK or" + "STATUS_FAULT. Please set either of these flags at all points"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500); baseRequest.setHandled(true); totalErrors.incrementAndGet(); } } } public InternalMessage sendMessage(InternalMessage message) { // Fetch the requestInformation from the message, and extract the endpoint RequestInformation requestInformation = message.getRequestInformation(); String endpoint = requestInformation.getEndpointReference(); /* If we have nowhere to send the message */ if(endpoint == null){ log.error("Endpoint reference not set"); totalErrors.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_FAULT, null); } /* Create the actual http-request*/ org.eclipse.jetty.client.api.Request request = _client.newRequest(requestInformation.getEndpointReference()); request.timeout(connectionTimeout, TimeUnit.SECONDS); /* Try to send the message */ try{ /* Raw request */ if ((message.statusCode & InternalMessage.STATUS_HAS_MESSAGE) == 0) { request.method(HttpMethod.GET); log.debug("Sending message without content to " + requestInformation.getEndpointReference()); ContentResponse response = request.send(); totalRequests.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); /* Request with message */ } else { // Set proper request method request.method(HttpMethod.POST); // If the statusflag has set a message and it is not an input stream if ((message.statusCode & InternalMessage.STATUS_MESSAGE_IS_INPUTSTREAM) == 0) { log.error("sendMessage(): " + "The message contained something else than an inputStream." + "Please convert your message to an InputStream before calling this methbod."); return new InternalMessage(InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } else { // Check if we should have had a message, but there was none if(message.getMessage() == null){ log.error("No content was found to send"); totalErrors.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } // Send the request to the specified endpoint reference log.info("Sending message with content to " + requestInformation.getEndpointReference()); InputStream msg = (InputStream) message.getMessage(); request.content(new InputStreamContentProvider(msg), "application/soap+xml; charset=utf-8"); ContentResponse response = request.send(); msg.close(); totalMessagesSent.incrementAndGet(); // Check what HTTP status we received, if is not A-OK, flag the internalmessage as fault // and make the response content the message of the InternalMessage returned if (!HttpStatus.isSuccess(response.getStatus())) { totalBadRequests.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_FAULT | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); } else { return new InternalMessage(InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); } } } } catch(ClassCastException e) { log.error("sendMessage(): The message contained something else than an inputStream." + "Please convert your message to an InputStream before calling this method."); totalErrors.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } catch(Exception e) { totalErrors.incrementAndGet(); e.printStackTrace(); log.error("sendMessage(): Unable to establish connection: " + e.getMessage()); return new InternalMessage(InternalMessage.STATUS_FAULT_INTERNAL_ERROR, null); } } }
package nom.bdezonia.zorbage.algorithm; import nom.bdezonia.zorbage.function.Function2; import nom.bdezonia.zorbage.type.algebra.Algebra; import nom.bdezonia.zorbage.type.algebra.Tolerance; /** * * @author Barry DeZonia * */ public class WithinTolerance<T extends Algebra<T,U> & Tolerance<U,W>, U, V extends Algebra<V,W>, W> implements Function2<Boolean,U,U> { private final T uAlgebra; private final V tolAlgebra; private final W tolerance; /** * * @param uAlgebra * @param tolAlgebra * @param tolerance */ public WithinTolerance(T uAlgebra, V tolAlgebra, W tolerance) { this.uAlgebra = uAlgebra; this.tolAlgebra = tolAlgebra; this.tolerance = tolAlgebra.construct(tolerance); } /** * * @param tol */ public void setTolerance(W tol) { tolAlgebra.assign().call(tol, tolerance); } /** * * @param tol */ public void getTolerance(W tol) { tolAlgebra.assign().call(tolerance, tol); } @Override public Boolean call(U a, U b) { return uAlgebra.within().call(a, b, tolerance); } }
package org.apdplat.word.segmentation; import java.util.List; import org.apdplat.word.corpus.Bigram; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * 4 * * () * @author */ public class WordSegmentation implements Segmentation{ private static final Logger LOGGER = LoggerFactory.getLogger(WordSegmentation.class); private static final Segmentation MM = SegmentationFactory.getSegmentation(SegmentationAlgorithm.MaximumMatching); private static final Segmentation RMM = SegmentationFactory.getSegmentation(SegmentationAlgorithm.ReverseMaximumMatching); private static final Segmentation MIM = SegmentationFactory.getSegmentation(SegmentationAlgorithm.MinimumMatching); private static final Segmentation RMIM = SegmentationFactory.getSegmentation(SegmentationAlgorithm.ReverseMinimumMatching); @Override public List<Word> seg(String text){ List<Word> words = RMM.seg(text); float score = Bigram.bigram(words); LOGGER.debug(""+words.toString()+" : ="+score); List<Word> result = words; float max = score; words = MM.seg(text); score = Bigram.bigram(words); LOGGER.debug(""+words.toString()+" : ="+score); if(score > max){ result = words; max = score; } words = RMIM.seg(text); score = Bigram.bigram(words); LOGGER.debug(""+words.toString()+" : ="+score); if(score > max){ result = words; max = score; } words = MIM.seg(text); score = Bigram.bigram(words); LOGGER.debug(""+words.toString()+" : ="+score); if(score > max){ result = words; max = score; } LOGGER.debug(""+max+", "+result); return result; } public static void main(String[] args){ Segmentation segmentation = new WordSegmentation(); LOGGER.info(segmentation.seg("APDPlat").toString()); } }
package org.banyan.concurrent.interrupt; public class SleepInterrupt implements Runnable { public static void main(String[] args) { SleepInterrupt sleepInterrupt = new SleepInterrupt(); Thread thread = new Thread(sleepInterrupt); thread.start(); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main() - interrupting other thread"); thread.interrupt(); System.out.println("main() - end"); } @Override public void run() { try { System.out.println("run() sleep 10 seconds"); Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("run() - interrupted while sleeping"); //run //return return; } System.out.println("run() - leaving normally"); } }
package org.concord.energy3d.simulation; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import org.concord.energy3d.gui.EnergyPanel; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Sensor; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Tree; import org.concord.energy3d.model.UserData; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.scene.SceneManager; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.util.Util; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.AnyToXYTransform; import org.poly2tri.transform.coordinate.XYToAnyTransform; import org.poly2tri.triangulation.point.TPoint; import com.ardor3d.image.Image; import com.ardor3d.image.ImageDataFormat; import com.ardor3d.image.PixelDataType; import com.ardor3d.image.Texture.MinificationFilter; import com.ardor3d.image.Texture2D; import com.ardor3d.intersection.PickResults; import com.ardor3d.intersection.PickingUtil; import com.ardor3d.intersection.PrimitivePickResults; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Ray3; import com.ardor3d.math.Vector2; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector2; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.state.RenderState.StateType; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.Spatial; import com.ardor3d.scenegraph.hint.CullHint; import com.ardor3d.util.TextureKey; import com.ardor3d.util.geom.BufferUtils; public class SolarRadiation { public final static double SOLAR_CONSTANT = 1.361; public final static int MINUTES_OF_DAY = 1440; public final static double[] ASHRAE_C = new double[] { 0.103, 0.104, 0.109, 0.120, 0.130, 0.137, 0.138, 0.134, 0.121, 0.111, 0.106, 0.103 }; // revised C coefficients found from Iqbal's book public final static int AIR_MASS_NONE = -1; public final static int AIR_MASS_KASTEN_YOUNG = 0; public final static int AIR_MASS_SPHERE_MODEL = 1; private static SolarRadiation instance = new SolarRadiation(); private final Map<Mesh, MeshData> onMesh = new HashMap<Mesh, MeshData>(); private final List<Spatial> collidables = new ArrayList<Spatial>(); private final Map<Spatial, HousePart> collidablesToParts = new HashMap<Spatial, HousePart>(); private int timeStep = 15; private double solarStep = 2.0; private long maxValue; private int airMassSelection = AIR_MASS_SPHERE_MODEL; private double peakRadiation; private class MeshData { public Vector3 p0; public Vector3 p1; public Vector3 p2; public Vector3 u; public Vector3 v; public int rows; public int cols; public double[][] dailySolarIntensity; public double[] solarPotential; public double[] heatLoss; } public static SolarRadiation getInstance() { return instance; } public void compute() { System.out.println("computeSolarRadiation()"); initCollidables(); onMesh.clear(); for (final HousePart part : Scene.getInstance().getParts()) part.setSolarPotential(new double[MINUTES_OF_DAY / timeStep]); maxValue = 1; computeToday((Calendar) Heliodon.getInstance().getCalender().clone()); for (final HousePart part : Scene.getInstance().getParts()) { if (part.isDrawCompleted()) part.drawHeatFlux(); } } public double[] getSolarPotential(final Mesh mesh) { final MeshData md = onMesh.get(mesh); return md == null ? null : md.solarPotential; } public double[] getHeatLoss(final Mesh mesh) { final MeshData md = onMesh.get(mesh); return md == null ? null : md.heatLoss; } private void initCollidables() { collidables.clear(); collidablesToParts.clear(); for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation || part instanceof Wall || part instanceof SolarPanel || part instanceof Tree || part instanceof Sensor || part instanceof Window) { final Spatial s = part.getRadiationCollisionSpatial(); collidables.add(s); collidablesToParts.put(s, part); } else if (part instanceof Roof) { for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { if (roofPart.getSceneHints().getCullHint() != CullHint.Always) { final Spatial s = ((Node) roofPart).getChild(6); collidables.add(s); collidablesToParts.put(s, part); } } } } } private void computeToday(final Calendar today) { today.set(Calendar.SECOND, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.HOUR_OF_DAY, 0); final ReadOnlyVector3[] sunLocations = new ReadOnlyVector3[SolarRadiation.MINUTES_OF_DAY / timeStep]; int totalSteps = 0; for (int minute = 0; minute < SolarRadiation.MINUTES_OF_DAY; minute += timeStep) { final ReadOnlyVector3 sunLocation = Heliodon.getInstance().computeSunLocation(today).normalize(null); sunLocations[minute / timeStep] = sunLocation; if (sunLocation.getZ() > 0) totalSteps++; today.add(Calendar.MINUTE, timeStep); } totalSteps -= 2; final double dayLength = totalSteps * timeStep / 60.0; int step = 1; for (int minute = 0; minute < SolarRadiation.MINUTES_OF_DAY; minute += timeStep) { final ReadOnlyVector3 sunLocation = sunLocations[minute / timeStep]; if (sunLocation.getZ() > 0) { final ReadOnlyVector3 directionTowardSun = sunLocation.normalize(null); for (final HousePart part : Scene.getInstance().getParts()) { if (part.isDrawCompleted()) if (part instanceof Foundation || part instanceof Wall || part instanceof Window) computeOnMesh(minute, dayLength, directionTowardSun, part, part.getRadiationMesh(), (Mesh) part.getRadiationCollisionSpatial(), part.getNormal()); else if (part instanceof SolarPanel || part instanceof Sensor) computeOnMeshSolarPanel(minute, dayLength, directionTowardSun, part, part.getRadiationMesh(), (Mesh) part.getRadiationCollisionSpatial(), part.getNormal()); else if (part instanceof Roof) for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { if (roofPart.getSceneHints().getCullHint() != CullHint.Always) { final ReadOnlyVector3 faceDirection = (ReadOnlyVector3) roofPart.getUserData(); final Mesh mesh = (Mesh) ((Node) roofPart).getChild(6); computeOnMesh(minute, dayLength, directionTowardSun, part, mesh, mesh, faceDirection); } } } computeOnLand(dayLength, directionTowardSun); EnergyPanel.getInstance().progress(100 * step / totalSteps); step++; } maxValue++; } maxValue *= 1 - 0.01 * Scene.getInstance().getSolarHeatMapColorContrast(); } private void computeOnLand(final double dayLength, final ReadOnlyVector3 directionTowardSun) { calculatePeakRadiation(directionTowardSun, dayLength); final double indirectRadiation = calculateDiffuseAndReflectedRadiation(directionTowardSun, Vector3.UNIT_Z); final double totalRadiation = calculateDirectRadiation(directionTowardSun, Vector3.UNIT_Z) + indirectRadiation; final double step = solarStep * 4; final int rows = (int) (256 / step); final int cols = rows; MeshData data = onMesh.get(SceneManager.getInstance().getSolarLand()); if (data == null) { data = new MeshData(); data.dailySolarIntensity = new double[rows][cols]; onMesh.put(SceneManager.getInstance().getSolarLand(), data); } final Vector3 p = new Vector3(); final double absorption = 1 - Scene.getInstance().getGround().getAlbedo(); for (int col = 0; col < cols; col++) { p.setX((col - cols / 2) * step + step / 2.0); for (int row = 0; row < rows; row++) { if (EnergyPanel.getInstance().isCancelled()) throw new CancellationException(); p.setY((row - rows / 2) * step + step / 2.0); final Ray3 pickRay = new Ray3(p, directionTowardSun); final PickResults pickResults = new PrimitivePickResults(); for (final Spatial spatial : collidables) { PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() != 0) break; } if (pickResults.getNumber() == 0) { data.dailySolarIntensity[row][col] += Scene.getInstance().getOnlyAbsorptionInSolarMap() ? totalRadiation * absorption : totalRadiation; } else { // if shaded, it still receives indirect radiation data.dailySolarIntensity[row][col] += Scene.getInstance().getOnlyAbsorptionInSolarMap() ? indirectRadiation * absorption : indirectRadiation; } } } } // Formula from http://en.wikipedia.org/wiki/Air_mass_(solar_energy)#Solar_intensity private void computeOnMesh(final int minute, final double dayLength, final ReadOnlyVector3 directionTowardSun, final HousePart housePart, final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal) { MeshData data = onMesh.get(drawMesh); if (data == null) data = initMeshTextureData(drawMesh, collisionMesh, normal, !(housePart instanceof Window)); /* needed in order to prevent picking collision with neighboring wall at wall edge */ final double OFFSET = 0.1; final ReadOnlyVector3 offset = directionTowardSun.multiply(OFFSET, null); calculatePeakRadiation(directionTowardSun, dayLength); final double dot = normal.dot(directionTowardSun); final double directRadiation = dot > 0 ? calculateDirectRadiation(directionTowardSun, normal) : 0; final double indirectRadiation = calculateDiffuseAndReflectedRadiation(directionTowardSun, normal); final double annotationScale = Scene.getInstance().getAnnotationScale(); final double scaleFactor = annotationScale * annotationScale / 60 * timeStep; final float absorption = housePart instanceof Window ? 1 : 1 - housePart.getAlbedo(); // a window itself doesn't really absorb solar energy, but it passes the energy into the house to be absorbed if (housePart instanceof Roof) { // for now, only store this for roofs that have different meshes if (data.solarPotential == null) data.solarPotential = new double[MINUTES_OF_DAY / timeStep]; if (data.heatLoss == null) data.heatLoss = new double[MINUTES_OF_DAY / timeStep]; } for (int col = 0; col < data.cols; col++) { final ReadOnlyVector3 pU = data.u.multiply(solarStep / 2.0 + col * solarStep, null).addLocal(data.p0); final double w = (col == data.cols - 1) ? data.p2.distance(pU) : solarStep; for (int row = 0; row < data.rows; row++) { if (EnergyPanel.getInstance().isCancelled()) throw new CancellationException(); if (data.dailySolarIntensity[row][col] == -1) continue; final ReadOnlyVector3 p = data.v.multiply(solarStep / 2.0 + row * solarStep, null).addLocal(pU).add(offset, null); final double h; if (row == data.rows - 1) h = data.p1.subtract(data.p0, null).length() - row * solarStep; else h = solarStep; final Ray3 pickRay = new Ray3(p, directionTowardSun); final PickResults pickResults = new PrimitivePickResults(); double radiation = indirectRadiation; // assuming that indirect (ambient or diffuse) radiation can always reach a grid point if (dot > 0) { for (final Spatial spatial : collidables) { if (spatial != collisionMesh) { PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() != 0) { if (housePart instanceof Foundation) { // at this point, we only show radiation heat map on the first floor final HousePart collidableOwner = collidablesToParts.get(spatial); if (collidableOwner instanceof Window) { radiation += directRadiation * ((Window) collidableOwner).getSolarHeatGainCoefficient(); } } break; } } } if (pickResults.getNumber() == 0) radiation += directRadiation; } data.dailySolarIntensity[row][col] += Scene.getInstance().getOnlyAbsorptionInSolarMap() ? absorption * radiation : radiation; if (data.solarPotential != null) // solar potential should not apply absorption data.solarPotential[minute / timeStep] += radiation * w * h * scaleFactor; housePart.getSolarPotential()[minute / timeStep] += radiation * w * h * scaleFactor; } } } private void computeOnMeshSolarPanel(final int minute, final double dayLength, final ReadOnlyVector3 directionTowardSun, final HousePart housePart, final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal) { if (normal == null) // FIXME: Sometimes a solar panel can be created without a parent. This is a temporary fix. return; MeshData data = onMesh.get(drawMesh); if (data == null) data = initMeshTextureDataSolarPanel(drawMesh, collisionMesh, normal); final double OFFSET = 3; final ReadOnlyVector3 offset = directionTowardSun.multiply(OFFSET, null); calculatePeakRadiation(directionTowardSun, dayLength); final double dot = normal.dot(directionTowardSun); double directRadiation = 0; if (dot > 0) directRadiation += calculateDirectRadiation(directionTowardSun, normal); final double indirectRadiation = calculateDiffuseAndReflectedRadiation(directionTowardSun, normal); final FloatBuffer vertexBuffer = drawMesh.getMeshData().getVertexBuffer(); for (int col = 0; col < 2; col++) { for (int row = 0; row < 2; row++) { if (EnergyPanel.getInstance().isCancelled()) throw new CancellationException(); final int index; if (row == 0 && col == 0) index = 3; else if (row == 0 && col == 1) index = 0; else if (row == 1 && col == 0) index = 6; else index = 12; final Vector3 point = new Vector3(vertexBuffer.get(index), vertexBuffer.get(index + 1), vertexBuffer.get(index + 2)); final ReadOnlyVector3 p = drawMesh.getWorldTransform().applyForward(point).addLocal(offset); final Ray3 pickRay = new Ray3(p, directionTowardSun); double radiation = indirectRadiation; // assuming that indirect (ambient or diffuse) radiation can always reach a grid point if (dot > 0) { final PickResults pickResults = new PrimitivePickResults(); for (final Spatial spatial : collidables) { if (spatial != collisionMesh) { PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() != 0) break; } } if (pickResults.getNumber() == 0) radiation += directRadiation; } data.dailySolarIntensity[row][col] += radiation; double area = 1; if (housePart instanceof SolarPanel) area = SolarPanel.WIDTH * SolarPanel.HEIGHT; else if (housePart instanceof Sensor) area = Sensor.WIDTH * Sensor.HEIGHT; housePart.getSolarPotential()[minute / timeStep] += radiation * area / 240.0 * timeStep; // ABOVE: 4x60: 4 is to get the 1/4 area of the 2x2 grid; 60 is to convert the unit of timeStep from minute to kWh } } } public void initMeshTextureData(final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal) { if (onMesh.get(drawMesh) == null) { drawMesh.setDefaultColor(ColorRGBA.BLACK); } initMeshTextureData(drawMesh, collisionMesh, normal, true); } private MeshData initMeshTextureData(final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal, final boolean updateTexture) { final MeshData data = new MeshData(); final AnyToXYTransform toXY = new AnyToXYTransform(normal.getX(), normal.getY(), normal.getZ()); final XYToAnyTransform fromXY = new XYToAnyTransform(normal.getX(), normal.getY(), normal.getZ()); final FloatBuffer vertexBuffer = collisionMesh.getMeshData().getVertexBuffer(); vertexBuffer.rewind(); double minX, minY, maxX, maxY; minX = minY = Double.POSITIVE_INFINITY; maxX = maxY = Double.NEGATIVE_INFINITY; double z = Double.NaN; final List<ReadOnlyVector2> points = new ArrayList<ReadOnlyVector2>(vertexBuffer.limit() / 3); while (vertexBuffer.hasRemaining()) { final Vector3 pWorld = drawMesh.localToWorld(new Vector3(vertexBuffer.get(), vertexBuffer.get(), vertexBuffer.get()), null); final Point p = new TPoint(pWorld.getX(), pWorld.getY(), pWorld.getZ()); toXY.transform(p); if (p.getX() < minX) minX = p.getX(); if (p.getX() > maxX) maxX = p.getX(); if (p.getY() < minY) minY = p.getY(); if (p.getY() > maxY) maxY = p.getY(); if (Double.isNaN(z)) z = p.getZ(); points.add(new Vector2(p.getX(), p.getY())); } final Point tmp = new TPoint(minX, minY, z); fromXY.transform(tmp); data.p0 = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); tmp.set(minX, maxY, z); fromXY.transform(tmp); data.p1 = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); tmp.set(maxX, minY, z); fromXY.transform(tmp); data.p2 = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); data.rows = (int) Math.ceil(data.p1.subtract(data.p0, null).length() / solarStep); data.cols = (int) Math.ceil(data.p2.subtract(data.p0, null).length() / solarStep); if (data.dailySolarIntensity == null) data.dailySolarIntensity = new double[roundToPowerOfTwo(data.rows)][roundToPowerOfTwo(data.cols)]; if (onMesh.get(drawMesh) == null) { final ReadOnlyVector2 originXY = new Vector2(minX, minY); final ReadOnlyVector2 uXY = new Vector2(maxX - minX, 0).normalizeLocal(); final ReadOnlyVector2 vXY = new Vector2(0, maxY - minY).normalizeLocal(); for (int row = 0; row < data.dailySolarIntensity.length; row++) for (int col = 0; col < data.dailySolarIntensity[0].length; col++) { if (row >= data.rows || col >= data.cols) data.dailySolarIntensity[row][col] = -1; else { final ReadOnlyVector2 p = originXY.add(uXY.multiply(col * solarStep, null), null).add(vXY.multiply(row * solarStep, null), null); boolean isInside = false; for (int i = 0; i < points.size(); i += 3) { if (Util.isPointInsideTriangle(p, points.get(i), points.get(i + 1), points.get(i + 2))) { isInside = true; break; } } if (!isInside) data.dailySolarIntensity[row][col] = -1; } } } data.u = data.p2.subtract(data.p0, null).normalizeLocal(); data.v = data.p1.subtract(data.p0, null).normalizeLocal(); onMesh.put(drawMesh, data); if (updateTexture) updateTextureCoords(drawMesh); return data; } private MeshData initMeshTextureDataSolarPanel(final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal) { final MeshData data = new MeshData(); data.rows = 4; data.cols = 4; if (data.dailySolarIntensity == null) data.dailySolarIntensity = new double[roundToPowerOfTwo(data.rows)][roundToPowerOfTwo(data.cols)]; onMesh.put(drawMesh, data); return data; } private void updateTextureCoords(final Mesh drawMesh) { final MeshData data = onMesh.get(drawMesh); final ReadOnlyVector3 o = data.p0; final ReadOnlyVector3 u = data.u.multiply(roundToPowerOfTwo(data.cols) * getSolarStep(), null); final ReadOnlyVector3 v = data.v.multiply(roundToPowerOfTwo(data.rows) * getSolarStep(), null); final FloatBuffer vertexBuffer = drawMesh.getMeshData().getVertexBuffer(); final FloatBuffer textureBuffer = drawMesh.getMeshData().getTextureBuffer(0); vertexBuffer.rewind(); textureBuffer.rewind(); while (vertexBuffer.hasRemaining()) { final ReadOnlyVector3 p = drawMesh.localToWorld(new Vector3(vertexBuffer.get(), vertexBuffer.get(), vertexBuffer.get()), null); final Vector3 uP = Util.closestPoint(o, u, p, v.negate(null)); final Vector3 vP = Util.closestPoint(o, v, p, u.negate(null)); if (uP != null && vP != null) { final float uScale = (float) (uP.distance(o) / u.length()); final float vScale = (float) (vP.distance(o) / v.length()); textureBuffer.put(uScale).put(vScale); } } } // air mass calculation from http://en.wikipedia.org/wiki/Air_mass_(solar_energy)#At_higher_altitudes private double computeAirMass(final ReadOnlyVector3 directionTowardSun) { switch (airMassSelection) { case AIR_MASS_NONE: return 1; case AIR_MASS_KASTEN_YOUNG: double zenithAngle = directionTowardSun.smallestAngleBetween(Vector3.UNIT_Z); return 1 / (Math.cos(zenithAngle) + 0.50572 * Math.pow(96.07995 - zenithAngle / Math.PI * 180.0, -1.6364)); default: zenithAngle = directionTowardSun.smallestAngleBetween(Vector3.UNIT_Z); final double cos = Math.cos(zenithAngle); final double r = 708; final String city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); if (!"".equals(city)) { final double c = LocationData.getInstance().getAltitudes().get(city) / 9000.0; return Math.sqrt((r + c) * (r + c) * cos * cos + (2 * r + 1 + c) * (1 - c)) - (r + c) * cos; } else { return Math.sqrt(r * r * cos * cos + 2 * r + 1) - r * cos; } } } // Solar radiation incident outside the earth's atmosphere is called extraterrestrial radiation. private static double getExtraterrestrialRadiation() { final double b = Math.PI * 2.0 * Heliodon.getInstance().getCalender().get(Calendar.DAY_OF_YEAR) / 365.0; final double er = 1.00011 + 0.034221 * Math.cos(b) + 0.00128 * Math.sin(b) + 0.000719 * Math.cos(2 * b) + 0.000077 * Math.sin(2 * b); return SOLAR_CONSTANT * er; } // Reused peak solar radiation value. Must be called once and only once before calling calculateDirectRadiation and calculateDiffusionAndReflection private void calculatePeakRadiation(final ReadOnlyVector3 directionTowardSun, final double dayLength) { double sunshinePercentage = 1.0; final String city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); if (!city.equals("")) { final int[] sunshineHours = LocationData.getInstance().getSunshineHours().get(city); if (sunshineHours != null) sunshinePercentage = sunshineHours[Heliodon.getInstance().getCalender().get(Calendar.MONTH)] / (dayLength * 30); } // don't use the 1.1 prefactor as we consider diffuse radiation in the ASHRAE model peakRadiation = getExtraterrestrialRadiation() * Math.pow(0.7, Math.pow(computeAirMass(directionTowardSun), 0.678)) * sunshinePercentage; } private double calculateDirectRadiation(final ReadOnlyVector3 directionTowardSun, final ReadOnlyVector3 normal) { final double result = directionTowardSun.dot(normal) * peakRadiation; return result < 0 ? 0 : result; } private double calculateDiffuseAndReflectedRadiation(final ReadOnlyVector3 directionTowardSun, final ReadOnlyVector3 normal) { double result = 0; final double cos = normal.dot(Vector3.UNIT_Z); final double viewFactorWithSky = 0.5 * (1 + cos); final double viewFactorWithGround = 0.5 * (1 - cos); if (viewFactorWithSky > 0 || viewFactorWithGround > 0) { if (viewFactorWithSky > 0) { // diffuse irradiance from the sky result += ASHRAE_C[Heliodon.getInstance().getCalender().get(Calendar.MONTH)] * viewFactorWithSky * peakRadiation; } if (viewFactorWithGround > 0) { // short-wave reflection from the ground result += Scene.getInstance().getGround().getAlbedo() * viewFactorWithGround * peakRadiation; } } return result; } public void computeTotalEnergyForBuildings() { applyTexture(SceneManager.getInstance().getSolarLand()); for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation || part instanceof Wall || part instanceof SolarPanel || part instanceof Sensor) applyTexture(part.getRadiationMesh()); else if (part instanceof Roof) for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { if (roofPart.getSceneHints().getCullHint() != CullHint.Always) { final Mesh mesh = (Mesh) ((Node) roofPart).getChild(6); applyTexture(mesh); } } part.drawHeatFlux(); } final Calendar today = Heliodon.getInstance().getCalender(); final String city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); final double[] outsideTemperatureRange = Weather.computeOutsideTemperature(today, city); for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) { final Foundation foundation = (Foundation) part; final int n = foundation.getHeatLoss().length; final double[] heatLoss = new double[n]; final double[] passiveSolar = new double[n]; final double[] photovoltaic = new double[n]; for (int i = 0; i < n; i++) { final double groundHeatLoss = foundation.getHeatLoss()[i]; // In most cases, the inside temperature is always higher than the ground temperature. In this winter, this adds to heating load, but in the summer, this reduces cooling load. // In other words, geothermal energy is good in hot conditions. This is similar to passive solar energy, which is good in the winter but bad in the summer. if (groundHeatLoss > 0) { final double outsideTemperature = Weather.getInstance().getOutsideTemperatureAtMinute(outsideTemperatureRange[1], outsideTemperatureRange[0], i * timeStep); if (outsideTemperature >= foundation.getThermostat().getTemperature(today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY, today.get(Calendar.HOUR_OF_DAY))) { heatLoss[i] -= groundHeatLoss; } } else { heatLoss[i] += groundHeatLoss; } } double solarPotentialTotal = 0.0; for (final HousePart houseChild : Scene.getInstance().getParts()) { if (houseChild.getTopContainer() == foundation) { houseChild.setSolarPotentialToday(0.0); for (int i = 0; i < n; i++) { solarPotentialTotal += houseChild.getSolarPotential()[i]; houseChild.setSolarPotentialToday(houseChild.getSolarPotentialToday() + houseChild.getSolarPotential()[i]); if (houseChild instanceof Wall || houseChild instanceof Door || houseChild instanceof Window || houseChild instanceof Roof) heatLoss[i] += houseChild.getHeatLoss()[i]; if (houseChild instanceof Window) { final Window window = (Window) houseChild; passiveSolar[i] += houseChild.getSolarPotential()[i] * window.getSolarHeatGainCoefficient(); } else if (houseChild instanceof SolarPanel) { final SolarPanel solarPanel = (SolarPanel) houseChild; photovoltaic[i] += houseChild.getSolarPotential()[i] * solarPanel.getEfficiency(); } } } } double heatingTotal = 0.0; double coolingTotal = 0.0; double passiveSolarTotal = 0.0; double photovoltaicTotal = 0.0; for (int i = 0; i < n; i++) { if (heatLoss[i] < 0) { heatLoss[i] -= passiveSolar[i]; } else { heatLoss[i] = Math.max(0, heatLoss[i] - passiveSolar[i]); } if (heatLoss[i] > 0) { heatingTotal += heatLoss[i]; } else { coolingTotal -= heatLoss[i]; } passiveSolarTotal += passiveSolar[i]; photovoltaicTotal += photovoltaic[i]; } foundation.setSolarPotentialToday(solarPotentialTotal); foundation.setSolarLabelValue(solarPotentialTotal); foundation.setPassiveSolarToday(passiveSolarTotal); foundation.setPhotovoltaicToday(photovoltaicTotal); foundation.setHeatingToday(heatingTotal); foundation.setCoolingToday(coolingTotal); foundation.setTotalEnergyToday(heatingTotal + coolingTotal - photovoltaicTotal); } } } public void computeEnergyAtHour(final int hour) { final Calendar today = Heliodon.getInstance().getCalender(); final String city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); final double[] outsideTemperatureRange = Weather.computeOutsideTemperature(today, city); final double outsideTemperature = Weather.getInstance().getOutsideTemperatureAtMinute(outsideTemperatureRange[1], outsideTemperatureRange[0], hour * 60); for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) { final Foundation foundation = (Foundation) part; if (foundation.getHeatLoss() == null) continue; final int n = (int) Math.round(60.0 / timeStep); final double[] heatLoss = new double[n]; final double[] passiveSolar = new double[n]; final double[] photovoltaic = new double[n]; final int t0 = n * hour; for (int i = 0; i < n; i++) { final double groundHeatLoss = foundation.getHeatLoss()[t0 + i]; if (groundHeatLoss > 0) { final double thermostat = foundation.getThermostat().getTemperature(today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY, today.get(Calendar.HOUR_OF_DAY)); if (outsideTemperature >= thermostat) { heatLoss[i] -= groundHeatLoss; } } else { heatLoss[i] += groundHeatLoss; } } double solarPotentialTotal = 0.0; for (final HousePart houseChild : Scene.getInstance().getParts()) { if (houseChild.getTopContainer() == foundation) { houseChild.setSolarPotentialNow(0); for (int i = 0; i < n; i++) { solarPotentialTotal += houseChild.getSolarPotential()[t0 + i]; houseChild.setSolarPotentialNow(houseChild.getSolarPotentialNow() + houseChild.getSolarPotential()[t0 + i]); if (houseChild instanceof Wall || houseChild instanceof Door || houseChild instanceof Window || houseChild instanceof Roof) heatLoss[i] += houseChild.getHeatLoss()[t0 + i]; if (houseChild instanceof Window) { final Window window = (Window) houseChild; passiveSolar[i] += houseChild.getSolarPotential()[t0 + i] * window.getSolarHeatGainCoefficient(); } else if (houseChild instanceof SolarPanel) { final SolarPanel solarPanel = (SolarPanel) houseChild; photovoltaic[i] += houseChild.getSolarPotential()[t0 + i] * solarPanel.getEfficiency(); } } } } double heatingTotal = 0.0; double coolingTotal = 0.0; double passiveSolarTotal = 0.0; double photovoltaicTotal = 0.0; for (int i = 0; i < n; i++) { if (heatLoss[i] < 0) { heatLoss[i] -= passiveSolar[i]; } else { heatLoss[i] = Math.max(0, heatLoss[i] - passiveSolar[i]); } if (heatLoss[i] > 0) { heatingTotal += heatLoss[i]; } else { coolingTotal -= heatLoss[i]; } passiveSolarTotal += passiveSolar[i]; photovoltaicTotal += photovoltaic[i]; } foundation.setSolarPotentialNow(solarPotentialTotal); foundation.setPassiveSolarNow(passiveSolarTotal); foundation.setPhotovoltaicNow(photovoltaicTotal); foundation.setHeatingNow(heatingTotal); foundation.setCoolingNow(coolingTotal); foundation.setTotalEnergyNow(heatingTotal + coolingTotal - photovoltaicTotal); } } } private void applyTexture(final Mesh mesh) { if (onMesh.get(mesh) == null) { mesh.setDefaultColor(ColorRGBA.BLUE); mesh.clearRenderState(StateType.Texture); return; } final double[][] solarData = onMesh.get(mesh).dailySolarIntensity; if (mesh.getUserData() != null && ((UserData) mesh.getUserData()).getHousePart() instanceof SolarPanel) { solarData[3][0] = solarData[2][0] = solarData[1][0]; solarData[3][1] = solarData[2][1] = solarData[1][0]; solarData[3][2] = solarData[2][2] = solarData[1][1]; solarData[3][3] = solarData[2][3] = solarData[1][1]; solarData[0][2] = solarData[1][2] = solarData[0][1]; solarData[0][3] = solarData[1][3] = solarData[0][1]; solarData[0][0] = solarData[1][0] = solarData[0][0]; solarData[0][1] = solarData[1][1] = solarData[0][0]; } fillBlanksWithNeighboringValues(solarData); final int rows = solarData.length; final int cols = solarData[0].length; final ByteBuffer data = BufferUtils.createByteBuffer(cols * rows * 3); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { final ColorRGBA color = computeColor(solarData[row][col], maxValue); data.put((byte) (color.getRed() * 255)).put((byte) (color.getGreen() * 255)).put((byte) (color.getBlue() * 255)); } } final Image image = new Image(ImageDataFormat.RGB, PixelDataType.UnsignedByte, cols, rows, data, null); final Texture2D texture = new Texture2D(); texture.setTextureKey(TextureKey.getRTTKey(MinificationFilter.NearestNeighborNoMipMaps)); texture.setImage(image); // texture.setWrap(WrapMode.Clamp); final TextureState textureState = new TextureState(); textureState.setTexture(texture); mesh.setDefaultColor(Scene.GRAY); mesh.setRenderState(textureState); } private void fillBlanksWithNeighboringValues(final double[][] solarData) { final int rows = solarData.length; final int cols = solarData[0].length; for (int repeat = 0; repeat < 2; repeat++) for (int row = 0; row < rows; row++) for (int col = 0; col < cols; col++) if (solarData[row][col] == -1) if (solarData[row][(col + 1) % cols] != -1) solarData[row][col] = solarData[row][(col + 1) % cols]; else if (col != 0 && solarData[row][col - 1] != -1) solarData[row][col] = solarData[row][col - 1]; else if (col == 0 && solarData[row][cols - 1] != -1) solarData[row][col] = solarData[row][cols - 1]; else if (solarData[(row + 1) % rows][col] != -1) solarData[row][col] = solarData[(row + 1) % rows][col]; else if (row != 0 && solarData[row - 1][col] != -1) solarData[row][col] = solarData[row - 1][col]; else if (row == 0 && solarData[rows - 1][col] != -1) solarData[row][col] = solarData[rows - 1][col]; } public ColorRGBA computeColor(final double value, final long maxValue) { final ReadOnlyColorRGBA[] colors = EnergyPanel.solarColors; long valuePerColorRange = maxValue / (colors.length - 1); final int colorIndex; if (valuePerColorRange == 0) { valuePerColorRange = 1; colorIndex = 0; } else colorIndex = (int) Math.min(value / valuePerColorRange, colors.length - 2); final float scalar = Math.min(1.0f, (float) (value - valuePerColorRange * colorIndex) / valuePerColorRange); final ColorRGBA color = new ColorRGBA().lerpLocal(colors[colorIndex], colors[colorIndex + 1], scalar); return color; } private int roundToPowerOfTwo(final int n) { return (int) Math.pow(2.0, Math.ceil(Math.log(n) / Math.log(2))); } public void setSolarStep(final double solarStep) { this.solarStep = solarStep; } public double getSolarStep() { return solarStep; } public void setTimeStep(final int timeStep) { this.timeStep = timeStep; } public int getTimeStep() { return timeStep; } public void setAirMassSelection(final int selection) { airMassSelection = selection; } public int getAirMassSelection() { return airMassSelection; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.wizard; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JPanel; public final class NewFileVisualPanel1 extends JPanel { private NewFileWizardPanel1 parentWizard; private JFileChooser chooser; /** Creates new form NewFileVisualPanel1 */ public NewFileVisualPanel1(NewFileWizardPanel1 parent, String dir) { super(); this.parentWizard = parent; initComponents(); nameField.setText(""); folderField.setText(dir); String loc = dir + (dir.endsWith(File.separator) ? "" : File.separator); fileField.setText(loc); chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setApproveButtonText("Select"); } @Override public String getName() { return "Step } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { nameField = new javax.swing.JTextField(); nameLabel = new javax.swing.JLabel(); folderLabel = new javax.swing.JLabel(); folderField = new javax.swing.JTextField(); fileField = new javax.swing.JTextField(); fileLabel = new javax.swing.JLabel(); customLabel = new javax.swing.JLabel(); customCombo = new javax.swing.JComboBox(); browseButton = new javax.swing.JButton(); errorLabel = new javax.swing.JLabel(); extField = new javax.swing.JTextField(); nameField.setText(org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.nameField.text")); // NOI18N nameField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { nameFieldKeyReleased(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(nameLabel, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.nameLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(folderLabel, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.folderLabel.text")); // NOI18N folderField.setText(org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.folderField.text")); // NOI18N folderField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { folderFieldKeyReleased(evt); } }); fileField.setEditable(false); fileField.setText(org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.fileField.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(fileLabel, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.fileLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(customLabel, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.customLabel.text")); // NOI18N customCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Add Empty Class", "Add Class with main method", "Add Mixin", "Add Enum", "Add Facet", "Leave Empty" })); org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.browseButton.text")); // NOI18N browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(errorLabel, org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.errorLabel.text")); // NOI18N extField.setText(org.openide.util.NbBundle.getMessage(NewFileVisualPanel1.class, "NewFileVisualPanel1.extField.text")); // NOI18N extField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { extFieldKeyReleased(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(customLabel) .add(nameLabel) .add(folderLabel) .add(fileLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, fileField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .add(customCombo, 0, 299, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, folderField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE) .add(nameField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)) .add(25, 25, 25) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(extField, 0, 0, Short.MAX_VALUE) .add(browseButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .add(errorLabel)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(nameLabel) .add(nameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(extField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(folderLabel) .add(folderField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(browseButton)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(fileField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(fileLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(customLabel) .add(customCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 113, Short.MAX_VALUE) .add(errorLabel) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void nameFieldKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_nameFieldKeyReleased {//GEN-HEADEREND:event_nameFieldKeyReleased updateFile(); }//GEN-LAST:event_nameFieldKeyReleased private void folderFieldKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_folderFieldKeyReleased {//GEN-HEADEREND:event_folderFieldKeyReleased updateFile(); }//GEN-LAST:event_folderFieldKeyReleased private void browseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_browseButtonActionPerformed {//GEN-HEADEREND:event_browseButtonActionPerformed int val = chooser.showDialog(this, "Select"); if (val == JFileChooser.APPROVE_OPTION) { folderField.setText(chooser.getSelectedFile().getPath()); updateFile(); } }//GEN-LAST:event_browseButtonActionPerformed private void extFieldKeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_extFieldKeyReleased {//GEN-HEADEREND:event_extFieldKeyReleased updateFile(); }//GEN-LAST:event_extFieldKeyReleased @Override public boolean isValid() { if (folderField == null) { return false; } String loc = folderField.getText(); String file = fileField.getText(); String err = ""; String name = nameField.getText(); if (loc == null || loc.length() < 1) { err = "Please choose a folder."; } else { File locF = new File(loc); if (!locF.exists() || !locF.isDirectory() || !locF.canWrite()) { err = "Folder must be an existing, writable directory."; } else { if (!checkName(name)) { err = "Please enter a valid name."; } else if (new File(file).exists()) { err = "This file already exists."; } } } //warnings if (name.indexOf(".") != -1) { errorLabel.setText("Warning: Not expecting a dot in Name."); } if (extField.getText().indexOf(".") != 0) { errorLabel.setText("Warning: File extension missing."); } errorLabel.setText(err); return err.length() == 0; } private void updateFile() { String dir = folderField.getText(); dir += (dir.endsWith(File.separator) ? "" : File.separator) + nameField.getText() + extField.getText(); fileField.setText(dir); // will recheck that it's valid parentWizard.fireChangeEvent(); } private boolean checkName(String text) { return FanPodPanel1.VALID_NAME.matcher(text).matches(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseButton; private javax.swing.JComboBox customCombo; private javax.swing.JLabel customLabel; private javax.swing.JLabel errorLabel; private javax.swing.JTextField extField; private javax.swing.JTextField fileField; private javax.swing.JLabel fileLabel; private javax.swing.JTextField folderField; private javax.swing.JLabel folderLabel; private javax.swing.JTextField nameField; private javax.swing.JLabel nameLabel; // End of variables declaration//GEN-END:variables String getFile() { return fileField.getText(); } int getComboChoice() { return customCombo.getSelectedIndex(); } String getFileName() { return nameField.getText(); } }
package org.github.etcd.viewer.html.node; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.inject.Inject; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.ChainingModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.github.etcd.service.EtcdProxyFactory; import org.github.etcd.service.api.EtcdNode; import org.github.etcd.service.api.EtcdProxy; import org.github.etcd.viewer.ConvertUtils; import org.github.etcd.viewer.html.modal.TriggerModalLink; import org.github.etcd.viewer.html.pages.NavigationPage; import org.github.etcd.viewer.html.pages.NavigationPageLink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EtcdNodePanel extends GenericPanel<EtcdNode> { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(EtcdNodePanel.class); private static final Comparator<EtcdNode> NODE_SORTER = new Comparator<EtcdNode>() { @Override public int compare(EtcdNode o1, EtcdNode o2) { if (o1.isDir() == o2.isDir()) { return o1.getKey().compareTo(o2.getKey()); } if (o1.isDir()) { return -1; } if (o2.isDir()) { return 1; } return 0; } }; public static final String ROOT_KEY = "/"; private static final List<String> ROOT_BREADCRUMB = Collections.unmodifiableList(Arrays.asList(ROOT_KEY)); private IModel<EtcdNode> actionModel = Model.of(new EtcdNode()); private IModel<Boolean> updating = Model.of(false); private EditNodeModalPanel editNodeModal; private DeleteNodeModalPanel deleteNodeModal; private WebMarkupContainer breadcrumbAndActions; private WebMarkupContainer contents; @Inject private EtcdProxyFactory proxyFactory; private IModel<String> registry; private final IModel<String> key; private final IModel<String> parentKey; public EtcdNodePanel(String id, IModel<String> etcdRegistry, IModel<String> keyModel) { super(id); this.registry = etcdRegistry; this.key = keyModel; setModel(new LoadableDetachableModel<EtcdNode>() { private static final long serialVersionUID = 1L; @Override protected EtcdNode load() { if (registry.getObject() == null) { return null; } try (EtcdProxy p = proxyFactory.getEtcdProxy(registry.getObject())) { return p.getNode(key.getObject()); } catch (Exception e) { log.warn(e.getLocalizedMessage(), e); // TODO: handle this exception and show some alert on page error("Could not retrieve key " + key.getObject() + ": " + e.toString()); EtcdNodePanel.this.setEnabled(false); return null; } } }); parentKey = new ParentKeyModel(); setOutputMarkupId(true); createModalPanels(); add(breadcrumbAndActions = new WebMarkupContainer("breadcrumbAndActions")); breadcrumbAndActions.setOutputMarkupId(true); createBreadcrumb(); createNodeActions(); add(new WebMarkupContainer("icon").add(new AttributeModifier("class", new StringResourceModel("icon.node.dir.${dir}", getModel(), "")))); add(new Label("key", new PropertyModel<>(getModel(), "key"))); add(contents = new WebMarkupContainer("contents")); contents.setOutputMarkupId(true); WebMarkupContainer currentNode; contents.add(currentNode = new WebMarkupContainer("currentNode")); currentNode.add(new AttributeAppender("class", new StringResourceModel("nodeClass", getModel(), "") , " ")); currentNode.add(new Label("createdIndex", new PropertyModel<>(getModel(), "createdIndex"))); currentNode.add(new Label("modifiedIndex", new PropertyModel<>(getModel(), "modifiedIndex"))); currentNode.add(new Label("ttl", new PropertyModel<>(getModel(), "ttl"))); currentNode.add(new Label("expiration", new PropertyModel<>(getModel(), "expiration"))); contents.add(new TriggerModalLink<EtcdNode>("editValue", getModel(), editNodeModal) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) { add(AttributeAppender.append("disabled", "disabled")); } else { add(AttributeModifier.remove("disabled")); } // hide value for directory entries setVisible(EtcdNodePanel.this.getModelObject() != null && !EtcdNodePanel.this.getModelObject().isDir()); } @Override protected void onModalTriggerClick(AjaxRequestTarget target) { updating.setObject(true); actionModel.setObject(getModelObject()); } } .add(new MultiLineLabel("value", new PropertyModel<>(getModel(), "value")))); AbstractLink goUp; contents.add(goUp = createNavigationLink("goUp", parentKey)); goUp.add(new Behavior() { private static final long serialVersionUID = 1L; @Override public void onConfigure(Component component) { super.onConfigure(component); component.setEnabled(key.getObject() != null && !"".equals(key.getObject()) && !"/".equals(key.getObject())); } }); contents.add(createNodesView("nodes")); } @Override protected void onDetach() { super.onDetach(); registry.detach(); key.detach(); parentKey.detach(); } protected void onNodeKeyUpdated(AjaxRequestTarget target) { } protected void onNodedSaved(AjaxRequestTarget target) { } protected void onNodedDeleted(AjaxRequestTarget target) { } private void createModalPanels() { add(editNodeModal = new EditNodeModalPanel("editNodeModal", actionModel, registry, updating) { private static final long serialVersionUID = 1L; @Override protected void onNodeSaved(AjaxRequestTarget target) { super.onNodeSaved(target); target.add(contents); EtcdNodePanel.this.onNodedSaved(target); } }); add(deleteNodeModal = new DeleteNodeModalPanel("deleteNodeModal", actionModel, registry) { private static final long serialVersionUID = 1L; @Override protected void onNodeDeleted(AjaxRequestTarget target) { super.onNodeDeleted(target); PageParameters params = ConvertUtils.getPageParameters(parentKey.getObject()); params.add("cluster", registry.getObject()); setResponsePage(NavigationPage.class, params); key.setObject(parentKey.getObject()); // target.add(EtcdNodePanel.this); onNodeKeyUpdated(target); target.add(contents, breadcrumbAndActions); EtcdNodePanel.this.onNodedDeleted(target); } }); } private void createNodeActions() { breadcrumbAndActions.add(new TriggerModalLink<Void>("addNode", editNodeModal) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (EtcdNodePanel.this.getModelObject() != null && EtcdNodePanel.this.getModelObject().isDir()) { add(AttributeModifier.remove("disabled")); } else { add(AttributeAppender.append("disabled", "disabled")); } } @Override protected void onModalTriggerClick(AjaxRequestTarget target) { updating.setObject(false); actionModel.setObject(new EtcdNode()); String currentKey = key != null? key.getObject() : ""; StringBuffer newKey = new StringBuffer(currentKey); if (!currentKey.endsWith("/")) { newKey.append('/'); } newKey.append("new_node"); actionModel.getObject().setKey(newKey.toString()); } }); breadcrumbAndActions.add(new TriggerModalLink<EtcdNode>("editNode", getModel(), editNodeModal) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) { add(AttributeAppender.append("disabled", "disabled")); } else { add(AttributeModifier.remove("disabled")); } } @Override protected void onModalTriggerClick(AjaxRequestTarget target) { updating.setObject(true); actionModel.setObject(getModelObject()); } }); breadcrumbAndActions.add(new TriggerModalLink<EtcdNode>("deleteNode", getModel(), deleteNodeModal) { private static final long serialVersionUID = 1L; @Override protected void onConfigure() { super.onConfigure(); if (key.getObject() == null || "".equals(key.getObject()) || "/".equals(key.getObject())) { add(AttributeAppender.append("disabled", "disabled")); } else { add(AttributeModifier.remove("disabled")); } } @Override protected void onModalTriggerClick(AjaxRequestTarget target) { actionModel.setObject(getModelObject()); } }); } private void createBreadcrumb() { IModel<List<String>> breadcrumb = new ChainingModel<List<String>>(new PropertyModel<>(getModel(), "key")) { private static final long serialVersionUID = 1L; @Override public List<String> getObject() { @SuppressWarnings("unchecked") String key = ((IModel<String>) super.getChainedModel()).getObject(); if (key == null || key.length() == 0 || "/".equals(key)) { return ROOT_BREADCRUMB; } List<String> crumbs = new ArrayList<>(); int index = -1; while ((index = key.indexOf('/', index + 1)) != -1) { if (index == 0) { crumbs.add("/"); } else { crumbs.add(key.substring(0, index)); } } crumbs.add(key); return crumbs; } }; breadcrumbAndActions.add(new ListView<String>("breadcrumb", breadcrumb) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<String> item) { AbstractLink link; item.add(link = createNavigationLink("key", item.getModel())); link.add(new Label("label", new KeyLabelModel(item.getModel()))); // Last breadcrumb part should be active if (item.getIndex() == getViewSize() - 1) { item.add(new AttributeAppender("class", Model.of("active"), " ")); item.setEnabled(false); } } }); } private Component createNodesView(String id) { IModel<List<EtcdNode>> nodes = new LoadableDetachableModel<List<EtcdNode>>() { private static final long serialVersionUID = 1L; @Override protected List<EtcdNode> load() { if (getModelObject() == null || getModelObject().getNodes() == null) { return Collections.emptyList(); } List<EtcdNode> nodes = getModelObject().getNodes(); Collections.sort(nodes, NODE_SORTER); return nodes; } }; return new ListView<EtcdNode>(id, nodes) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<EtcdNode> item) { item.add(new AttributeModifier("class", new StringResourceModel("nodeClass", item.getModel(), ""))); AbstractLink link; item.add(link = createNavigationLink("key", new PropertyModel<String>(item.getModel(), "key"))); link.add(new Label("label", new KeyLabelModel(new PropertyModel<String>(item.getModel(), "key")))); item.add(new MultiLineLabel("value", new PropertyModel<>(item.getModel(), "value"))); item.add(new Label("createdIndex", new PropertyModel<>(item.getModel(), "createdIndex"))); item.add(new Label("modifiedIndex", new PropertyModel<>(item.getModel(), "modifiedIndex"))); item.add(new Label("ttl", new PropertyModel<>(item.getModel(), "ttl"))); item.add(new Label("expiration", new PropertyModel<>(item.getModel(), "expiration"))); } }; } private AbstractLink createNavigationLink(final String id, final IModel<String> targetKey) { return new NavigationPageLink(id, registry, targetKey); /* return new AjaxLink<String>(id, targetKey) { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { key.setObject(getModelObject()); target.add(EtcdNodePanel.this); onNodeKeyUpdated(target); } @Override public String getBeforeDisabledLink() { return ""; } @Override public String getAfterDisabledLink() { return ""; } @Override protected void onConfigure() { super.onConfigure(); setEnabled(selectedCluster != null && selectedCluster.getObject() != null && getModelObject() != null ); } };*/ } private class ParentKeyModel extends LoadableDetachableModel<String> { private static final long serialVersionUID = 1L; @Override protected String load() { String etcdKey = key.getObject(); if (etcdKey == null || etcdKey.indexOf('/') == -1 || "/".equals(etcdKey)) { return etcdKey; } if (etcdKey.endsWith("/")) { // Find the 2nd to last / return etcdKey.substring(0, etcdKey.lastIndexOf('/', etcdKey.length()-2)); } else { return etcdKey.substring(0, etcdKey.lastIndexOf('/')); } } } private class KeyLabelModel extends ChainingModel<String> { private static final long serialVersionUID = 1L; public KeyLabelModel(IModel<String> keyModel) { super(keyModel); } public KeyLabelModel(String key) { super(key); } @Override public String getObject() { String etcdKey = super.getObject(); if (etcdKey == null || etcdKey.indexOf('/') == -1 || "/".equals(etcdKey)) { return etcdKey; } if (etcdKey.endsWith("/")) { return etcdKey.substring(etcdKey.lastIndexOf('/', etcdKey.length()-2) + 1); } else { return etcdKey.substring(etcdKey.lastIndexOf('/') + 1); } } } }
package org.hummingbirdlang.types.concrete; import org.hummingbirdlang.nodes.builtins.BuiltinNodes; import org.hummingbirdlang.types.MethodProperty; import org.hummingbirdlang.types.Property; import org.hummingbirdlang.types.PropertyNotFoundException; import org.hummingbirdlang.types.UnknownType; import org.hummingbirdlang.types.realize.Index.Module; public final class IntegerType extends BootstrappableConcreteType { public static String BUILTIN_NAME = "Integer"; private MethodType toString; @Override public String getBootstrapName() { return IntegerType.BUILTIN_NAME; } @Override public void bootstrapBuiltins(BuiltinNodes builtins) { this.toString = new MethodType(this, new UnknownType(), "toString", builtins.getCallTarget("Integer", "toString")); } @Override public void bootstrapTypes(Module indexModule) { this.toString = this.toString.cloneWithReturnType(indexModule.get(StringType.BUILTIN_NAME)); } @Override public Property getProperty(String name) throws PropertyNotFoundException { switch (name) { case "toString": return MethodProperty.fromType(this.toString); default: throw new PropertyNotFoundException(this, name); } } @Override public String toString() { return "$Integer"; } }
package org.jvnet.hudson.plugins.monitoring; import hudson.Plugin; import hudson.model.Hudson; import hudson.util.PluginServletFilter; import java.io.File; /** * Entry point of the plugin. * * <p> * There must be one {@link Plugin} class in each plugin. * See javadoc of {@link Plugin} for more about what can be done on this class. * * @author Emeric Vernat */ public class PluginImpl extends Plugin { @Override public void start() throws Exception { super.start(); // on active les actions syst?mes (gc, heap dump, histogramme m?moire, processus...), sauf si l'administrateur a dit diff?remment if (System.getProperty("javamelody.system-actions-enabled") == null) { System.setProperty("javamelody.system-actions-enabled", "true"); } // on d?sactive les graphiques jdbc et statistiques sql puisqu'il n'y en aura pas if (System.getProperty("javamelody.no-database") == null) { System.setProperty("javamelody.no-database", "true"); } // le r?pertoire de stockage est dans le r?pertoire de hudson au lieu d'?tre dans le r?pertoire temporaire // ("/" initial n?cessaire sous windows pour javamelody v1.8.1) if (System.getProperty("javamelody.storage-directory") == null) { System.setProperty("javamelody.storage-directory", "/" + new File(Hudson.getInstance().getRootDir(),"monitoring").getAbsolutePath()); } // google-analytics pour conna?tre le nombre d'installations actives et pour conna?tre les fonctions les plus utilis?es if (System.getProperty("javamelody.analytics-id") == null) { System.setProperty("javamelody.analytics-id", "UA-1335263-7"); } PluginServletFilter.addFilter(new HudsonMonitoringFilter()); // TODO on pourrait ajouter un counter de nom job avec les temps de build } }
package oo.encapsulamento.exemplo1.correto; import java.math.BigDecimal; import javax.swing.JFrame; import javax.swing.JTextField; @SuppressWarnings("serial") public class InterfaceSwing extends JPanel { private JTextField campoValorTotalVenda; private Venda venda; public void atualizarValorTotalVenda() { // Trecho 1 BigDecimal valorTotalVenda = venda.calcularValorTotal(); // Trecho 2 campoValorTotalVenda.setText(valorTotalVenda.toString()); } }
package org.markdownwriterfx.projects; import java.io.File; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.ListCell; import javafx.scene.control.Tooltip; import javafx.scene.layout.StackPane; import org.markdownwriterfx.FileEditorManager; import org.markdownwriterfx.Messages; import org.markdownwriterfx.util.Utils; /** * A combo box that contains recently opened projects and allows switching active project. * * @author Karl Tauber */ class ProjectsComboBox extends ComboBox<File> { private static final File OPEN_FOLDER = new File(""); private static final Comparator<File> PROJECT_COMPARATOR = (f1, f2) -> f1.getPath().compareToIgnoreCase(f2.getPath()); private boolean inSelectionChange; private boolean doNotHidePopupOnce; ProjectsComboBox(FileEditorManager fileEditorManager) { getStyleClass().add("projects-combo-box"); setFocusTraversable(false); setVisibleRowCount(30); setButtonCell(new ProjectButtonCell()); setCellFactory(listView -> new ProjectListCell()); // let this control grow horizontally setMaxWidth(Double.MAX_VALUE); // update tooltip valueProperty().addListener((observer, oldProject, newProject) -> { setTooltip((newProject != null) ? new Tooltip(newProject.getAbsolutePath()) : null); }); // add items ObservableList<File> projects = ProjectManager.getProjects(); projects.sort(PROJECT_COMPARATOR); getItems().add(OPEN_FOLDER); getItems().addAll(projects); // set active project setValue(ProjectManager.getActiveProject()); // listen to selection changes getSelectionModel().selectedItemProperty().addListener((observer, oldProject, newProject) -> { if (inSelectionChange) return; if (newProject == ProjectManager.getActiveProject()) return; Platform.runLater(() -> { inSelectionChange = true; try { if (newProject == OPEN_FOLDER) { // closing last active project automatically selects this item // --> activate first project if (oldProject != null && !getItems().contains(oldProject)) { ProjectManager.setActiveProject((getItems().size() > 1) ? getItems().get(1) : null); return; } getSelectionModel().select(oldProject); if (fileEditorManager.canOpenAnotherProject()) ProjectManager.openProject(getScene().getWindow()); } else { if (fileEditorManager.canOpenAnotherProject()) ProjectManager.setActiveProject(newProject); else getSelectionModel().select(oldProject); } } finally { inSelectionChange = false; } }); }); // listen to projects changes and update combo box projects.addListener((ListChangeListener<File>) change -> { while (change.next()) { if (change.wasAdded()) { for (File addedProject : change.getAddedSubList()) Utils.addSorted(getItems(), addedProject, PROJECT_COMPARATOR); } if (change.wasRemoved()) getItems().removeAll(change.getRemoved()); } }); // listen to active project change and update combo box value ProjectManager.activeProjectProperty().addListener((observer, oldProject, newProject) -> { setValue(newProject); }); } @Override public void hide() { if (doNotHidePopupOnce) { doNotHidePopupOnce = false; return; } super.hide(); } private class ProjectButtonCell extends ListCell<File> { @Override protected void updateItem(File item, boolean empty) { super.updateItem(item, empty); setText((!empty && item != null) ? buildUniqueName(item) : null); } private String buildUniqueName(File item) { String name = item.getName(); // find other projects with same name List<File> projects = getItems().stream() .filter(f -> !f.equals(item) && f.getName().equals(name)) .collect(Collectors.toList()); if (projects.isEmpty()) return name; // there are more than one project with the same name // --> go up folder hierarchy and find a unique name File itemParent = item.getParentFile(); while (itemParent != null) { // parent of projects projects = projects.stream() .map(f -> f.getParentFile()) .filter(f -> f != null) .collect(Collectors.toList()); String n = itemParent.getName(); if (n.isEmpty()) break; // find unique parent name long equalCount = projects.stream() .filter(f -> f.getName().equals(n)) .count(); if (equalCount == 0) return name + " [" + itemParent.getName() + "]"; itemParent = itemParent.getParentFile(); } // fallback: append path return name + " - " + item.getParent(); } } private class ProjectListCell extends ListCell<File> { private final StackPane closeButton = new StackPane(); ProjectListCell() { closeButton.getStyleClass().add("close-project-button"); closeButton.setPrefSize(16, 16); closeButton.setOnMousePressed( event -> { event.consume(); doNotHidePopupOnce = true; ProjectManager.getProjects().remove(getItem()); }); } @Override protected void updateItem(File item, boolean empty) { super.updateItem(item, empty); // add/remove separator below "open folder" item if (!empty && item == OPEN_FOLDER && ProjectsComboBox.this.getItems().size() > 1) getStyleClass().add("open-project"); else getStyleClass().remove("open-project"); String text = null; Node graphic = null; if (!empty && item != null) { text = (item == OPEN_FOLDER) ? Messages.get("ProjectsComboBox.openProject") : item.getAbsolutePath(); graphic = closeButton; closeButton.setVisible(item != OPEN_FOLDER); } setText(text); setGraphic(graphic); } } }
package org.anddev.andengine.ui.activity; import org.anddev.andengine.audio.sound.SoundManager; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.WakeLockOptions; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.opengl.view.RenderSurfaceView; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.ui.IGameInterface; import android.content.Context; import android.content.pm.ActivityInfo; import android.hardware.SensorManager; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.DisplayMetrics; import android.view.Window; import android.view.WindowManager; import android.view.ViewGroup.LayoutParams; /** * @author Nicolas Gramlich * @since 11:27:06 - 08.03.2010 */ public abstract class BaseGameActivity extends BaseActivity implements IGameInterface { // Constants // Fields protected Engine mEngine; private WakeLock mWakeLock; protected RenderSurfaceView mRenderSurfaceView; // Constructors @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mEngine = this.onLoadEngine(); this.applyEngineOptions(this.mEngine.getEngineOptions()); this.onSetContentView(); this.onLoadResources(); final Scene scene = this.onLoadScene(); this.mEngine.onLoadComplete(scene); this.onLoadComplete(); } @Override protected void onResume() { super.onResume(); this.mRenderSurfaceView.onResume(); this.mEngine.onResume(); this.mEngine.start(); this.acquireWakeLock(this.mEngine.getEngineOptions().getWakeLockOptions()); } @Override protected void onPause() { super.onPause(); this.releaseWakeLock(); this.mEngine.onPause(); this.mRenderSurfaceView.onPause(); } // Getter & Setter public Engine getEngine() { return this.mEngine; } public SoundManager getSoundManager() { return this.mEngine.getSoundManager(); } // Methods for/from SuperClass/Interfaces // Methods protected void onSetContentView() { this.mRenderSurfaceView = new RenderSurfaceView(this, this.mEngine); this.mRenderSurfaceView.setEGLConfigChooser(false); this.mRenderSurfaceView.applyRenderer(); this.setContentView(this.mRenderSurfaceView, this.createSurfaceViewLayoutParams()); } private void acquireWakeLock(final WakeLockOptions pWakeLockOptions) { final PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); this.mWakeLock = pm.newWakeLock(pWakeLockOptions.getFlag() | PowerManager.ON_AFTER_RELEASE, "AndEngine"); this.mWakeLock.acquire(); } private void releaseWakeLock() { if(this.mWakeLock != null) { this.mWakeLock.release(); } } private void applyEngineOptions(final EngineOptions pEngineOptions) { if(pEngineOptions.isFullscreen()) { this.applyFullscreen(); } switch(pEngineOptions.getScreenOrientation()){ case LANDSCAPE: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case PORTRAIT: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; } } protected LayoutParams createSurfaceViewLayoutParams() { final DisplayMetrics displayMetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); return this.mEngine.getEngineOptions().getResolutionPolicy().createLayoutParams(displayMetrics); } private void applyFullscreen() { final Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); window.requestFeature(Window.FEATURE_NO_TITLE); } protected void enableVibrator() { this.mEngine.enableVibrator(this); } protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener); } /** * @param pAccelerometerListener * @param pRate one of: {@link SensorManager#SENSOR_DELAY_FASTEST}, {@link SensorManager#SENSOR_DELAY_GAME}, {@link SensorManager#SENSOR_DELAY_UI}, {@link SensorManager#SENSOR_DELAY_NORMAL} * @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise. */ protected boolean enableAccelerometerSensor(final IAccelerometerListener pAccelerometerListener, final int pRate) { return this.mEngine.enableAccelerometerSensor(this, pAccelerometerListener, pRate); } protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener) { return this.mEngine.enableOrientationSensor(this, pOrientationListener); } /** * @param pOrientationListener * @param pRate one of: {@link SensorManager#SENSOR_DELAY_FASTEST}, {@link SensorManager#SENSOR_DELAY_GAME}, {@link SensorManager#SENSOR_DELAY_UI}, {@link SensorManager#SENSOR_DELAY_NORMAL} * @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise. */ protected boolean enableOrientationSensor(final IOrientationListener pOrientationListener, final int pRate) { return this.mEngine.enableOrientationSensor(this, pOrientationListener, pRate); } // Inner and Anonymous Classes }
package org.markdownwriterfx.spellchecker; import static javafx.scene.input.KeyCode.COMMA; import static javafx.scene.input.KeyCode.PERIOD; import static javafx.scene.input.KeyCombination.SHORTCUT_DOWN; import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed; import static org.fxmisc.wellbehaved.event.InputMap.consume; import static org.fxmisc.wellbehaved.event.InputMap.sequence; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.WeakInvalidationListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.geometry.Bounds; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.CustomMenuItem; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.text.TextFlow; import org.apache.commons.lang3.StringUtils; import org.fxmisc.richtext.StyleClassedTextArea; import org.fxmisc.richtext.model.PlainTextChange; import org.fxmisc.wellbehaved.event.Nodes; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.language.AmericanEnglish; import org.languagetool.markup.AnnotatedText; import org.languagetool.markup.AnnotatedTextBuilder; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.spelling.SpellingCheckRule; import org.markdownwriterfx.Messages; import org.markdownwriterfx.editor.MarkdownEditorPane; import org.markdownwriterfx.editor.ParagraphOverlayGraphicFactory; import org.markdownwriterfx.options.Options; import org.reactfx.EventStream; import org.reactfx.Subscription; import org.reactfx.util.FxTimer; import org.reactfx.util.Timer; import org.reactfx.util.Try; import com.vladsch.flexmark.ast.Block; import com.vladsch.flexmark.ast.Code; import com.vladsch.flexmark.ast.HardLineBreak; import com.vladsch.flexmark.ast.Heading; import com.vladsch.flexmark.ast.Node; import com.vladsch.flexmark.ast.NodeVisitor; import com.vladsch.flexmark.ast.Paragraph; import com.vladsch.flexmark.ast.SoftLineBreak; import com.vladsch.flexmark.ast.Text; /** * Spell checker for an instance of StyleClassedTextArea * * @author Karl Tauber */ public class SpellChecker { private final MarkdownEditorPane editor; private final StyleClassedTextArea textArea; private final ParagraphOverlayGraphicFactory overlayGraphicFactory; private final InvalidationListener optionsListener; private ContextMenu quickFixMenu; private int lastQuickFixNavigationDirection; private List<SpellBlockProblems> spellProblems; private Subscription textChangesSubscribtion; private SpellCheckerOverlayFactory spellCheckerOverlayFactory; // global executor used for all spell checking private static ExecutorService executor; // global JLanguageTool used in executor private static JLanguageTool languageTool; // global ResultCache used by global JLanguageTool private static ResultCacheEx cache; // global user dictionary private static UserDictionary userDictionary; // global ignored words (keeps ignored words when switching spell checking off and on) private static Set<String> wordsToBeIgnored = new HashSet<>(); public SpellChecker(MarkdownEditorPane editor, StyleClassedTextArea textArea, ParagraphOverlayGraphicFactory overlayGraphicFactory) { this.editor = editor; this.textArea = textArea; this.overlayGraphicFactory = overlayGraphicFactory; enableDisable(); Nodes.addInputMap(textArea, sequence( consume(keyPressed(PERIOD, SHORTCUT_DOWN), this::navigateNext), consume(keyPressed(COMMA, SHORTCUT_DOWN), this::navigatePrevious) )); // listen to option changes optionsListener = e -> { if (textArea.getScene() == null) return; // editor closed but not yet GCed if (e == Options.spellCheckerProperty()) enableDisable(); else if (e == Options.userDictionaryProperty()) { languageTool = null; cache = null; userDictionary = null; spellProblems = null; checkAsync(true); } }; WeakInvalidationListener weakOptionsListener = new WeakInvalidationListener(optionsListener); Options.spellCheckerProperty().addListener(weakOptionsListener); Options.userDictionaryProperty().addListener(weakOptionsListener); } private void enableDisable() { boolean spellChecker = Options.isSpellChecker(); if (spellChecker && spellCheckerOverlayFactory == null) { if (executor == null) { executor = Executors.newSingleThreadExecutor(runnable -> { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); // allow quitting app without shutting down executor return thread; }); } // listen to text changes and invoke spell checker after a delay EventStream<PlainTextChange> textChanges = textArea.plainTextChanges(); textChangesSubscribtion = textChanges .hook(this::updateSpellRangeOffsets) .successionEnds(Duration.ofMillis(500)) .supplyTask(() -> checkAsync(false)) .awaitLatest(textChanges) .subscribe(this::checkFinished); spellCheckerOverlayFactory = new SpellCheckerOverlayFactory(() -> spellProblems); overlayGraphicFactory.addOverlayFactory(spellCheckerOverlayFactory); checkAsync(true); } else if (!spellChecker && spellCheckerOverlayFactory != null) { textChangesSubscribtion.unsubscribe(); textChangesSubscribtion = null; overlayGraphicFactory.removeOverlayFactory(spellCheckerOverlayFactory); spellCheckerOverlayFactory = null; languageTool = null; cache = null; userDictionary = null; spellProblems = null; if (executor != null) { executor.shutdown(); executor = null; } } } private Task<List<SpellBlockProblems>> checkAsync(boolean invokeFinished) { Node astRoot = editor.getMarkdownAST(); boolean updatePeriodically = (spellProblems == null || spellProblems.isEmpty()); Task<List<SpellBlockProblems>> task = new Task<List<SpellBlockProblems>>() { @Override protected List<SpellBlockProblems> call() throws Exception { return check(astRoot, updatePeriodically); } @Override protected void succeeded() { if (invokeFinished) checkFinished(Try.success(getValue())); } @Override protected void failed() { if (invokeFinished) checkFinished(Try.failure(getException())); } }; executor.execute(task); return task; } private void checkFinished(Try<List<SpellBlockProblems>> result) { if (overlayGraphicFactory == null) return; // ignore result; user turned spell checking off if (result.isSuccess()) { spellProblems = result.get(); overlayGraphicFactory.update(); } else { //TODO result.getFailure().printStackTrace(); } } private List<SpellBlockProblems> check(Node astRoot, boolean updatePeriodically) throws IOException { if (languageTool == null) { Language language = new AmericanEnglish(); cache = new ResultCacheEx(10000, 1, TimeUnit.DAYS); languageTool = new JLanguageTool(language, null, cache); languageTool.disableRule("WHITESPACE_RULE"); userDictionary = new UserDictionary(); addIgnoreTokens(userDictionary.getWords()); addIgnoreTokens(Arrays.asList(wordsToBeIgnored.toArray(new String[wordsToBeIgnored.size()]))); } // find nodes that should be checked ArrayList<Node> nodesToCheck = new ArrayList<>(); NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) { @Override public void visit(Node node) { if (node instanceof Paragraph || node instanceof Heading) nodesToCheck.add(node); if (node instanceof Block) visitChildren(node); } }; visitor.visit(astRoot); ArrayList<SpellBlockProblems> spellProblems = new ArrayList<>(); // start timer to update overlays periodically during a lengthy check (on initial run) // using FxTimer instead of Timeline because FxTimer makes sure // the action is not executed after invoking FxTimer.stop(), // which may happen for Timeline Timer timer = updatePeriodically ? FxTimer.runPeriodically(Duration.ofMillis(350), () -> { ArrayList<SpellBlockProblems> spellProblems2; synchronized (spellProblems) { spellProblems2 = new ArrayList<>(spellProblems); } checkFinished(Try.success(spellProblems2)); }) : null; // check spelling of nodes try { for (Node node : nodesToCheck) { AnnotatedText annotatedText = annotatedNodeText(node); List<RuleMatch> ruleMatches = languageTool.check(annotatedText); SpellBlockProblems problem = new SpellBlockProblems(node.getStartOffset(), node.getEndOffset(), ruleMatches); synchronized (spellProblems) { spellProblems.add(problem); } } } finally { if (timer != null) timer.stop(); } return spellProblems; } private AnnotatedText annotatedNodeText(Node node) { AnnotatedTextBuilder builder = new AnnotatedTextBuilder(); NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) { int prevTextEnd = node.getStartOffset(); @Override public void visit(Node node) { if (node instanceof Text) addText(node.getStartOffset(), node.getChars().toString()); else if (node instanceof Code) addText(((Code)node).getText().getStartOffset(), ((Code)node).getText().toString()); else if (node instanceof SoftLineBreak) addText(node.getStartOffset(), " "); else if (node instanceof HardLineBreak) addText(node.getStartOffset(), "\n"); else visitChildren(node); } private void addText(int start, String text) { if (start > prevTextEnd) builder.addMarkup(getMarkupFiller(start - prevTextEnd)); builder.addText(text); prevTextEnd = start + text.length(); } }; visitor.visit(node); return builder.build(); } private static final ArrayList<String> markupFiller = new ArrayList<>(); private String getMarkupFiller(int length) { if (markupFiller.isEmpty()) { for (int i = 1; i <= 16; i++) markupFiller.add(StringUtils.repeat(' } if (length <= markupFiller.size()) return markupFiller.get(length - 1); return StringUtils.repeat('#', length); } private void updateSpellRangeOffsets(PlainTextChange e) { if (spellProblems == null) return; int position = e.getPosition(); int inserted = e.getInserted().length(); int removed = e.getRemoved().length(); for (SpellBlockProblems blockProblems : spellProblems) blockProblems.updateOffsets(position, inserted, removed); } private void showQuickFixMenu() { editor.hideContextMenu(); ContextMenu quickFixMenu = new ContextMenu(); initQuickFixMenu(quickFixMenu, textArea.getCaretPosition(), false); if (quickFixMenu.getItems().isEmpty()) return; Optional<Bounds> caretBounds = textArea.getCaretBounds(); if (!caretBounds.isPresent()) return; // show context menu quickFixMenu.show(textArea, caretBounds.get().getMaxX(), caretBounds.get().getMaxY()); this.quickFixMenu = quickFixMenu; } public void initContextMenu(ContextMenu contextMenu, int characterIndex) { initQuickFixMenu(contextMenu, characterIndex, true); lastQuickFixNavigationDirection = 0; ObservableList<MenuItem> menuItems = contextMenu.getItems(); // add separator (if necessary) if (!menuItems.isEmpty()) menuItems.add(new SeparatorMenuItem()); // add "Check Spelling and Grammar" item CheckMenuItem checkSpellingItem = new CheckMenuItem(Messages.get("SpellChecker.checkSpelling")); checkSpellingItem.selectedProperty().bindBidirectional(Options.spellCheckerProperty()); menuItems.add(checkSpellingItem); } private void initQuickFixMenu(ContextMenu contextMenu, int characterIndex, boolean addNavigation) { if( languageTool == null ) return; // find problems List<SpellProblem> problems = findProblemsAt(characterIndex); // create menu items ArrayList<MenuItem> newItems = new ArrayList<>(); for (SpellProblem problem : problems) { CustomMenuItem problemItem = new SeparatorMenuItem(); problemItem.setContent(buildMessage(problem.getMessage())); newItems.add(problemItem); List<String> suggestedReplacements = problem.getSuggestedReplacements(); if (!suggestedReplacements.isEmpty()) { for (String suggestedReplacement : suggestedReplacements) { MenuItem item = new MenuItem(suggestedReplacement); item.getStyleClass().add("spell-menu-suggestion"); item.setOnAction(e -> { textArea.replaceText(problem.getFromPos(), problem.getToPos(), suggestedReplacement); navigateNextPrevious(); }); newItems.add(item); } } else { MenuItem item = new MenuItem(Messages.get("SpellChecker.noSuggestionsAvailable")); item.setDisable(true); newItems.add(item); } String word = textArea.getText(problem.getFromPos(), problem.getToPos()); if (problem.isTypo() && !word.contains(" ")) { newItems.add(new SeparatorMenuItem()); MenuItem addDictItem = new MenuItem(Messages.get("SpellChecker.addToDictionary")); addDictItem.setOnAction(e -> { addToUserDictionary(word); navigateNextPrevious(); }); newItems.add(addDictItem); MenuItem ignoreItem = new MenuItem(Messages.get("SpellChecker.ignoreWord")); ignoreItem.setOnAction(e -> { ignoreWord(word); navigateNextPrevious(); }); newItems.add(ignoreItem); } } if (addNavigation) { // add separator (if necessary) if (!newItems.isEmpty()) newItems.add(new SeparatorMenuItem()); // add "Next Problem" item MenuItem nextProblemItem = new MenuItem(Messages.get("SpellChecker.nextProblem")); nextProblemItem.setAccelerator(KeyCombination.valueOf("Shortcut+.")); nextProblemItem.setOnAction(e -> { navigateNext(null); }); newItems.add(nextProblemItem); // add "Next Problem" item MenuItem previousProblemItem = new MenuItem(Messages.get("SpellChecker.previousProblem")); previousProblemItem.setAccelerator(KeyCombination.valueOf("Shortcut+,")); previousProblemItem.setOnAction(e -> { navigatePrevious(null); }); newItems.add(previousProblemItem); } ObservableList<MenuItem> menuItems = contextMenu.getItems(); // add separator (if necessary) if (!newItems.isEmpty() && !menuItems.isEmpty()) newItems.add(new SeparatorMenuItem()); // add new menu items to context menu menuItems.addAll(0, newItems); } public void hideContextMenu() { if (quickFixMenu != null) { quickFixMenu.hide(); quickFixMenu = null; } } private static final Pattern SUGGESTION_PATTERN = Pattern.compile("<suggestion>(.*?)</suggestion>"); private TextFlow buildMessage(String message) { ArrayList<javafx.scene.text.Text> texts = new ArrayList<>(); Matcher matcher = SUGGESTION_PATTERN.matcher(message); int pos = 0; while (matcher.find(pos)) { int start = matcher.start(); if (start > pos) texts.add(new javafx.scene.text.Text(message.substring(pos, start))); javafx.scene.text.Text text = new javafx.scene.text.Text(matcher.group(1)); text.getStyleClass().add("spell-menu-message-suggestion"); texts.add(new javafx.scene.text.Text("\"")); texts.add(text); texts.add(new javafx.scene.text.Text("\"")); pos = matcher.end(); } if (pos < message.length()) texts.add(new javafx.scene.text.Text(message.substring(pos))); TextFlow textFlow = new TextFlow(texts.toArray(new javafx.scene.text.Text[texts.size()])) { @Override protected double computePrefWidth(double height) { // limit width to 300 return Math.min(super.computePrefWidth(height), 300); } @Override protected double computePrefHeight(double width) { // compute height based on maximum width return super.computePrefHeight(300); } }; textFlow.getStyleClass().add("spell-menu-message"); return textFlow; } private void addToUserDictionary(String word) { userDictionary.addWord(word); addIgnoreWord(word); } private void ignoreWord(String word) { wordsToBeIgnored.add(word); addIgnoreWord(word); } private void addIgnoreWord(String word) { cache.invalidate(word); addIgnoreTokens(Collections.singletonList(word)); checkAsync(true); } private void navigateNextPrevious() { if (lastQuickFixNavigationDirection == 0) return; Platform.runLater(() -> { if (lastQuickFixNavigationDirection > 0) navigateNext(null); else if (lastQuickFixNavigationDirection < 0) navigatePrevious(null); }); } private void navigateNext(KeyEvent e) { if (spellProblems == null) return; lastQuickFixNavigationDirection = 1; int caretPosition = textArea.getCaretPosition(); SpellProblem problem = findNextProblemAt(caretPosition); if (problem == null) problem = findNextProblemAt(0); if (problem == null) return; selectProblem(problem); showQuickFixMenu(); } private void navigatePrevious(KeyEvent e) { if (spellProblems == null) return; lastQuickFixNavigationDirection = -1; int caretPosition = textArea.getCaretPosition(); SpellProblem problem = findPreviousProblemAt(caretPosition); if (problem == null) problem = findPreviousProblemAt(textArea.getLength()); if (problem == null) return; selectProblem(problem); showQuickFixMenu(); } private void selectProblem(SpellProblem problem) { textArea.selectRange(problem.getFromPos(), problem.getToPos()); editor.scrollCaretToVisible(); } private void addIgnoreTokens(List<String> words) { forEachSpellingCheckRule(rule -> { rule.addIgnoreTokens(words); }); } private void forEachSpellingCheckRule(Consumer<SpellingCheckRule> action) { for (Rule rule : languageTool.getAllActiveRules()) { if (rule instanceof SpellingCheckRule) action.accept((SpellingCheckRule) rule); } } private List<SpellProblem> findProblemsAt(int index) { if (index < 0 || spellProblems == null || spellProblems.isEmpty()) return Collections.emptyList(); ArrayList<SpellProblem> result = new ArrayList<>(); for (SpellBlockProblems blockProblems : spellProblems) { if (!blockProblems.contains(index)) continue; for (SpellProblem problem : blockProblems.problems) { if (problem.contains(index)) result.add(problem); } } return result; } private SpellProblem findNextProblemAt(int index) { for (SpellBlockProblems blockProblems : spellProblems) { if (index > blockProblems.getToPos()) continue; // index is after block for (SpellProblem problem : blockProblems.problems) { if (index < problem.getFromPos()) return problem; } } return null; } private SpellProblem findPreviousProblemAt(int index) { for (int i = spellProblems.size() - 1; i >= 0; i SpellBlockProblems blockProblems = spellProblems.get(i); if (index < blockProblems.getFromPos()) continue; // index is before block for (int j = blockProblems.problems.size() - 1; j >= 0; j SpellProblem problem = blockProblems.problems.get(j); if (index > problem.getToPos()) return problem; } } return null; } }
package org.openremote.model.data.json; import java.io.BufferedReader; import java.io.Reader; import java.util.Collection; import java.util.Iterator; import flexjson.JSONContext; import flexjson.JSONDeserializer; import flexjson.TypeContext; import flexjson.transformer.AbstractTransformer; import org.openremote.base.exception.IncorrectImplementationException; import org.openremote.model.Model; /** * This is a utility class that extends the AbstractTransformer API provided by the FlexJSON * framework for creating Java type transformers. It contains some common implementation that * is not included in the AbstractTransformer implementation and increases the API type-safety * in some parts. Implementations in this package should extend this class instead of the * AbstractTransformer in most cases. * * @param <T> the Java type to convert to JSON representation * * @author Juha Lindfors */ public abstract class JSONTransformer<T> extends AbstractTransformer { /** * A default validator for string type JSON attributes. This implementation ensures that * JSON strings added to org.openremote.model instance representations do not contain * null values and are not longer than {@link Model#DEFAULT_STRING_ATTRIBUTE_LENGTH_CONSTRAINT} * value to ensure they can be added to database model without truncation. */ protected static JSONValidator<String> defaultStringValidator = new JSONValidator<String>() { @Override public void validate(String attribute) throws Model.ValidationException { if (attribute == null) { throw new Model.ValidationException("String attribute has null value."); } if (attribute.length() > Model.DEFAULT_STRING_ATTRIBUTE_LENGTH_CONSTRAINT) { throw new Model.ValidationException( "String attribute is too long. Maximum {0} characters allowed, " + "given string has {1} characters.", Model.DEFAULT_STRING_ATTRIBUTE_LENGTH_CONSTRAINT, attribute.length() ); } } }; /** * The JSON string validator made available by this class. Defaults to * {@link #defaultStringValidator}. * * @see #setStringValidator(org.openremote.model.data.json.JSONTransformer.JSONValidator) */ private static JSONValidator<String> jsonStringValidator = defaultStringValidator; /** * Returns the JSON string validator configured for the instances of this class. * * @see Model#DEFAULT_STRING_ATTRIBUTE_LENGTH_CONSTRAINT * * @return JSON */ public static JSONValidator<String> getStringValidator() { return jsonStringValidator; } /** * Sets a new JSON string validator for this class. This method should in general only * be called at the application initialization time, and not again after, to ensure * predictable operation. Setting a new JSON string validator mid-flight in the application * will impact all the existing instances. * * @see #defaultStringValidator * @see #getStringValidator() * * @param newValidator a new JSON string validator */ protected static void setStringValidator(JSONValidator<String> newValidator) { JSONTransformer.jsonStringValidator = newValidator; } /** * The class type this JSON transformer instance is being used for (not available at runtime due * to Java generics type erasure). */ private Class<T> clazz; /** * Flag first property in a list for correct comma handling. */ private boolean firstProperty = true; /** * Constructs a new JSON transformer for a given Java type. * * @param clazz * the class definition of the Java type */ protected JSONTransformer(Class<T> clazz) { this.clazz = clazz; } /** * Overrides the transform() method from AbstractTransformer to handle the comma handling * for property lists * * @param object * the Java object to transform to JSON format */ @Override public void transform(Object object) { JSONContext ctx = getContext(); TypeContext typeCtx = ctx.peekTypeContext(); if (typeCtx != null && !typeCtx.isFirst()) { ctx.writeComma(); } try { write(clazz.cast(object)); } catch (ClassCastException e) { throw new IncorrectImplementationException( "Implementation Error: Object transformation to JSON data format failed "received type ''{0}'' is not compatible with expected type ''{1}''.", object.getClass().getName(), clazz.getName() ); } } /** * Reads from a stream a JSON representation of a domain object and deserializes it to a full * Java type. <p> * * The reader stream should point to a beginning of a JSON object that starts with a * {@link JSONHeader} representation. The JSON headers are parsed first, after which the * model object JSON attributes and values are passed to a concrete domain object deserializer * via a call to {@link #deserialize(JSONModel)} method. * The concrete domain model implementation should construct the Java instance based on this * JSON data. <p> * * This implementation will automatically reject any JSON representation that does not * match the library name {@link JSONHeader#LIBRARY_NAME} in its header fields. * * @param reader * a reference to the stream reader * * @throws DeserializationException * if the domain object cannot be resolved from the JSON representation * * @return initialized domain object instance */ public T read(Reader reader) throws DeserializationException { // Use flex JSON to deserialize representation to a JSON prototype with header fields... JSONModel model; try { model = new JSONDeserializer<JSONModel>() .deserialize(new BufferedReader(reader), JSONModel.class); // TODO : log debug --> "Deserialized " + model } catch (Throwable throwable) { throw new DeserializationException( "JSON representation could not be resolved to a proper prototype from the stream : {0}", throwable, throwable.getMessage() ); } // Reject the JSON if it doesn't belong to this library... if (!model.isValidLibrary()) { throw new DeserializationException( "Ignoring JSON object with library identifier '{0}'.", model.libraryName ); } // Reject the JSON if the model didn't resolve to any attributes or nested objects... if (!model.getModel().hasAttributes() && !model.getModel().hasObjects()) { throw new DeserializationException( "Model object JSON representation did not resolve correctly. " + "Class: ''{0}'', Schema : {1}, API : {2}", model.javaFullClassName, model.schema, model.api ); } // Resolve the domain object model into a Java instance (via concrete subclass impl.)... return deserialize(model); } /** * Adds a property with a given name and value to the JSON representation. The value is * transformed to JSON representation per the registered type transformers registered to * the FlexJSON framework. <p> * * This method can be used for JSON transformers which translate Java types to JSON objects * with multiple properties. See {@link #startObject()} and {@link #endObject()} on defining * the starting and ending boundaries for structured JSON objects. * * @param name * the property name to add to the JSON representation * * @param value * the value of the property */ protected void writeProperty(String name, Object value) { JSONContext ctx = getContext(); if (!firstProperty) { ctx.writeComma(); } else { firstProperty = false; } ctx.writeName(name); writeValue(value); } /** * Adds an array with a given name and array elements to the JSON representation. The * element values are transformed to JSON representation per the registered type transformers * registered to the FlexJSON framework. <p> * * @param name * the array name to add to the JSON representation * * @param values * the elements of the array (converted by transformers if/when present) */ protected void writeArray(String name, Collection values) { JSONContext ctx = getContext(); if (!firstProperty) { ctx.writeComma(); } else { firstProperty = false; } ctx.writeName(name); ctx.writeOpenArray(); Iterator it = values.iterator(); while (it.hasNext()) { writeValue(it.next()); if (it.hasNext()) { ctx.writeComma(); } } ctx.writeCloseArray(); } /** * Writes a JSON value. This is useful for simple type transformers that translate to a single * property value strings. For types that do not include default transformers in the FlexJSON * framework, a matching object type transformer should be registered. * * @param object * the JSON property value to transform */ protected void writeValue(Object object) { JSONContext ctx = getContext(); ctx.transform(object); } /** * Writes the appropriate JSON marker that begins a new JSON object. */ protected void startObject() { JSONContext ctx = getContext(); ctx.writeOpenObject(); } protected void startObject(String name) { JSONContext ctx = getContext(); ctx.writeName(name); ctx.writeOpenObject(); } /** * Writes the appropriate JSON marker that ends an JSON object definition. */ protected void endObject() { JSONContext ctx = getContext(); ctx.writeCloseObject(); // transformer is stateful (unfortunately) so make sure we reset state at the end of object... firstProperty = true; } /** * Override this method to provide the implementation of how to transform a given object * instance to a JSON representation. This method should be functionally equivalent to the * transform() method in AbstractTransformer class but adds a type-safe API. Use the helper * method implementations in this class to avoid having to deal with FlexJSON specific APIs * with regards to contexts, comma handling and so on. See {@link #writeProperty(String, Object)}, * {@link #writeValue(Object)}, {@link #startObject()} and {@link #endObject()} for example. * * @param object * the object instance to transform to JSON representation */ protected abstract void write(T object); /** * Override this method to provide the implementation of how to deserialize a given set of * JSON attribute names and values into a typed Java domain object instance. * * @param model * A model frame that represents the structures parsed from the JSON document * instance. This prototype should be used to construct the deserialized Java * instance the JSON represented. */ protected abstract T deserialize(JSONModel model) throws DeserializationException; /** * A validator interface that can be used by implementations that want to check the incoming * values adhere to given constraints before they are written to JSON serialization documents. * * @param <T> Java type of the JSON attribute to be validated */ public static interface JSONValidator<T> { public void validate(T attribute) throws Model.ValidationException; } }
package org.cacheonix.impl.net.processor; import java.io.IOException; import java.net.InetAddress; import java.util.Collection; import java.util.Set; import java.util.Timer; import org.cacheonix.impl.clock.Clock; import org.cacheonix.impl.net.ClusterNodeAddress; /** * A {@link Message} processor. */ public interface RequestProcessor extends Processor { /** * Returns address of this cluster node. * * @return address of this cluster node. */ ClusterNodeAddress getAddress(); /** * The router that is responsible for placing a message being sent to an input queue of a proper local processor or * to a processor that serves sending messages out. * * @return the router that is responsible for placing a message being sent to an input queue of a proper local * processor or to a processor that serves sending messages out. */ Router getRouter(); /** * Returns an unmodifiable local IP address set. * * @return an unmodifiable local IP address set. */ Set<InetAddress> getLocalInetAddresses(); WaiterList getWaiterList(); void processMessage(Message message) throws InterruptedException, IOException; /** * Puts request into the execution queue and waits for completion. Clients use this method to execute requests. * * @param message the message to wait the result for. * @return result. * @throws RetryException if destination requires to retry. */ <T> T execute(Message message) throws RetryException; /** * Puts the message into the input queue for future execution by this processor. This method exits immediately * without waiting. * * @param message message to post. */ void post(Message message); /** * Puts the messages into the input queue for future execution by this processor. This method exits immediately * without waiting. * * @param messages message to post. */ void post(Collection<? extends Message> messages); /** * Handles messages coming from the local client threads by placing them to the right local processor. * <p/> * <code>dispatch()</code> creates and returns a response waiter if message is a request and the local client thread * wants to wait for the response. In this <code>dispatch()</code> is different from <code>enqueue()</code> which * handles request arriving from the network. * * @param message the message to dispatch * @return a ResponseWaiter that a client thread should use if it wants to wait for a result. See {@link * #execute(Message)} for details. */ ResponseWaiter route(Message message); /** * Processes notification about a cluster node leaving the cluster by notifying the waiter list. * * @param nodeLeftAddress an address of a node. */ void notifyNodeLeft(ClusterNodeAddress nodeLeftAddress); /** * Processes notifications about cluster nods leaving the cluster by notifying the waiter list. * * @param addresses a collection of addresses. */ void notifyNodesLeft(Collection<ClusterNodeAddress> addresses); Timer getTimer(); /** * Returns the cluster-wide clock. * * @return the cluster-wide clock. */ Clock getClock(); }
package org.pfaa.chemica.model; import java.awt.Color; public class ChemicalStateProperties extends StateProperties { public final Thermo thermo; public ChemicalStateProperties(State state, Color color, double density, Thermo thermo, Hazard hazard, boolean opaque) { super(state, color, density, hazard, opaque); this.thermo = thermo; } public static class Solid extends ChemicalStateProperties { public Solid(Color color, double density, Thermo thermo, Hazard hazard) { super(State.SOLID, color, density, thermo, hazard, true); } public Solid(Color color, double density, Thermo thermo) { this(color, density, thermo, new Hazard()); } public Solid(Color color, double density) { this(color, density, new Thermo()); } public Solid(double density, Thermo thermo, Hazard hazard) { this(Color.WHITE, density, thermo, hazard); } public Solid(double density, Thermo thermo) { this(density, thermo, new Hazard()); } public Solid(Thermo thermo) { this(Double.NaN, thermo); } public Solid() { this(new Thermo()); } } public static class Liquid extends ChemicalStateProperties { private final Yaws yaws; public Liquid(Color color, double density, Thermo thermo, Hazard hazard, Yaws yaws) { super(State.LIQUID, color, density, thermo, hazard, false); this.yaws = yaws; } public Liquid(double density, Thermo thermo, Hazard hazard, Yaws yaws) { this(COLORLESS, density, thermo, hazard, yaws); } public Liquid(double density, Thermo thermo) { this(density, thermo, new Hazard(), null); } public Liquid(Thermo thermo) { this(Double.NaN, thermo); } public Liquid() { this(new Thermo()); } @Override public double getViscosity(double temperature) { return this.yaws == null ? super.getViscosity(temperature) : this.yaws.getViscosity(temperature); } public static class Yaws { private double A; private double B; private double C; private double D; public Yaws(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public double getViscosity(double temperature) { double exp = this.A + this.B / temperature + this.C * temperature + this.D * Math.pow(temperature, 2); return Math.pow(10, exp); } } } public static class Gas extends ChemicalStateProperties { private final double molarMass; private final Sutherland sutherland; public Gas(Gas gas, double molarMass) { this(gas.getColor(), gas.thermo, gas.getHazard(), gas.sutherland, molarMass); } public Gas(Color color, Thermo thermo, Hazard hazard, Sutherland sutherland, double molarMass) { super(State.GAS, color, Double.NaN, thermo, hazard, false); this.molarMass = molarMass; this.sutherland = sutherland; } public Gas(Color color, Thermo thermo, Hazard hazard, Sutherland sutherland) { this(color, thermo, hazard, sutherland, Double.NaN); } public Gas(Thermo thermo, Hazard hazard, Sutherland sutherland) { this(COLORLESS, thermo, hazard, sutherland); } public Gas(Thermo thermo) { this(thermo, new Hazard(), null); } public Gas() { this(new Thermo()); } @Override public double getDensity(Condition condition) { if (Double.isNaN(this.molarMass)) { return super.getDensity(condition); } else { return getDensity(condition, this.molarMass); } } private static double getDensity(Condition condition, double molarMass) { return (molarMass * condition.pressure) / (Constants.R * condition.temperature) / 1E6; } @Override public double getViscosity(double temperature) { return this.sutherland == null ? super.getViscosity(temperature) : this.sutherland.getViscosity(temperature); } public static class Sutherland { private double refViscosity; private double refTemperature; private double constant; // approximately 1.47 * boiling point public Sutherland(double refViscosity, double refTemperature, double constant) { this.refViscosity = refViscosity / 1000; this.refTemperature = refTemperature; this.constant = constant; } public double getViscosity(double temperature) { return refViscosity * ((refTemperature + constant) / (temperature + constant) * Math.pow(temperature / refTemperature, 1.5)); } } } }
package org.spongepowered.api.data; import com.google.common.base.Optional; import com.google.common.collect.ImmutableCollection; /** * Represents an immutable variant of the {@link DataHolder} where once built, * the {@link ImmutableDataHolder} can not be modified. * * @see DataHolder * @param <T> The sub type of immutable data holder */ public interface ImmutableDataHolder<T extends ImmutableDataHolder<T>> extends DataSerializable { /** * Get a copy of all properties defined on this * {@link ImmutableDataHolder}, with their current values. * * @return A collection of all known manipulators */ ImmutableCollection<DataManipulator<?>> getManipulators(); /** * Gets an instance of the given data class for this * {@link ImmutableDataHolder}. * * <p>If there is no pre-existing data that can be represented by the given * {@link DataManipulator} class, {@link Optional#absent()} is returned. * </p> * * @param manipulatorClass The data class * @param <M> The type of data * @return An instance of the class, if not available */ <M extends DataManipulator<M>> Optional<M> getManipulator(Class<M> manipulatorClass); /** * Gets an altered copy of this {@link ImmutableDataHolder} with the given * {@link DataManipulator} modified data. If the data is not compatible for * any reason, {@link Optional#absent()} is returned. * * <p>This does not alter the current {@link ImmutableDataHolder}.</p> * * @param manipulator The new manipulator containing data * @param <M> The type of data manipulator * @return A new immutable data holder with the given manipulator */ <M extends DataManipulator<M>> Optional<T> withData(M manipulator); /** * Gets an altered copy of this {@link ImmutableDataHolder} without the * given {@link DataManipulator}. If the data represented by the * manipulator can not exist without a "default state" of the * {@link DataManipulator}, the {@link DataManipulator} is reset to the * "default" state. * * @param manipulator The manipulator class to remove * @param <M> The manipulator type * @return A new immutable data holder without the given manipulator */ <M extends DataManipulator<M>> Optional<T> withoutData(Class<M> manipulator); }
package org.jboss.as.cli.gui; import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.text.JTextComponent; import org.jboss.as.cli.gui.ManagementModelNode.UserObject; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; public class OperationDialog extends JDialog { private ManagementModelNode node; private String opName; private SortedSet<RequestProp> props; public OperationDialog(ManagementModelNode node, String opName, String strDescription, ModelNode requestProperties) { super(GuiMain.getFrame(), opName, true); this.node = node; this.opName = opName; setProps(requestProperties); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout(10, 10)); JLabel opNameLabel = new JLabel("Params for " + opName + ":"); opNameLabel.setToolTipText(strDescription); contentPane.add(opNameLabel, BorderLayout.NORTH); contentPane.add(makeInputPanel(), BorderLayout.CENTER); contentPane.add(makeButtonPanel(), BorderLayout.SOUTH); pack(); setResizable(false); } @Override public void setVisible(boolean isVisible) { if (node.isLeaf()) { // "rightSide" field should have focus for write-attribute dialog // where "leftSide" field is already populated for (RequestProp prop : props) { if (prop.getName().equals("value")) { prop.getValueComponent().requestFocus(); } } } super.setVisible(isVisible); } private void setProps(ModelNode requestProperties) { props = new TreeSet<RequestProp>(); if (opName.equals("add")) { UserObject usrObj = (UserObject)node.getUserObject(); props.add(new RequestProp("/" + usrObj.getName() + "=<name>/", "Resource name for the new " + usrObj.getName(), true)); } for (Property prop : requestProperties.asPropertyList()) { props.add(new RequestProp(prop.getName(), prop.getValue())); } } private JPanel makeInputPanel() { boolean hasRequiredFields = false; JPanel inputPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbConst = new GridBagConstraints(); gbConst.anchor = GridBagConstraints.WEST; gbConst.insets = new Insets(5,5,5,5); for (RequestProp prop : props) { JLabel label = prop.getLabel(); gbConst.gridwidth = 1; inputPanel.add(label, gbConst); inputPanel.add(Box.createHorizontalStrut(5)); JComponent comp = prop.getValueComponent(); gbConst.gridwidth = GridBagConstraints.REMAINDER; inputPanel.add(comp, gbConst); if (prop.isRequired) hasRequiredFields = true; } if (hasRequiredFields) { inputPanel.add(new JLabel(" * = Required Field")); } return inputPanel; } private JPanel makeButtonPanel() { JPanel buttonPanel = new JPanel(); JButton ok = new JButton("OK"); ok.addActionListener(new SetOperationActionListener()); JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { OperationDialog.this.dispose(); } }); buttonPanel.add(ok); buttonPanel.add(cancel); return buttonPanel; } /** * Set the command line with address + operation + params. */ private class SetOperationActionListener implements ActionListener { public void actionPerformed(ActionEvent ae) { String addressPath = OperationDialog.this.node.addressPath(); if (OperationDialog.this.opName.equals("add")) { UserObject usrObj = (UserObject)OperationDialog.this.node.getUserObject(); ManagementModelNode parent = (ManagementModelNode)OperationDialog.this.node.getParent(); RequestProp resourceProp = OperationDialog.this.props.first(); String value = resourceProp.getValueAsString(); value = ManagementModelNode.escapeAddressElement(value); addressPath = parent.addressPath() + usrObj.getName() + "=" + value + "/"; OperationDialog.this.props.remove(resourceProp); } StringBuilder command = new StringBuilder(); command.append(addressPath); command.append(":"); command.append(OperationDialog.this.opName); addRequestProps(command, OperationDialog.this.props); GuiMain.getCommandText().setText(command.toString()); OperationDialog.this.dispose(); GuiMain.getCommandText().requestFocus(); } private void addRequestProps(StringBuilder command, SortedSet<RequestProp> reqProps) { boolean addedProps = false; command.append("("); for (RequestProp prop : reqProps) { String value = prop.getValueAsString(); if (value == null) continue; if (value.equals("")) continue; addedProps = true; command.append(prop.getName()); command.append("="); command.append(value); command.append(","); } if (addedProps) { // replace training comma with close paren command.replace(command.length()-1, command.length(), ")"); } else { // remove opening paren command.deleteCharAt(command.length() - 1); } } } /** * Request property class. This class contains all known information about each operation attribute. * * It is also responsible for building the input component for the attribute. */ private class RequestProp implements Comparable { private final String name; private ModelNode props; private ModelType type; private String description; private boolean isRequired = false; private boolean nillable = false; private ModelNode defaultValue = null; private JLabel label; private JComponent valueComponent; private boolean isResourceName = false; /** * Constructor used for resource name property. * @param name Property name * @param description Description for tool tip text. * @param isRequired Is this a isRequired property? */ public RequestProp(String name, String description, boolean required) { this.name = name; this.props = new ModelNode(); this.description = description; this.type = ModelType.STRING; this.isRequired = required; this.isResourceName = true; setInputComponent(); } public RequestProp(String name, ModelNode props) { this.name = name; this.props = props; this.type = props.get("type").asType(); if (props.get("description").isDefined()) { this.description = props.get("description").asString(); } if (props.get("required").isDefined()) { this.isRequired = props.get("required").asBoolean(); } if (props.get("nillable").isDefined()) { this.nillable = props.get("nillable").asBoolean(); } if (props.get("default").isDefined()) { this.defaultValue = props.get("default"); } setInputComponent(); setWriteAttributeValues(); } public String getName() { return name; } public JComponent getValueComponent() { return valueComponent; } public JLabel getLabel() { return this.label; } public String getValueAsString() { if (valueComponent instanceof JTextComponent) { return ((JTextComponent)valueComponent).getText(); } if (valueComponent instanceof AbstractButton) { return Boolean.toString(((AbstractButton)valueComponent).isSelected()); } if (valueComponent instanceof JComboBox) { return ((JComboBox)valueComponent).getSelectedItem().toString(); } return null; } private void setInputComponent() { if (type == ModelType.BOOLEAN) { if (defaultValue == null) { this.valueComponent = new JCheckBox(makeLabelString(false)); } else { this.valueComponent = new JCheckBox(makeLabelString(false), defaultValue.asBoolean()); } this.valueComponent.setToolTipText(description); this.label = new JLabel(); } else if (props.get("allowed").isDefined()) { JComboBox comboBox = makeJComboBox(props.get("allowed").asList()); if (defaultValue != null) comboBox.setSelectedItem(defaultValue.asString()); this.valueComponent = comboBox; this.label = makeLabel(); } else { JTextField textField = new JTextField(30); if (defaultValue != null) textField.setText(defaultValue.asString()); this.valueComponent = textField; this.label = makeLabel(); } } private String makeLabelString(boolean addColon) { String labelString = name; if (addColon) labelString += ":"; if (isRequired) labelString += " *"; return labelString; } private JLabel makeLabel() { JLabel label = new JLabel(makeLabelString(true)); label.setToolTipText(description); return label; } private JComboBox makeJComboBox(List<ModelNode> values) { Vector<String> valueVector = new Vector<String>(values.size()); if (!isRequired) { valueVector.add(""); } for (ModelNode node : values) { valueVector.add(node.asString()); } return new JComboBox(valueVector); } // fill in form fields for write-attribute when an attribute node is selected. private void setWriteAttributeValues() { if (!OperationDialog.this.node.isLeaf()) return; if (!OperationDialog.this.opName.equals("write-attribute")) return; UserObject usrObj = (UserObject)OperationDialog.this.node.getUserObject(); if (this.name.equals("name")) { ((JTextField)valueComponent).setText(usrObj.getName()); return; } if (usrObj.getValue().equals("undefined")) return; if (this.name.equals("value")) ((JTextField)valueComponent).setText(usrObj.getValue()); } @Override public int compareTo(Object t) { if (this.equals(t)) return 0; if (this.isResourceName) return -1; RequestProp compareTo = (RequestProp)t; if (this.isRequired && compareTo.isRequired) return 1; if (this.isRequired) return -1; return 1; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof RequestProp)) return false; RequestProp compareTo = (RequestProp)obj; return this.name.equals(compareTo.name); } @Override public int hashCode() { return name.hashCode(); } } }
package org.jetbrains.plugins.scala.util; import scala.tools.ant.Scalac; public class AntScalaCompiler extends Scalac { public void execute() { setAddparams("-Xgenerics"); setAddparams("-target:jvm-1.5"); super.execute(); } }
package org.spongepowered.api.event; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3i; import com.google.common.base.Optional; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import org.spongepowered.api.Game; import org.spongepowered.api.GameProfile; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockTransaction; import org.spongepowered.api.block.tileentity.Sign; import org.spongepowered.api.block.tileentity.carrier.BrewingStand; import org.spongepowered.api.block.tileentity.carrier.Furnace; import org.spongepowered.api.block.tileentity.carrier.TileEntityCarrier; import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableBrewingData; import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableFurnaceData; import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableSignData; import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityInteractionType; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.Tamer; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.living.Ageable; import org.spongepowered.api.entity.living.Human; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.gamemode.GameMode; import org.spongepowered.api.entity.projectile.FishHook; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.source.ProjectileSource; import org.spongepowered.api.event.action.MessageEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.source.block.BlockBurnBlockEvent; import org.spongepowered.api.event.source.block.BlockDispenseItemEvent; import org.spongepowered.api.event.source.block.BlockHarvestBlockEvent; import org.spongepowered.api.event.source.block.BlockIgniteBlockEvent; import org.spongepowered.api.event.source.block.BlockInteractBlockEvent; import org.spongepowered.api.event.source.block.BlockMoveBlockEvent; import org.spongepowered.api.event.source.block.BlockSpreadBlockEvent; import org.spongepowered.api.event.source.block.BlockUpdateBlockPowerEvent; import org.spongepowered.api.event.source.block.BlockUpdateNeighborBlockEvent; import org.spongepowered.api.event.source.block.tileentity.BrewingStandBrewItemsEvent; import org.spongepowered.api.event.source.block.tileentity.FurnaceConsumeFuelEvent; import org.spongepowered.api.event.source.block.tileentity.FurnaceSmeltItemEvent; import org.spongepowered.api.event.source.command.SendCommandEvent; import org.spongepowered.api.event.source.command.TabCompleteCommandEvent; import org.spongepowered.api.event.source.entity.living.human.HumanSleepEvent; import org.spongepowered.api.event.source.entity.living.human.player.PlayerChangeSignEvent; import org.spongepowered.api.event.source.entity.living.human.player.PlayerChangeStatisticEvent; import org.spongepowered.api.event.source.entity.living.human.player.PlayerChatEvent; import org.spongepowered.api.event.source.entity.living.human.player.PlayerJoinEvent; import org.spongepowered.api.event.source.entity.living.human.player.PlayerQuitEvent; import org.spongepowered.api.event.source.game.state.GameStateEvent; import org.spongepowered.api.event.source.network.GameClientAuthEvent; import org.spongepowered.api.event.source.network.GameClientConnectEvent; import org.spongepowered.api.event.source.plugin.PluginForceChunkEvent; import org.spongepowered.api.event.source.rcon.RconLoginEvent; import org.spongepowered.api.event.source.rcon.RconQuitEvent; import org.spongepowered.api.event.source.server.ServerCreateWorldEvent; import org.spongepowered.api.event.source.server.ServerLoadWorldEvent; import org.spongepowered.api.event.source.server.ServerUnloadWorldEvent; import org.spongepowered.api.event.source.world.WorldDecayBlockEvent; import org.spongepowered.api.event.source.world.WorldExplosionEvent; import org.spongepowered.api.event.source.world.WorldGenerateChunkEvent; import org.spongepowered.api.event.source.world.WorldGrowBlockEvent; import org.spongepowered.api.event.source.world.WorldPopulateChunkEvent; import org.spongepowered.api.event.source.world.WorldTickBlockEvent; import org.spongepowered.api.event.target.block.BreakBlockEvent; import org.spongepowered.api.event.target.block.ChangeBlockEvent; import org.spongepowered.api.event.target.block.CollideBlockEvent; import org.spongepowered.api.event.target.block.HarvestBlockEvent; import org.spongepowered.api.event.target.block.InteractBlockEvent; import org.spongepowered.api.event.target.block.PlaceBlockEvent; import org.spongepowered.api.event.target.entity.BreedEntityEvent; import org.spongepowered.api.event.target.entity.CollideEntityEvent; import org.spongepowered.api.event.target.entity.DestructEntityEvent; import org.spongepowered.api.event.target.entity.DismountEntityEvent; import org.spongepowered.api.event.target.entity.DisplaceEntityEvent; import org.spongepowered.api.event.target.entity.FishingEvent; import org.spongepowered.api.event.target.entity.HarvestEntityEvent; import org.spongepowered.api.event.target.entity.InteractEntityEvent; import org.spongepowered.api.event.target.entity.LeashEntityEvent; import org.spongepowered.api.event.target.entity.MountEntityEvent; import org.spongepowered.api.event.target.entity.PreCreateEntityEvent; import org.spongepowered.api.event.target.entity.SpawnEntityEvent; import org.spongepowered.api.event.target.entity.TameEntityEvent; import org.spongepowered.api.event.target.entity.TargetEntityEvent; import org.spongepowered.api.event.target.entity.UnleashEntityEvent; import org.spongepowered.api.event.target.entity.living.TargetLivingEvent; import org.spongepowered.api.event.target.entity.living.human.ChangeHumanGameModeEvent; import org.spongepowered.api.event.target.entity.living.human.player.RespawnPlayerEvent; import org.spongepowered.api.event.target.entity.projectile.LaunchProjectileEvent; import org.spongepowered.api.event.target.inventory.DropItemStackEvent; import org.spongepowered.api.event.target.inventory.PickUpItemEvent; import org.spongepowered.api.event.target.server.PingServerEvent; import org.spongepowered.api.event.target.world.ChangeWorldGameRuleEvent; import org.spongepowered.api.event.target.world.ChangeWorldWeatherEvent; import org.spongepowered.api.event.target.world.CreateWorldEvent; import org.spongepowered.api.event.target.world.chunk.LoadChunkEvent; import org.spongepowered.api.event.target.world.chunk.UnforcedChunkEvent; import org.spongepowered.api.event.target.world.chunk.UnloadChunkEvent; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.type.TileEntityInventory; import org.spongepowered.api.network.RemoteConnection; import org.spongepowered.api.service.world.ChunkLoadService.LoadingTicket; import org.spongepowered.api.statistic.Statistic; import org.spongepowered.api.status.StatusClient; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.sink.MessageSink; import org.spongepowered.api.util.Direction; import org.spongepowered.api.util.command.CommandResult; import org.spongepowered.api.util.command.CommandSource; import org.spongepowered.api.util.command.source.RconSource; import org.spongepowered.api.util.event.factory.ClassGeneratorProvider; import org.spongepowered.api.util.event.factory.EventFactory; import org.spongepowered.api.util.event.factory.EventFactoryPlugin; import org.spongepowered.api.util.event.factory.NullPolicy; import org.spongepowered.api.util.event.factory.plugin.AccessorModifierEventFactoryPlugin; import org.spongepowered.api.util.event.factory.plugin.AnnotationEventFactoryPlugin; import org.spongepowered.api.world.Chunk; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.api.world.WorldCreationSettings; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.gen.Populator; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.api.world.weather.Weather; import org.spongepowered.api.world.weather.WeatherUniverse; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Generates Sponge event implementations. */ public final class SpongeEventFactory { private static final ClassGeneratorProvider factoryProvider; private static final LoadingCache<Class<?>, EventFactory<?>> factories; private static final List<EventFactoryPlugin> plugins = new ArrayList<EventFactoryPlugin>(); static { factoryProvider = new ClassGeneratorProvider("org.spongepowered.api.event.impl"); factoryProvider.setNullPolicy(NullPolicy.NON_NULL_BY_DEFAULT); plugins.add(0, new AnnotationEventFactoryPlugin()); plugins.add(0, new AccessorModifierEventFactoryPlugin("org.spongepowered.api.event.impl.base")); factories = CacheBuilder.newBuilder() .build( new CacheLoader<Class<?>, EventFactory<?>>() { @Override public EventFactory<?> load(Class<?> type) { return factoryProvider.create(type, getBaseClass(type)); } }); } private SpongeEventFactory() { } private static Class<?> getBaseClass(Class<?> event) { Class<?> superClass = null; for (EventFactoryPlugin plugin : plugins) { superClass = plugin.resolveSuperClassFor(event, superClass, factoryProvider.getClassLoader()); } return superClass; } /** * Adds an {@link EventFactoryPlugin} to the chain of plugins. * * <p>The plugin chain is in LIFO order.</p> * * @param plugin The {@link EventFactoryPlugin} to add to the chain */ public static void addEventFactoryPlugin(EventFactoryPlugin plugin) { plugins.add(0, plugin); } /** * Creates an event class from an interface and a map of property names to values. * * @param type The event interface to generate a class for * @param values The map of property names to values * @param <T> The type of event to be created * @return The generated event class. */ @SuppressWarnings("unchecked") public static <T> T createEvent(Class<T> type, Map<String, Object> values) { return (T) factories.getUnchecked(type).apply(values); } /** * Creates a new {@link GameStateEvent} of the given type. * * @param type The type of the state event * @param game The game instance for this {@link GameEvent} * @param <T> The type of the state event * @return A new instance of the event */ public static <T extends GameStateEvent> T createState(Class<T> type, Game game) { Map<String, Object> values = Maps.newHashMapWithExpectedSize(1); values.put("game", game); return createEvent(type, values); } /** * Creates a new {@link BreakBlockEvent.SourceBlock}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param replacementBlock The block that will replace the existing block * @param exp The experience to give, or take for negative values * @return A new instance of the event */ public static BreakBlockEvent.SourceBlock createBlockBreakBlock(Game game, Cause cause, Location<World> location, BlockSnapshot replacementBlock, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(BreakBlockEvent.SourceBlock.class, values); } /** * Creates a new {@link BlockBurnBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static BlockBurnBlockEvent createBlockBurnBlock(Game game, Cause cause, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(BlockBurnBlockEvent.class, values); } /** * Creates a new {@link ChangeBlockEvent.SourceBlock}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static ChangeBlockEvent.SourceBlock createBlockChangeBlock(Game game, Cause cause, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(ChangeBlockEvent.SourceBlock.class, values); } /** * Creates a new {@link BlockDispenseItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param velocity The velocity to dispense the item at * @param dispensedItem The item to dispense from the block * @return A new instance of the event */ public static BlockDispenseItemEvent createBlockDispenseItem(Game game, Cause cause, Location<World> location, Vector3d velocity, ItemStack dispensedItem) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("velocity", velocity); values.put("dispensedItem", dispensedItem); return createEvent(BlockDispenseItemEvent.class, values); } /** * Creates a new {@link BlockHarvestBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param droppedItems The items to drop * @param dropChance The chance the items will drop, see * {@link HarvestBlockEvent#setDropChance(float)} * @return A new instance of the event */ public static BlockHarvestBlockEvent createBlockHarvestBlock(Game game, Cause cause, Location<World> location, Collection<ItemStack> droppedItems, float dropChance) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("droppedItems", droppedItems); values.put("dropChance", dropChance); return createEvent(BlockHarvestBlockEvent.class, values); } /** * Creates a new {@link BlockIgniteBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @return A new instance of the event */ public static BlockIgniteBlockEvent createBlockIgniteBlock(Game game, Cause cause, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); return createEvent(BlockIgniteBlockEvent.class, values); } /** * Creates a new {@link BlockInteractBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param side The face interacted with as a direction * @return A new instance of the event */ public static BlockInteractBlockEvent createBlockInteractBlock(Game game, Cause cause, Location<World> location, Direction side) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("side", side); return createEvent(BlockInteractBlockEvent.class, values); } /** * Creates a new {@link BlockMoveBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param locations The locations * @return A new instance of the event */ public static BlockMoveBlockEvent createBlockMoveBlock(Game game, Cause cause, List<Location<World>> locations) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("locations", locations); return createEvent(BlockMoveBlockEvent.class, values); } /** * Creates a new {@link PlaceBlockEvent.SourceBlock}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location the location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static PlaceBlockEvent.SourceBlock createBlockPlaceBlock(Game game, Cause cause, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(PlaceBlockEvent.SourceBlock.class, values); } /** * Creates a new {@link WorldTickBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @return A new instance of the event */ public static WorldTickBlockEvent createWorldTickBlock(Game game, Cause cause, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("targetLocation", location); values.put("targetBlock", location.getBlock()); values.put("sourceWorld", location.getExtent()); return createEvent(WorldTickBlockEvent.class, values); } /** * Creates a new {@link BlockUpdateNeighborBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param directions The directions * @param relatives The relative directions * @param snapshotRelatives The relative snapshots * @param transactions The block transactions * @return A new instance of the event */ public static BlockUpdateNeighborBlockEvent createBlockUpdateNeighborBlock(Game game, ImmutableList<BlockTransaction> transactions, Map<Direction, Location<World>> directions, Map<Direction, Location<World>> relatives, Map<Direction, BlockSnapshot> snapshotRelatives) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("transactions", transactions); values.put("directions", directions); values.put("relatives", relatives); values.put("snapshotRelatives", snapshotRelatives); return createEvent(BlockUpdateNeighborBlockEvent.class, values); } /** * Create a new {@link BlockUpdateBlockPowerEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param locations The affected locations * @param oldCurrent The previous signal strength of the redstone * @param newCurrent The updated signal strength of the redstone * @return A new instance of the event */ public static BlockUpdateBlockPowerEvent createBlockUpdateBlockPower(Game game, Cause cause, Location<World> location, List<Location<World>> locations, int oldCurrent, int newCurrent) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("location", location); values.put("block", location.getBlock()); values.put("locations", locations); values.put("oldSignalStrength", oldCurrent); values.put("newSignalStrength", newCurrent); return createEvent(BlockUpdateBlockPowerEvent.class, values); } /** * Creates a new {@link WorldGrowBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static WorldGrowBlockEvent createWorldGrowBlock(Game game, Cause cause, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(WorldGrowBlockEvent.class, values); } /** * Creates a new {@link BlockSpreadBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param location The location * @param locations The affected locations * @return A new instance of the event */ public static BlockSpreadBlockEvent createBlockSpreadBlock(Game game, Cause cause, Location<World> location, List<Location<World>> locations) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("locations", locations); return createEvent(BlockSpreadBlockEvent.class, values); } /** * Creates a new {@link BreakBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @param replacementBlock The block that will replace the existing block * @param exp The experience to give, or take for negative values * @return A new instance of the event */ public static BreakBlockEvent.SourceEntity createEntityBreakBlock(Game game, Cause cause, Entity entity, Location<World> location, BlockSnapshot replacementBlock, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); values.put("exp", exp); return createEvent(BreakBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link DestructEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param targetEntity The target entity * @param targetTransform The target transform * @param snapshot The entity snapshot * @return A new instance of the event */ public static DestructEntityEvent createDestructEntity(Game game, Entity targetEntity, Transform<World> targetTransform, EntitySnapshot snapshot) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetEntity", targetEntity); values.put("targetTransform", targetTransform); values.put("snapshot", snapshot); return createEvent(DestructEntityEvent.class, values); } /** * Creates a new {@link BreedEntityEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param parent The parent of the entity * @param otherParent The other parent of the entity * @return A new instance of the event */ public static BreedEntityEvent.SourceEntity createEntityBreedWithEntity(Game game, Ageable entity, Ageable parent, Ageable otherParent) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("parent", parent); values.put("otherParent", otherParent); return createEvent(BreedEntityEvent.SourceEntity.class, values); } /** * Creates a new {@link ChangeBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static ChangeBlockEvent.SourceEntity createEntityChangeBlock(Game game, Cause cause, Entity entity, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(ChangeBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link CollideEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @return A new instance of the event */ public static CollideEntityEvent createCollideEntity(Game game, Cause cause, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); return createEvent(CollideEntityEvent.class, values); } /** * Creates a new {@link CollideBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @return A new instance of the event */ public static CollideBlockEvent.SourceEntity createEntityCollideBlock(Game game, Cause cause, Entity entity, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("location", location); values.put("block", location.getBlock()); return createEvent(CollideBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link CollideEntityEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param collided The entity that was collided with * @return A new instance of the event */ public static CollideEntityEvent.SourceEntity createEntityCollideEntity(Game game, Cause cause, Entity entity, Entity collided) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("collided", collided); return createEvent(CollideEntityEvent.SourceEntity.class, values); } /** * Creates a new {@link HarvestEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @param exp The experience to give, or take for negative values * @return A new instance of the event */ public static HarvestEntityEvent createHarvestEntity(Game game, Cause cause, Entity entity, Location<World> location, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("location", location); values.put("exp", exp); return createEvent(HarvestEntityEvent.class, values); } /** * Creates a new {@link DismountEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param dismounted The entity being dismounted from * @return A new instance of the event */ public static DismountEntityEvent createDismountEntity(Game game, Entity entity, Entity dismounted) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("dismounted", dismounted); return createEvent(DismountEntityEvent.class, values); } /** * Creates a new {@link DisplaceEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param oldLocation The previous location * @param newLocation The new location * @param rotation The rotation the entity is facing * @return A new instance of the event */ public static DisplaceEntityEvent createDisplaceEntity(Game game, Entity entity, Location<World> oldLocation, Location<World> newLocation, Vector3d rotation) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); values.put("rotation", rotation); return createEvent(DisplaceEntityEvent.class, values); } /** * Creates a new {@link DropItemStackEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of this event * @param entity The entity * @param droppedItems The items to drop * @return A new instance of the event */ public static DropItemStackEvent.SourceEntity createEntityDropItem(Game game, Cause cause, Entity entity, Collection<ItemStack> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("droppedItems", droppedItems); return createEvent(DropItemStackEvent.SourceEntity.class, values); } /** * Creates a new {@link HarvestBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @param droppedItems The items to drop * @param dropChance The chance the items will drop, see * {@link HarvestBlockEvent#setDropChance(float)} * @return A new instance of the event */ public static HarvestBlockEvent.SourceEntity createEntityHarvestBlock(Game game, Cause cause, Entity entity, Location<World> location, Collection<ItemStack> droppedItems, float dropChance) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("droppedItems", droppedItems); values.put("dropChance", dropChance); return createEvent(HarvestBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link InteractBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param sourceEntity The source entity * @param sourceLocation The source location * @param targetLocation The target location * @param targetSide The target side of the block affected * @return A new instance of the event */ public static InteractBlockEvent.SourceEntity createEntityInteractBlock(Game game, Cause cause, Entity sourceEntity, Location<World> sourceLocation, Location<World> targetLocation, Direction targetSide) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("sourceEntity", sourceEntity); values.put("sourceLocation", sourceLocation); values.put("targetLocation", targetLocation); values.put("targetBlock", targetLocation.getBlock()); values.put("targetSide", targetSide); return createEvent(InteractBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link InteractEntityEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param targetEntity The entity being interacted with * @return A new instance of the event */ public static InteractEntityEvent.SourceEntity createEntityInteractEntity(Game game, Entity entity, Entity targetEntity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("targetEntity", targetEntity); return createEvent(InteractEntityEvent.SourceEntity.class, values); } /** * Creates a new {@link HumanSleepEvent.Enter}. * * @param game The game instance for this {@link GameEvent} * @param entity The human entity * @param transform The human transform * @param bed The bed * @return A new instance of the event */ public static HumanSleepEvent.Enter createHumanSleep(Game game, Human entity, Transform<World> transform, Location<World> bed) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("transform", transform); values.put("bed", bed); return createEvent(HumanSleepEvent.Enter.class, values); } /** * Creates a new {@link LeashEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param leashHolder The entity holding the leash * @return A new instance of the event */ public static LeashEntityEvent createLeashEntity(Game game, Entity entity, Entity leashHolder) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("leashHolder", leashHolder); return createEvent(LeashEntityEvent.class, values); } /** * Creates a new {@link LeashEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param leashHolder The entity holding the leash * @return A new instance of the event */ public static UnleashEntityEvent createUnleashEntity(Game game, Entity entity, Entity leashHolder) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("leashHolder", leashHolder); return createEvent(UnleashEntityEvent.class, values); } /** * Creates a new {@link MountEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param vehicle The entity being mounted * @return A new instance of the event */ public static MountEntityEvent createMountEntity(Game game, Entity entity, Entity vehicle) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("vehicle", vehicle); return createEvent(MountEntityEvent.class, values); } /** * Creates a new {@link DisplaceEntityEvent.Move}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param oldLocation The previous location of the entity * @param newLocation The new location of the entity * @param rotation The rotation the entity is facing * @return A new instance of the event */ public static DisplaceEntityEvent.Move createMoveEntity(Game game, Entity entity, Location<World> oldLocation, Location<World> newLocation, Vector3d rotation) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); values.put("rotation", rotation); return createEvent(DisplaceEntityEvent.Move.class, values); } /** * Creates a new {@link PickUpItemEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param items The items that will be picked up * @param inventory The inventory involved with the event * @return A new instance of the event */ public static PickUpItemEvent.SourceEntity createEntityPickupItem(Game game, Entity entity, Collection<Entity> items, Inventory inventory) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("items", items); values.put("inventory", inventory); return createEvent(PickUpItemEvent.SourceEntity.class, values); } /** * Creates a new {@link PlaceBlockEvent.SourceEntity}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static PlaceBlockEvent.SourceEntity createEntityPlaceBlock(Game game, Cause cause, Entity entity, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("location", location); values.put("block", location.getBlock()); values.put("entity", entity); values.put("replacementBlock", replacementBlock); return createEvent(PlaceBlockEvent.SourceEntity.class, values); } /** * Creates a new {@link TargetEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param targetEntity The target entity * @param targetTransform The target transform * @return A new instance of the event */ public static TargetEntityEvent createTargetEntity(Game game, Entity targetEntity, Transform<World> targetTransform) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetEntity", targetEntity); values.put("targetTransform", targetTransform); return createEvent(TargetEntityEvent.class, values); } /** * Creates a new {@link TargetLivingEvent}. * * @param game The game instance for this {@link GameEvent} * @param targetEntity The target living entity * @param targetTransform The target transform * @return A new instance of the event */ public static TargetLivingEvent createTargetLivingy(Game game, Entity targetEntity, Transform<World> targetTransform) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetEntity", targetEntity); values.put("targetTransform", targetTransform); return createEvent(TargetLivingEvent.class, values); } /** * Creates a new {@link SpawnEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param targetEntity The entity being spawned * @param targetTransform The transform of where the entity is being spawned * @return A new instance of the event */ public static SpawnEntityEvent createSpawnEntity(Game game, Entity targetEntity, Transform<World> targetTransform) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetEntity", targetEntity); values.put("targetTransform", targetTransform); return createEvent(SpawnEntityEvent.class, values); } /** * Creates a new {@link PreCreateEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @return A new instance of the event */ public static PreCreateEntityEvent createConstructEntity(Game game, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); return createEvent(PreCreateEntityEvent.class, values); } /** * Creates a new {@link TameEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param tamer The tamer that has tamed the entity * @return A new instance of the event */ public static TameEntityEvent createTameEntity(Game game, Entity entity, Tamer tamer) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("tamer", tamer); return createEvent(TameEntityEvent.class, values); } /** * Creates a new {@link DisplaceEntityEvent.Teleport}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param oldLocation The previous location of the entity * @param newLocation The new location of the entity * @param rotation The rotation the entity is facing * @param keepsVelocity Whether the entity will maintain velocity * @return A new instance of the event */ public static DisplaceEntityEvent.Teleport createTeleportEntity(Game game, Cause cause, Entity entity, Location<World> oldLocation, Location<World> newLocation, Vector3d rotation, boolean keepsVelocity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); values.put("rotation", rotation); values.put("keepsVelocity", keepsVelocity); return createEvent(DisplaceEntityEvent.Teleport.class, values); } /** * Creates a new {@link LaunchProjectileEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity * @param source The projectile source * @return A new instance of the event */ public static LaunchProjectileEvent createLaunchProjectile(Game game, Cause cause, Projectile entity, ProjectileSource source) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("launchedProjectile", entity); values.put("source", Optional.fromNullable(source)); return createEvent(LaunchProjectileEvent.class, values); } /** * Creates a new {@link SendCommandEvent}. * * @param game The game instance for this {@link GameEvent} * @param arguments The arguments provided * @param source The source of the command * @param command The command name * @param result The result of the command * @return A new instance of the event */ public static SendCommandEvent createSendCommand(Game game, String arguments, CommandSource source, String command, CommandResult result) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("arguments", arguments); values.put("source", source); values.put("command", command); values.put("result", result); return createEvent(SendCommandEvent.class, values); } /** * Creates a new {@link TabCompleteCommandEvent}. * * @param game The game instance for this {@link GameEvent} * @param arguments The arguments provided * @param source The source of the command * @param command The command name * @param suggestions The list of suggestion. Must be mutable. * @return A new instance of the event */ public static TabCompleteCommandEvent createTabCompleteCommand(Game game, String arguments, CommandSource source, String command, List<String> suggestions) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("arguments", arguments); values.put("source", source); values.put("command", command); values.put("suggestions", suggestions); return createEvent(TabCompleteCommandEvent.class, values); } /** * Creates a new {@link MessageEvent}. * * @param game The game instance for this {@link GameEvent} * @param source The source of the message * @param message The message to say * @param sink The destination for the message * @return A new instance of the event */ public static MessageEvent createMessage(Game game, CommandSource source, Text message, MessageSink sink) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("source", source); values.put("message", message); values.put("newMessage", message); values.put("sink", sink); return createEvent(MessageEvent.class, values); } /** * Creates a new {@link BreakBlockEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param transform The transform * @param transactions The block transactions * @return A new instance of the event */ public static BreakBlockEvent.SourcePlayer createPlayerBreakBlock(Game game, Cause cause, Player entity, Transform<World> transform, ImmutableList<BlockTransaction> transactions) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("transform", entity); values.put("transactions", transactions); return createEvent(BreakBlockEvent.SourcePlayer.class, values); } /** * Creates a new {@link FishingEvent.Cast.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param fishHook The {@link FishHook} effected by this event * @return A new instance of the event */ public static FishingEvent.Cast.SourcePlayer createPlayerCastFishingLine(Game game, Player entity, FishHook fishHook) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("fishHook", fishHook); return createEvent(FishingEvent.Cast.SourcePlayer.class, values); } /** * Creates a new {@link FishingEvent.Hook.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param fishHook The {@link FishHook} affected by this event * @param caughtEntity The {@link Entity} caught by the player, can be null * @return A new instance of the event */ public static FishingEvent.Hook.SourcePlayer createPlayerHookEntity(Game game, Player entity, FishHook fishHook, Entity caughtEntity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("fishHook", fishHook); values.put("caughtEntity", Optional.fromNullable(caughtEntity)); return createEvent(FishingEvent.Hook.SourcePlayer.class, values); } /** * Creates a new {@link FishingEvent.Retract.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param fishHook The {@link FishHook} affected by this event * @param caughtItem The {@link ItemStack} caught by the player, can be null * @param caughtEntity The {@link Entity} caught by the player, can be null * @param exp The experience to give, or take for negative values * @return A new instance of the event */ public static FishingEvent.Retract.SourcePlayer createPlayerRetractFishingLine(Game game, Player entity, FishHook fishHook, ItemStack caughtItem, Entity caughtEntity, int exp) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("fishHook", fishHook); values.put("caughtEntity", Optional.fromNullable(caughtEntity)); values.put("caughtItem", Optional.fromNullable(caughtItem)); values.put("exp", exp); return createEvent(FishingEvent.Retract.SourcePlayer.class, values); } /** * Creates a new {@link ChangeBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param transactions The block transactions * @return A new instance of the event */ public static ChangeBlockEvent createPlayerChangeBlock(Game game, Cause cause, ImmutableList<BlockTransaction> transactions) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("transactions", transactions); return createEvent(ChangeBlockEvent.class, values); } /** * Creates a new {@link ChangeBlockEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param blockFace The face of the block the player was changing * @param location The location * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static ChangeBlockEvent.SourcePlayer createPlayerChangeBlock(Game game, Cause cause, Player entity, Direction blockFace, Location<World> location, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("user", entity); values.put("blockFace", blockFace); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); return createEvent(ChangeBlockEvent.SourcePlayer.class, values); } /** * Creates a new {@link ChangeHumanGameModeEvent.TargetPlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param newGameMode The game mode to change to * @param oldGameMode The Player's old game mode * @return A new instance of the event */ public static ChangeHumanGameModeEvent.TargetPlayer createChangePlayerGameMode(Game game, Player entity, GameMode newGameMode, GameMode oldGameMode) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("newGameMode", newGameMode); values.put("oldGameMode", oldGameMode); return createEvent(ChangeHumanGameModeEvent.TargetPlayer.class, values); } /** * Creates a new {@link PlayerChatEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param message The message to say * @param unformattedMessage The unformatted message * @param sink The destination for the message * @return A new instance of the event */ public static PlayerChatEvent createPlayerChat(Game game, Player entity, Text message, Text unformattedMessage, MessageSink sink) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("source", entity); values.put("user", entity); values.put("message", message); values.put("newMessage", message); values.put("unformattedMessage", unformattedMessage); values.put("sink", sink); return createEvent(PlayerChatEvent.class, values); } /** * Creates a new {@link HarvestEntityEvent.TargetPlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param location The location of death * @param message The message to show to the player because they died * @param sink The destination for the message * @param exp The experience to give, or take for negative values * @param newExperience The new experience the player will have towards the next level * @param newLevel The new level the player will have after death * @param keepsLevel Whether the player keeps all of their exp on death * @param keepsInventory Whether the player should keep inventory * @return A new instance of the event */ public static HarvestEntityEvent.TargetPlayer createHarvestPlayer(Game game, Cause cause, Player entity, Location<World> location, Text message, MessageSink sink, int exp, int newExperience, int newLevel, boolean keepsLevel, boolean keepsInventory) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("source", entity); values.put("user", entity); values.put("location", location); values.put("message", message); values.put("newMessage", message); values.put("sink", sink); values.put("exp", exp); values.put("newExperience", newExperience); values.put("newLevel", newLevel); values.put("keepsLevel", keepsLevel); values.put("keepsInventory", keepsInventory); return createEvent(HarvestEntityEvent.TargetPlayer.class, values); } /** * Creates a new {@link DropItemStackEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param cause The cause of the event * @param droppedItems The items to drop * @return A new instance of the event */ public static DropItemStackEvent.SourcePlayer createPlayerDropItem(Game game, Player entity, Cause cause, Collection<ItemStack> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("user", entity); values.put("droppedItems", droppedItems); return createEvent(DropItemStackEvent.SourcePlayer.class, values); } /** * Creates a new {@link HarvestBlockEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param location The location * @param droppedItems The items to drop * @param dropChance The chance the items will drop, see * {@link HarvestBlockEvent#setDropChance(float)} * @param silkTouch Whether the player is harvesting with silk touch * @return A new instance of the event */ public static HarvestBlockEvent.SourcePlayer createPlayerHarvestBlock(Game game, Cause cause, Player entity, Location<World> location, Collection<ItemStack> droppedItems, float dropChance, boolean silkTouch) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("user", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("droppedItems", droppedItems); values.put("dropChance", dropChance); values.put("silkTouch", silkTouch); return createEvent(HarvestBlockEvent.SourcePlayer.class, values); } /** * Creates a new {@link InteractBlockEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param location The location * @param side The face interacted with as a direction * @param interactionType The type of interaction used * @param clickedPosition The clicked position * @return A new instance of the event */ public static InteractBlockEvent.SourcePlayer createPlayerInteractBlock(Game game, Cause cause, Player entity, Location<World> location, Direction side, EntityInteractionType interactionType, @Nullable Vector3d clickedPosition) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("user", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("side", side); values.put("interactionType", interactionType); values.put("clickedPosition", Optional.fromNullable(clickedPosition)); return createEvent(InteractBlockEvent.SourcePlayer.class, values); } /** * Creates a new {@link InteractEntityEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity * @param targetEntity The entity being interacted with * @param interactionType The type of interaction used * @param clickedPosition The clicked position * @return A new instance of the event */ public static InteractEntityEvent.SourcePlayer createPlayerInteractEntity(Game game, Player entity, Entity targetEntity, EntityInteractionType interactionType, @Nullable Vector3d clickedPosition) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("targetEntity", targetEntity); values.put("interactionType", interactionType); values.put("clickedPosition", Optional.fromNullable(clickedPosition)); return createEvent(InteractEntityEvent.SourcePlayer.class, values); } /** * Creates a new {@link PlayerJoinEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param location The location of where the player is joining * @param message The message displayed when the player joins * @param sink The destination for the message * @return A new instance of the event */ public static PlayerJoinEvent createPlayerJoin(Game game, Player entity, Location<World> location, Text message, MessageSink sink) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("source", entity); values.put("location", location); values.put("message", message); values.put("newMessage", message); values.put("sink" ,sink); return createEvent(PlayerJoinEvent.class, values); } /** * Creates a new {@link DisplaceEntityEvent.Move.TargetPlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param oldTransform The previous location of the entity * @param newTransform The new location of the entity * @param targetTransform The current transform of the targeted entity * @return A new instance of the event */ public static DisplaceEntityEvent.Move.TargetPlayer createMovePlayer(Game game, Player entity, Transform<World> oldTransform, Transform<World> newTransform, Transform<World> targetTransform) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetEntity", entity); values.put("oldTransform", oldTransform); values.put("newTransform", newTransform); values.put("targetTransform", targetTransform); return createEvent(DisplaceEntityEvent.Move.TargetPlayer.class, values); } /** * Creates a new {@link PickUpItemEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param items The items that will be picked up * @param inventory The inventory involved with the event * @return A new instance of the event */ public static PickUpItemEvent.SourcePlayer createPlayerPickupItem(Game game, Player entity, Collection<Entity> items, Inventory inventory) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("items", items); values.put("inventory", inventory); return createEvent(PickUpItemEvent.SourcePlayer.class, values); } /** * Creates a new {@link PlaceBlockEvent.SourcePlayer}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The player * @param location The location * @param replacementBlock The block that will replace the existing block * @param blockFace The face the block was placed * @return A new instance of the event */ public static PlaceBlockEvent.SourcePlayer createPlayerPlaceBlock(Game game, Cause cause, Player entity, Location<World> location, BlockSnapshot replacementBlock, Direction blockFace) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("entity", entity); values.put("user", entity); values.put("location", location); values.put("block", location.getBlock()); values.put("replacementBlock", replacementBlock); values.put("blockFace", blockFace); return createEvent(PlaceBlockEvent.SourcePlayer.class, values); } /** * Creates a new {@link PlayerQuitEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param message The message to display to the player because they quit * @param sink The destination for the message * @return A new instance of the event */ public static PlayerQuitEvent createPlayerQuit(Game game, Player entity, Text message, MessageSink sink) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("source", entity); values.put("user", entity); values.put("message", message); values.put("newMessage", message); values.put("sink", sink); return createEvent(PlayerQuitEvent.class, values); } /** * Creates a new {@link RespawnPlayerEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param bedSpawn Whether this respawn is to a bed * @param respawnLocation The location the player will spawn in * @return A new instance of the event */ public static RespawnPlayerEvent createRespawnPlayer(Game game, Player entity, Location<World> respawnLocation, boolean bedSpawn) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("respawnLocation", respawnLocation); values.put("newRespawnLocation", respawnLocation); values.put("bedSpawn", bedSpawn); return createEvent(RespawnPlayerEvent.class, values); } /** * Creates a new {@link AchievementEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param achievement The achievement being added to the player * @return A new instance of the event */ /* TODO public static AchievementEvent createAchievement(Game game, Player entity, Achievement achievement) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("achievement", achievement); return createEvent(AchievementEvent.class, values); }*/ /** * Creates a new {@link PlayerChangeStatisticEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The player * @param changedStatistic Any statistics changed by this event * @param oldValue The old value of the statistic * @param newValue The new value of the statistic * @return A new instance of the event */ public static PlayerChangeStatisticEvent createPlayerChangeStatistic(Game game, Player entity, Statistic changedStatistic, long newValue, long oldValue) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("user", entity); values.put("changedStatistic", changedStatistic); values.put("newValue", newValue); values.put("oldValue", oldValue); return createEvent(PlayerChangeStatisticEvent.class, values); } /** * Creates a new {@link ChangeWorldWeatherEvent}. * * @param game The game instance for this {@link GameEvent} * @param weatherUniverse The universe the weather changed in * @param initialWeather The previous weather * @param resultingWeather The weather to change to * @param duration The lenfth of the resulting weather, in ticks * @return A new instance of the event */ public static ChangeWorldWeatherEvent createChangeWorldWeather(Game game, WeatherUniverse weatherUniverse, Weather initialWeather, Weather resultingWeather, int duration) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("weatherUniverse", weatherUniverse); values.put("initialWeather", initialWeather); values.put("resultingWeather", resultingWeather); values.put("duration", duration); return createEvent(ChangeWorldWeatherEvent.class, values); } /** * Creates a new {@link PluginForceChunkEvent}. * * @param game The game instance for this {@link GameEvent} * @param ticket The ticket that will load the chunk * @param chunkCoords The coordinates of the chunk being added * @return A new instance of the event */ public static PluginForceChunkEvent createPluginForceChunk(Game game, LoadingTicket ticket, Vector3i chunkCoords) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("ticket", ticket); values.put("chunkCoords", chunkCoords); return createEvent(PluginForceChunkEvent.class, values); } /** * Creates a new {@link LoadChunkEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static LoadChunkEvent createLoadChunk(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(LoadChunkEvent.class, values); } /** * Creates a new {@link WorldGenerateChunkEvent.Post}. * * @param game The game instance for this {@link GameEvent} * @param targetChunk The chunk involved in this event * @return A new instance of the event */ public static WorldGenerateChunkEvent.Post createWorldPostGenerateChunk(Game game, Chunk targetChunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetChunk", targetChunk); return createEvent(WorldGenerateChunkEvent.Post.class, values); } /** * Creates a new {@link WorldGenerateChunkEvent.Pre}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static WorldGenerateChunkEvent.Pre createWorldPreGenerateChunk(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(WorldGenerateChunkEvent.Pre.class, values); } /** * Creates a new {@link WorldPopulateChunkEvent.Pre}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @param pendingPopulators All populator's that will populate the chunk * @return A new instance of the event */ public static WorldPopulateChunkEvent.Pre createWorldPrePopulateChunk(Game game, Chunk chunk, List<Populator> pendingPopulators) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); values.put("pendingPopulators", pendingPopulators); return createEvent(WorldPopulateChunkEvent.Pre.class, values); } /** * Creates a new {@link WorldPopulateChunkEvent.Post}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static WorldPopulateChunkEvent.Post createWorldPostPopulateChunk(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(WorldPopulateChunkEvent.Post.class, values); } /** * Creates a new {@link UnforcedChunkEvent}. * * @param game The game instance for this {@link GameEvent} * @param ticket The ticket the chunk was removed from * @param chunkCoords The coordinates of the removed chunk* * @return A new instance of the event */ public static UnforcedChunkEvent createUnforcedChunk(Game game, LoadingTicket ticket, Vector3i chunkCoords) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("ticket", ticket); values.put("chunkCoords", chunkCoords); return createEvent(UnforcedChunkEvent.class, values); } /** * Creates a new {@link UnloadChunkEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static UnloadChunkEvent createUnloadChunk(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(UnloadChunkEvent.class, values); } /** * Creates a new {@link ChangeWorldGameRuleEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @param name The name of the game rule * @param oldValue The previous value for the rule * @param newValue The new value for the rule * @return A new instance of the event */ public static ChangeWorldGameRuleEvent createChangeWorldGameRule(Game game, World world, String name, String oldValue, String newValue) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("targetWorld", world); values.put("name", name); values.put("oldValue", oldValue); values.put("newValue", newValue); return createEvent(ChangeWorldGameRuleEvent.class, values); } /** * Creates a new {@link CreateWorldEvent}. * * @param game The game instance for this {@link GameEvent} * @param properties The properties of the new world * @param settings The creation settings * @return A new instance of the event */ public static ServerCreateWorldEvent createServerCreateWorld(Game game, WorldProperties properties, WorldCreationSettings settings) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Cause.of(game.getServer())); values.put("worldProperties", properties); values.put("worldCreationSettings", settings); return createEvent(ServerCreateWorldEvent.class, values); } /** * Creates a new {@link ServerLoadWorldEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @return A new instance of the event */ public static ServerLoadWorldEvent createServerLoadWorld(Game game, World world) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Cause.of(game.getServer())); values.put("targetWorld", world); return createEvent(ServerLoadWorldEvent.class, values); } /** * Creates a new {@link ServerUnloadWorldEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @return A new instance of the event */ public static ServerUnloadWorldEvent createServerUnloadWorld(Game game, World world) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Cause.of(game.getServer())); values.put("targetWorld", world); return createEvent(ServerUnloadWorldEvent.class, values); } /** * Creates a new {@link PingServerEvent}. * * @param game The game instance for this {@link GameEvent} * @param client The client that is pinging the server * @param response The response to send to the client * @return A new instance of the event */ public static PingServerEvent createPingServer(Game game, StatusClient client, PingServerEvent.Response response) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("client", client); values.put("response", response); return createEvent(PingServerEvent.class, values); } /** * Creates a new {@link BrewingStandBrewItemsEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause * @param brewingStand The {@link BrewingStand} involved in this event * @param sourceItems The {@link ItemStack}s being modified * @param fuelSource The {@link ItemStack} used as the reagent to modify the source items * @param brewedItems The {@link ItemStack}s produced as a result * @param inventory The inventory of the brewing stand * @param data The brewing stand data * @param location The location * @return A new instance of the event */ public static BrewingStandBrewItemsEvent createBrewingStandBrewItems(Game game, Cause cause, BrewingStand brewingStand, ImmutableBrewingData data, List<ItemStack> sourceItems, ItemStack fuelSource, List<ItemStack> brewedItems, TileEntityInventory<TileEntityCarrier> inventory, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("tile", brewingStand); values.put("sourceItems", sourceItems); values.put("fuelSource", fuelSource); values.put("brewedItems", brewedItems); values.put("results", brewedItems); values.put("inventory", inventory); values.put("location", location); values.put("block", location.getBlock()); values.put("currentData", data); return createEvent(BrewingStandBrewItemsEvent.class, values); } /** * Creates a new {@link FurnaceConsumeFuelEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause * @param furnace The {@link Furnace} involved in this event * @param burnedItem The {@link ItemStack} consumed for fuel * @param remainingFuel The {@link ItemStack} representing the remaining fuel, can be null * @param inventory The inventory of the furnace * @param data The furnace data * @param location The location * @return A new instance of the event */ public static FurnaceConsumeFuelEvent createFurnaceConsumeFuel(Game game, Cause cause, Furnace furnace, ImmutableFurnaceData data, ItemStack burnedItem, ItemStack remainingFuel, TileEntityInventory<TileEntityCarrier> inventory, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("tile", furnace); values.put("burnedItem", burnedItem); values.put("remainingFuel", Optional.fromNullable(remainingFuel)); values.put("result", Optional.fromNullable(remainingFuel)); values.put("inventory", inventory); values.put("location", location); values.put("block", location.getBlock()); values.put("currentData", data); return createEvent(FurnaceConsumeFuelEvent.class, values); } /** * Creates a new {@link FurnaceSmeltItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause * @param furnace The {@link Furnace} involved in this event * @param cookedItem The {@link ItemStack} resulting from smelting the source item * @param sourceItem The {@link ItemStack} smelted to create the cooked item * @param inventory The inventory of the furnace * @param data The furnace data * @param location The location * @return A new instance of the event */ public static FurnaceSmeltItemEvent createFurnaceSmeltItem(Game game, Cause cause, Furnace furnace, ImmutableFurnaceData data, ItemStack cookedItem, ItemStack sourceItem, TileEntityInventory<TileEntityCarrier> inventory, Location<World> location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("tile", furnace); values.put("cookedItem", cookedItem); values.put("sourceItem", sourceItem); values.put("result", Optional.fromNullable(cookedItem)); values.put("inventory", inventory); values.put("location", location); values.put("block", location.getBlock()); values.put("currentData", data); return createEvent(FurnaceSmeltItemEvent.class, values); } /** * Creates a new {@link PlayerChangeSignEvent}. * @param game The game instance for this {@link GameEvent} * @param cause The cause * @param sign The {@link Sign} * @param currentData The current sign data * @param newData The new sign data * @return A new instance of the event */ public static PlayerChangeSignEvent createPlayerChangeSign(Game game, Cause cause, Sign sign, ImmutableSignData currentData, SignData newData) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("tile", sign); values.put("currentData", currentData); values.put("newData", newData); return createEvent(PlayerChangeSignEvent.class, values); } /** * Creates a new {@link RconLoginEvent}. * * @param game The game instance for this {@link GameEvent} * @param source The {@link RconSource} that caused this event * @return A new instance of the event */ public static RconLoginEvent createRconLogin(Game game, RconSource source) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("source", source); return createEvent(RconLoginEvent.class, values); } /** * Creates a new {@link RconQuitEvent}. * * @param game The game instance for this {@link GameEvent} * @param source The {@link RconSource} that caused this event * @return A new instance of the event */ public static RconQuitEvent createRconQuit(Game game, RconSource source) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("source", source); return createEvent(RconQuitEvent.class, values); } /** * Creates a new {@link GameClientConnectEvent}. * * @param game The game instance for this {@link GameEvent} * @param connection The connection info of the client * @param profile The profile of the client attempting to connect * @param disconnectMessage The message to show to the client if the event * is cancelled * @param disconnectCause The cause for disconnected if the event is cancelled * @return A new instance of the event */ public static GameClientConnectEvent createGameClientConnect(Game game, RemoteConnection connection, GameProfile profile, @Nullable Text disconnectMessage, @Nullable Cause disconnectCause) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("connection", connection); values.put("profile", profile); values.put("disconnectMessage", Optional.fromNullable(disconnectMessage)); values.put("disconnectCause", Optional.fromNullable(disconnectCause)); return createEvent(GameClientConnectEvent.class, values); } /** * Creates a new {@link GameClientAuthEvent}. * * @param game The game instance for this {@link GameEvent} * @param connection The connection info of the client * @param profile The profile of the client attempting to connect * @param disconnectMessage The message to show to the client if the event * is cancelled * @param disconnectCause The cause for disconnected if the event is cancelled * @return A new instance of the event */ public static GameClientAuthEvent createGameClientAuth(Game game, RemoteConnection connection, GameProfile profile, @Nullable Text disconnectMessage, @Nullable Cause disconnectCause) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("connection", connection); values.put("profile", profile); values.put("disconnectMessage", Optional.fromNullable(disconnectMessage)); values.put("disconnectCause", Optional.fromNullable(disconnectCause)); return createEvent(GameClientAuthEvent.class, values); } /** * Creates a new {@link WorldDecayBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param world The world * @param transactions The list of block transactions * @return A new instance of the event */ public static WorldDecayBlockEvent createWorldDecayBlock(Game game, Cause cause, World world, ImmutableList<BlockTransaction> transactions) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", cause); values.put("sourceWorld", world); values.put("transactions", transactions); return createEvent(WorldDecayBlockEvent.class, values); } /** * Creates a new {@link WorldExplosionEvent}. * * @param game The game instance for this {@link GameEvent} * @param explosion The explosion * @return A new instance of the event */ public static WorldExplosionEvent createWorldExplosion(Game game, Explosion explosion) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("sourceWorld", explosion.getWorld()); values.put("explosion", explosion); return createEvent(WorldExplosionEvent.class, values); } /** * Creates a new {@link WorldExplosionEvent.Pre}. * * @param game The game instance for this {@link GameEvent} * @param explosion The explosion * @return A new instance of the event */ public static WorldExplosionEvent.Pre createWorldPreExplosion(Game game, Explosion explosion) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("sourceWorld", explosion.getWorld()); values.put("explosion", explosion); return createEvent(WorldExplosionEvent.Pre.class, values); } /** * Creates a new {@link WorldExplosionEvent.OnExplosion}. * * @param game The game instance for this {@link GameEvent} * @param explosion The explosion * @param locations The affected locations * @param entities The affected entities * @return A new instance of the event */ public static WorldExplosionEvent.OnExplosion createWorldOnExplosion(Game game, Cause cause, Explosion explosion, List<Location<World>> locations, List<Entity> entities) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("sourceWorld", explosion.getWorld()); values.put("explosion", explosion); values.put("locations", locations); values.put("originalLocations", ImmutableList.copyOf(locations)); values.put("entities", entities); values.put("originalEntities", ImmutableList.copyOf(entities)); return createEvent(WorldExplosionEvent.OnExplosion.class, values); } }
package org.jitsi.impl.neomedia.recording; import com.sun.media.util.*; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.audiolevel.*; import org.jitsi.impl.neomedia.codec.*; import org.jitsi.impl.neomedia.device.*; import org.jitsi.impl.neomedia.rtp.*; import org.jitsi.impl.neomedia.rtp.translator.*; import org.jitsi.impl.neomedia.transform.*; import org.jitsi.impl.neomedia.transform.fec.*; import org.jitsi.impl.neomedia.transform.rtcp.*; import org.jitsi.service.libjitsi.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.MediaException; import org.jitsi.service.neomedia.codec.*; import org.jitsi.service.neomedia.control.*; import org.jitsi.service.neomedia.event.*; import org.jitsi.service.neomedia.recording.*; import org.jitsi.util.*; import javax.media.*; import javax.media.control.*; import javax.media.format.*; import javax.media.protocol.*; import javax.media.rtp.*; import javax.media.rtp.event.*; import java.io.*; import java.lang.reflect.*; import java.util.*; /** * A <tt>Recorder</tt> implementation which attaches to an <tt>RTPTranslator</tt>. * * @author Vladimir Marinov * @author Boris Grozev */ public class RecorderRtpImpl implements Recorder, ReceiveStreamListener, ActiveSpeakerChangedListener, ControllerListener { /** * The <tt>Logger</tt> used by the <tt>RecorderRtpImpl</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(RecorderRtpImpl.class); //values hard-coded to match chrome //TODO: allow to set them dynamically private static final byte redPayloadType = 116; private static final byte ulpfecPayloadType = 117; private static final byte vp8PayloadType = 100; private static final byte opusPayloadType = 111; private static final Format redFormat = new VideoFormat(Constants.RED); private static final Format ulpfecFormat = new VideoFormat(Constants.ULPFEC); private static final Format vp8RtpFormat = new VideoFormat(Constants.VP8_RTP); private static final Format vp8Format = new VideoFormat(Constants.VP8); private static final Format opusFormat = new AudioFormat(Constants.OPUS_RTP, 48000, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED); private static final int FMJ_VIDEO_JITTER_BUFFER_MIN_SIZE = 300; private static final int FMJ_AUDIO_JITTER_BUFFER_MIN_SIZE = 16; /** * The <tt>ContentDescriptor</tt> to use when saving audio. */ private static final ContentDescriptor AUDIO_CONTENT_DESCRIPTOR = new ContentDescriptor(FileTypeDescriptor.MPEG_AUDIO); /** * The suffix for audio file names. */ private static final String AUDIO_FILENAME_SUFFIX = ".mp3"; /** * The suffix for video file names. */ private static final String VIDEO_FILENAME_SUFFIX = ".webm"; static { Registry.set( "video_jitter_buffer_MIN_SIZE", FMJ_VIDEO_JITTER_BUFFER_MIN_SIZE); Registry.set( "adaptive_jitter_buffer_MIN_SIZE", FMJ_AUDIO_JITTER_BUFFER_MIN_SIZE); } /** * The <tt>RTPTranslator</tt> that this recorder is/will be attached * to. */ private RTPTranslatorImpl translator; /** * The custom <tt>RTPConnector</tt> that this instance uses to read from * {@link #translator} and write to {@link #rtpManager}. */ private RTPConnectorImpl rtpConnector; /** * Path to the directory where the output files will be stored. */ private String path; /** * The <tt>RTCPFeedbackMessageSender</tt> that we use to send RTCP FIR * messages. */ private RTCPFeedbackMessageSender rtcpFeedbackSender; /** * The {@link RTPManager} instance we use to handle the packets coming * from <tt>RTPTranslator</tt>. */ private RTPManager rtpManager; /** * The instance which should be notified when events related to recordings * (such as the start or end of a recording) occur. */ private RecorderEventHandlerImpl eventHandler; /** * Holds the <tt>ReceiveStreams</tt> added to this instance by * {@link #rtpManager} and additional information associated with each one * (e.g. the <tt>Processor</tt>, if any, used for it). */ private final HashSet<ReceiveStreamDesc> receiveStreams = new HashSet<ReceiveStreamDesc>(); private final Set<Long> activeVideoSsrcs = new HashSet<Long>(); /** * The <tt>ActiveSpeakerDetector</tt> which will listen to the audio receive * streams of this <tt>RecorderRtpImpl</tt> and notify it about changes to * the active speaker via calls to {@link #activeSpeakerChanged(long)} */ private ActiveSpeakerDetector activeSpeakerDetector = null; StreamRTPManager streamRTPManager; private SynchronizerImpl synchronizer; private boolean started = false; /** * Constructor. * * @param translator the <tt>RTPTranslator</tt> to which this instance will * attach in order to record media. */ public RecorderRtpImpl(RTPTranslator translator) { this.translator = (RTPTranslatorImpl) translator; activeSpeakerDetector = new ActiveSpeakerDetectorImpl(); activeSpeakerDetector.addActiveSpeakerChangedListener(this); } /** * Implements {@link Recorder#addListener(Recorder.Listener)}. */ @Override public void addListener(Listener listener) { } /** * Implements {@link Recorder#removeListener(Recorder.Listener)}. */ @Override public void removeListener(Listener listener) { } /** * Implements {@link Recorder#getSupportedFormats()}. */ @Override public List<String> getSupportedFormats() { return null; } /** * Implements {@link Recorder#setMute(boolean)}. */ @Override public void setMute(boolean mute) { } /** * Implements {@link Recorder#getFilename()}. Returns null, since we don't * have a (single) associated filename. */ @Override public String getFilename() { return null; } /** * Sets the instance which should be notified when events related to * recordings (such as the start or end of a recording) occur. */ public void setEventHandler(RecorderEventHandler eventHandler) { if (this.eventHandler == null || (this.eventHandler != eventHandler && this.eventHandler.handler != eventHandler)) { if (this.eventHandler == null) this.eventHandler = new RecorderEventHandlerImpl(eventHandler); else this.eventHandler.handler = eventHandler; } } /** * {@inheritDoc} * * @param format unused, since this implementation records multiple streams * using potentially different formats. * @param dirname the path to the directory into which this <tt>Recorder</tt> * will store the recorded media files. */ @Override public void start(String format, String dirname) throws IOException, MediaException { if (logger.isInfoEnabled()) logger.info("Starting, format=" + format + " " + hashCode()); path = dirname; MediaService mediaService = LibJitsi.getMediaService(); /* * Note that we use only one RTPConnector for both the RTPTranslator * and the RTPManager instances. The this.translator will write to its * output streams, and this.rtpManager will read from its input streams. */ rtpConnector = new RTPConnectorImpl(redPayloadType, ulpfecPayloadType); rtpManager = RTPManager.newInstance(); /* * Add the formats that we know about. */ rtpManager.addFormat(vp8RtpFormat, vp8PayloadType); rtpManager.addFormat(opusFormat, opusPayloadType); rtpManager.addReceiveStreamListener(this); /* * Note: When this.rtpManager sends RTCP sender/receiver reports, they * will end up being written to its own input stream. This is not * expected to cause problems, but might be something to keep an eye on. */ rtpManager.initialize(rtpConnector); /* * Register a fake call participant. * TODO: can we use a more generic MediaStream here? */ streamRTPManager = new StreamRTPManager( mediaService.createMediaStream(new MediaDeviceImpl( new CaptureDeviceInfo(), MediaType.VIDEO)), translator); streamRTPManager.initialize(rtpConnector); rtcpFeedbackSender = translator.getRtcpFeedbackMessageSender(); translator.addFormat(streamRTPManager, opusFormat, opusPayloadType); //((RTPTranslatorImpl)videoRTPTranslator).addFormat(streamRTPManager, redFormat, redPayloadType); //((RTPTranslatorImpl)videoRTPTranslator).addFormat(streamRTPManager, ulpfecFormat, ulpfecPayloadType); //((RTPTranslatorImpl)videoRTPTranslator).addFormat(streamRTPManager, mediaFormatImpl.getFormat(), vp8PayloadType); started = true; } @Override public void stop() { if (started) { if (logger.isInfoEnabled()) logger.info("Stopping " + hashCode()); // remove the recorder from the translator (e.g. stop new packets from // being written to rtpConnector if (streamRTPManager != null) streamRTPManager.dispose(); HashSet<ReceiveStreamDesc> streamsToRemove = new HashSet<ReceiveStreamDesc>(); synchronized (receiveStreams) { streamsToRemove.addAll(receiveStreams); } for(ReceiveStreamDesc r : streamsToRemove) removeReceiveStream(r, false); rtpConnector.rtcpPacketTransformer.close(); rtpConnector.rtpPacketTransformer.close(); rtpManager.dispose(); if (activeSpeakerDetector != null) activeSpeakerDetector.removeActiveSpeakerChangedListener(this); started=false; } } /** * Implements {@link ReceiveStreamListener#update(ReceiveStreamEvent)}. * * {@link #rtpManager} will use this to notify us of * <tt>ReceiveStreamEvent</tt>s. */ @Override public void update(ReceiveStreamEvent event) { if (event == null) return; ReceiveStream receiveStream = event.getReceiveStream(); if (event instanceof NewReceiveStreamEvent) { if (receiveStream == null) { logger.warn("NewReceiveStreamEvent: null"); return; } final long ssrc = getReceiveStreamSSRC(receiveStream); ReceiveStreamDesc receiveStreamDesc = findReceiveStream(ssrc); if (receiveStreamDesc != null) { String s = "NewReceiveStreamEvent for an existing SSRC. "; if (receiveStream != receiveStreamDesc.receiveStream) s += "(but different ReceiveStream object)"; logger.warn(s); return; } else receiveStreamDesc = new ReceiveStreamDesc(receiveStream); if (logger.isInfoEnabled()) logger.info("New ReceiveStream, ssrc=" + ssrc); // Find the format of the ReceiveStream DataSource dataSource = receiveStream.getDataSource(); if (dataSource instanceof PushBufferDataSource) { Format format = null; PushBufferDataSource pbds = (PushBufferDataSource) dataSource; for (PushBufferStream pbs : pbds.getStreams()) { if ((format = pbs.getFormat()) != null) break; } if (format == null) { logger.error("Failed to handle new ReceiveStream: " + "Failed to determine format"); return; } receiveStreamDesc.format = format; } else { logger.error("Failed to handle new ReceiveStream: " + "Unsupported DataSource"); return; } int rtpClockRate = -1; if (receiveStreamDesc.format instanceof AudioFormat) rtpClockRate = (int) ((AudioFormat) receiveStreamDesc.format) .getSampleRate(); else if (receiveStreamDesc.format instanceof VideoFormat) rtpClockRate = 90000; getSynchronizer().setRtpClockRate(ssrc, rtpClockRate); //create a Processor and configure it Processor processor = null; try { processor = Manager.createProcessor(receiveStream.getDataSource()); } catch (NoProcessorException npe) { logger.error("Failed to create Processor: ", npe); return; } catch (IOException ioe) { logger.error("Failed to create Processor: ", ioe); return; } if (logger.isInfoEnabled()) logger.info("Created processor for SSRC="+ssrc); processor.addControllerListener(this); receiveStreamDesc.processor = processor; final int streamCount; synchronized (receiveStreams) { receiveStreams.add(receiveStreamDesc); streamCount = receiveStreams.size(); } /* * XXX TODO IRBABOON * This is a terrible hack which works around a failure to realize() * some of the Processor-s for audio streams, when multiple streams * start nearly simultaneously. The cause of the problem is currently * unknown (and synchronizing all FMJ calls in RecorderRtpImpl * does not help). * XXX TODO NOOBABRI */ if (receiveStreamDesc.format instanceof AudioFormat) { final Processor p = processor; new Thread(){ @Override public void run() { // delay configuring the processors for the different // audio streams to decrease the probability that they // run together. try { int ms = 450 * (streamCount - 1); logger.warn("Sleeping for " + ms + "ms before" + " configuring processor for SSRC=" + ssrc+ " "+System.currentTimeMillis()); Thread.sleep(ms); } catch (Exception e) {} p.configure(); } }.run(); } else { processor.configure(); } } else if (event instanceof TimeoutEvent) { if (receiveStream == null) { // TODO: we might want to get the list of ReceiveStream-s from // rtpManager and compare it to our list, to see if we should // remove a stream. logger.warn("TimeoutEvent: null."); return; } // FMJ silently creates new ReceiveStream instances, so we have to // recognize them by the SSRC. ReceiveStreamDesc receiveStreamDesc = findReceiveStream(getReceiveStreamSSRC(receiveStream)); if (receiveStreamDesc != null) { if (logger.isInfoEnabled()) { logger.info("ReceiveStream timeout, ssrc=" + receiveStreamDesc.ssrc); } removeReceiveStream(receiveStreamDesc, true); } } else if (event != null && logger.isInfoEnabled()) { logger.info("Unhandled ReceiveStreamEvent (" + event.getClass().getName() + "): " + event); } } private void removeReceiveStream(ReceiveStreamDesc receiveStream, boolean emptyJB) { if (receiveStream.format instanceof VideoFormat) { long ssrc = receiveStream.ssrc; // Don't accept packets with this SSRC rtpConnector.packetBuffer.disable(ssrc); emptyPacketBuffer(ssrc); // Continue accepting packets with this SSRC rtpConnector.packetBuffer.reset(ssrc); } if (receiveStream.dataSink != null) { try { receiveStream.dataSink.stop(); } catch (IOException e) { logger.error("Failed to stop DataSink " + e); } receiveStream.dataSink.close(); } if (receiveStream.processor != null) { receiveStream.processor.stop(); receiveStream.processor.close(); } DataSource dataSource = receiveStream.receiveStream.getDataSource(); if (dataSource != null) { try { dataSource.stop(); } catch (IOException ioe) { logger.warn("Failed to stop DataSource"); } dataSource.disconnect(); } synchronized(receiveStreams) { receiveStreams.remove(receiveStream); } } /** * Implements {@link ControllerListener#controllerUpdate(ControllerEvent)}. * Handles events from the <tt>Processor</tt>s that this instance uses to * transcode media. * @param ev the event to handle. */ public void controllerUpdate(ControllerEvent ev) { if (ev == null || ev.getSourceController() == null) { return; } Processor processor = (Processor) ev.getSourceController(); ReceiveStreamDesc desc = findReceiveStream(processor); if (desc == null) { logger.warn("Event from an orphaned processor, ignoring: " + ev); return; } if (ev instanceof ConfigureCompleteEvent) { if (logger.isInfoEnabled()) { logger.info("Configured processor for ReceiveStream ssrc=" + desc.ssrc + " (" + desc.format + ")" +" "+System.currentTimeMillis()); } boolean audio = desc.format instanceof AudioFormat; if (audio) { ContentDescriptor cd = processor.setContentDescriptor(AUDIO_CONTENT_DESCRIPTOR); if (!AUDIO_CONTENT_DESCRIPTOR.equals(cd)) { logger.error("Failed to set the Processor content " + "descriptor to " + AUDIO_CONTENT_DESCRIPTOR + ". Actual result: " + cd); removeReceiveStream(desc, false); return; } } for (TrackControl track : processor.getTrackControls()) { Format trackFormat = track.getFormat(); if (audio) { final long ssrc = desc.ssrc; SilenceEffect silenceEffect; if (Constants.OPUS_RTP.equals(desc.format.getEncoding())) { silenceEffect = new SilenceEffect(48000); } else { // We haven't tested that the RTP timestamps survive // the journey through the chain when codecs other than // opus are in use, so for the moment we rely on FMJ's // timestamps for non-opus formats. silenceEffect = new SilenceEffect(); } silenceEffect.setListener( new SilenceEffect.Listener() { boolean first = true; @Override public void onSilenceNotInserted(long timestamp) { if (first) { first = false; //send event only audioRecordingStarted(ssrc, timestamp); } else { //change file and send event resetRecording(ssrc, timestamp); } } } ); desc.silenceEffect = silenceEffect; AudioLevelEffect audioLevelEffect = new AudioLevelEffect(); audioLevelEffect.setAudioLevelListener( new SimpleAudioLevelListener() { @Override public void audioLevelChanged(int level) { activeSpeakerDetector.levelChanged(ssrc,level); } } ); try { // We add an effect, which will insert "silence" in // place of lost packets. track.setCodecChain(new Codec[]{ silenceEffect, audioLevelEffect}); } catch (UnsupportedPlugInException upie) { logger.warn("Failed to insert silence effect: " + upie); // But do go on, a recording without extra silence is // better than nothing ;) } } else { // transcode vp8/rtp to vp8 (i.e. depacketize vp8) if (trackFormat.matches(vp8RtpFormat)) track.setFormat(vp8Format); else { logger.error("Unsupported track format: " + trackFormat + " for ssrc=" + desc.ssrc); // we currently only support vp8 removeReceiveStream(desc, false); return; } } } processor.realize(); } else if (ev instanceof RealizeCompleteEvent) { desc.dataSource = processor.getDataOutput(); long ssrc = desc.ssrc; boolean audio = desc.format instanceof AudioFormat; String suffix = audio ? AUDIO_FILENAME_SUFFIX : VIDEO_FILENAME_SUFFIX; // XXX '\' on windows? String filename = getNextFilename(path + "/" + ssrc, suffix); desc.filename = filename; DataSink dataSink; if (audio) { try { dataSink = Manager.createDataSink(desc.dataSource, new MediaLocator( "file:" + filename)); } catch (NoDataSinkException ndse) { logger.error("Could not create DataSink: " + ndse); removeReceiveStream(desc, false); return; } } else { dataSink = new WebmDataSink(filename, desc.dataSource); } if (logger.isInfoEnabled()) logger.info("Created DataSink (" + dataSink + ") for SSRC=" + ssrc + ". Output filename: " + filename); try { dataSink.open(); } catch (IOException e) { logger.error("Failed to open DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ": " + e); removeReceiveStream(desc, false); return; } if (!audio) { final WebmDataSink webmDataSink = (WebmDataSink) dataSink; webmDataSink.setSsrc(ssrc); webmDataSink.setEventHandler(eventHandler); webmDataSink.setKeyFrameControl(new KeyFrameControlAdapter() { @Override public boolean requestKeyFrame( boolean urgent) { return requestFIR(webmDataSink); } }); } try { dataSink.start(); } catch (IOException e) { logger.error("Failed to start DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ". " + e); removeReceiveStream(desc, false); return; } if (logger.isInfoEnabled()) logger.info("Started DataSink for SSRC=" + ssrc); desc.dataSink = dataSink; processor.start(); } else if (logger.isDebugEnabled()) { logger.debug("Unhandled ControllerEvent from the Processor for ssrc=" + desc.ssrc + ": " + ev); } } /** * Restarts the recording for a specific SSRC. * @param ssrc the SSRC for which to restart recording. * RTP packet of the new recording). */ private void resetRecording(long ssrc, long timestamp) { ReceiveStreamDesc receiveStream = findReceiveStream(ssrc); //we only restart audio recordings if (receiveStream != null && receiveStream.format instanceof AudioFormat) { String newFilename = getNextFilename(path + "/" + ssrc, AUDIO_FILENAME_SUFFIX); //flush the buffer contained in the MP3 encoder String s= "trying to flush ssrc="+ssrc; Processor p = receiveStream.processor; if (p != null) { s+=" p!=null"; for (TrackControl tc : p.getTrackControls()) { Object o = tc.getControl(FlushableControl.class.getName()); if (o != null) ((FlushableControl)o).flush(); } } if (logger.isInfoEnabled()) { logger.info("Restarting recording for SSRC=" + ssrc + ". New filename: "+ newFilename); } receiveStream.dataSink.close(); receiveStream.dataSink = null; // flush the FMJ jitter buffer //DataSource ds = receiveStream.receiveStream.getDataSource(); //if (ds instanceof net.sf.fmj.media.protocol.rtp.DataSource) // ((net.sf.fmj.media.protocol.rtp.DataSource)ds).flush(); receiveStream.filename = newFilename; try { receiveStream.dataSink = Manager.createDataSink(receiveStream.dataSource, new MediaLocator( "file:" + newFilename)); } catch (NoDataSinkException ndse) { logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ndse); removeReceiveStream(receiveStream, false); } try { receiveStream.dataSink.open(); receiveStream.dataSink.start(); } catch (IOException ioe) { logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ioe); removeReceiveStream(receiveStream, false); } audioRecordingStarted(ssrc, timestamp); } } private void audioRecordingStarted(long ssrc, long timestamp) { ReceiveStreamDesc desc = findReceiveStream(ssrc); if (desc == null) return; RecorderEvent event = new RecorderEvent(); event.setType(RecorderEvent.Type.RECORDING_STARTED); event.setMediaType(MediaType.AUDIO); event.setSsrc(ssrc); event.setRtpTimestamp(timestamp); event.setFilename(desc.filename); if (eventHandler != null) eventHandler.handleEvent(event); } /** * Handles a request from a specific <tt>DataSink</tt> to request a keyframe * by sending an RTCP feedback FIR message to the media source. * * @param dataSink the <tt>DataSink</tt> which requests that a keyframe be * requested with a FIR message. * * @return <tt>true</tt> if a keyframe was successfully requested, * <tt>false</tt> otherwise */ private boolean requestFIR(WebmDataSink dataSink) { ReceiveStreamDesc desc = findReceiveStream(dataSink); if (desc != null && rtcpFeedbackSender != null) { return rtcpFeedbackSender.sendFIR((int)desc.ssrc); } return false; } /** * Returns "prefix"+"suffix" if the file with this name does not exist. * Otherwise, returns the first inexistant filename of the form * "prefix-"+i+"suffix", for an integer i. i is bounded by 100 to prevent * hanging, and on failure to find an inexistant filename the method will * return null. * * @param prefix * @param suffix * @return */ private String getNextFilename(String prefix, String suffix) { if (!new File(prefix + suffix).exists()) return prefix + suffix; int i = 1; String s; do { s = prefix + "-" + i + suffix; if (!new File(s).exists()) return s; i++; } while (i < 1000); //don't hang indefinitely... return null; } /** * Finds the <tt>ReceiveStreamDesc</tt> with a particular * <tt>Processor</tt> * @param processor The <tt>Processor</tt> to match. * @return the <tt>ReceiveStreamDesc</tt> with a particular * <tt>Processor</tt>, or <tt>null</tt>. */ private ReceiveStreamDesc findReceiveStream(Processor processor) { if (processor == null) return null; synchronized (receiveStreams) { for (ReceiveStreamDesc r : receiveStreams) if (processor.equals(r.processor)) return r; } return null; } /** * Finds the <tt>ReceiveStreamDesc</tt> with a particular * <tt>DataSink</tt> * @param dataSink The <tt>DataSink</tt> to match. * @return the <tt>ReceiveStreamDesc</tt> with a particular * <tt>DataSink</tt>, or <tt>null</tt>. */ private ReceiveStreamDesc findReceiveStream(DataSink dataSink) { if (dataSink == null) return null; synchronized (receiveStreams) { for (ReceiveStreamDesc r : receiveStreams) if (dataSink.equals(r.dataSink)) return r; } return null; } /** * Finds the <tt>ReceiveStreamDesc</tt> with a particular * SSRC. * @param ssrc The SSRC to match. * @return the <tt>ReceiveStreamDesc</tt> with a particular * SSRC, or <tt>null</tt>. */ private ReceiveStreamDesc findReceiveStream(long ssrc) { synchronized (receiveStreams) { for (ReceiveStreamDesc r : receiveStreams) if (ssrc == r.ssrc) return r; } return null; } /** * Gets the SSRC of a <tt>ReceiveStream</tt> as a (non-negative) * <tt>long</tt>. * * FMJ stores the 32-bit SSRC values in <tt>int</tt>s, and the * <tt>ReceiveStream.getSSRC()</tt> implementation(s) don't take care of * converting the negative <tt>int</tt> values sometimes resulting from * reading of a 32-bit field into the correct unsigned <tt>long</tt> value. * So do the conversion here. * * @param receiveStream the <tt>ReceiveStream</tt> for which to get the SSRC. * @return the SSRC of <tt>receiveStream</tt> an a (non-negative) * <tt>long</tt>. */ private long getReceiveStreamSSRC(ReceiveStream receiveStream) { return 0xffffffffL & receiveStream.getSSRC(); } /** * Implements {@link ActiveSpeakerChangedListener#activeSpeakerChanged(long)}. * Notifies this <tt>RecorderRtpImpl</tt> that the audio * <tt>ReceiveStream</tt> considered active has changed, and that the new * active stream has SSRC <tt>ssrc</tt>. * @param ssrc the SSRC of the new active stream. */ @Override public void activeSpeakerChanged(long ssrc) { if (eventHandler !=null) { RecorderEvent e = new RecorderEvent(); e.setAudioSsrc(ssrc); //TODO: how do we time this? e.setInstant(System.currentTimeMillis()); e.setType(RecorderEvent.Type.SPEAKER_CHANGED); e.setMediaType(MediaType.VIDEO); eventHandler.handleEvent(e); } } private void handleRtpPacket(RawPacket pkt) { if (pkt != null && pkt.getPayloadType() == vp8PayloadType) { int ssrc = pkt.getSSRC(); if (!activeVideoSsrcs.contains(ssrc & 0xffffffffL)) { synchronized (activeVideoSsrcs) { if (!activeVideoSsrcs.contains(ssrc & 0xffffffffL)) { activeVideoSsrcs.add(ssrc & 0xffffffffL); rtcpFeedbackSender.sendFIR(ssrc); } } } } } private void handleRtcpPacket(RawPacket pkt) { getSynchronizer().addRTCPPacket(pkt); eventHandler.nudge(); } public SynchronizerImpl getSynchronizer() { if (synchronizer == null) synchronizer = new SynchronizerImpl(); return synchronizer; } public void setSynchronizer(Synchronizer synchronizer) { if (synchronizer instanceof SynchronizerImpl) { this.synchronizer = (SynchronizerImpl) synchronizer; } } public void connect(Recorder recorder) { if (!(recorder instanceof RecorderRtpImpl)) return; ((RecorderRtpImpl)recorder).setSynchronizer(getSynchronizer()); } private void emptyPacketBuffer(long ssrc) { RawPacket[] pkts = rtpConnector.packetBuffer.emptyBuffer(ssrc); RTPConnectorImpl.OutputDataStreamImpl dataStream; try { dataStream = rtpConnector.getDataOutputStream(); } catch (IOException ioe) { logger.error("Failed to empty packet buffer for SSRC=" + ssrc +": " + ioe); return; } for (RawPacket pkt : pkts) dataStream.write(pkt.getBuffer(), pkt.getOffset(), pkt.getLength(), false /* already transformed */); } /** * The <tt>RTPConnector</tt> implementation used by this * <tt>RecorderRtpImpl</tt>. */ private class RTPConnectorImpl implements RTPConnector { private PushSourceStreamImpl controlInputStream; private OutputDataStreamImpl controlOutputStream; private PushSourceStreamImpl dataInputStream; private OutputDataStreamImpl dataOutputStream; private SourceTransferHandler dataTransferHandler; private SourceTransferHandler controlTransferHandler; private RawPacket pendingDataPacket = new RawPacket(); private RawPacket pendingControlPacket = new RawPacket(); private PacketTransformer rtpPacketTransformer = null; private PacketTransformer rtcpPacketTransformer = null; /** * The PacketBuffer instance which we use as a jitter buffer. */ private PacketBuffer packetBuffer; private RTPConnectorImpl(byte redPT, byte ulpfecPT) { packetBuffer = new PacketBuffer(); // The chain of transformers will be applied in reverse order for // incoming packets. TransformEngine transformEngine = new TransformEngineChain( new TransformEngine[] { packetBuffer, new TransformEngineImpl(), new CompoundPacketEngine(), new FECTransformEngine(ulpfecPT, (byte)-1), new REDTransformEngine(redPT, (byte)-1) }); rtpPacketTransformer = transformEngine.getRTPTransformer(); rtcpPacketTransformer = transformEngine.getRTCPTransformer(); } private RTPConnectorImpl() { } @Override public void close() { try { if (dataOutputStream != null) dataOutputStream.close(); if (controlOutputStream != null) controlOutputStream.close(); } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } } @Override public PushSourceStream getControlInputStream() throws IOException { if (controlInputStream == null) { controlInputStream = new PushSourceStreamImpl(true); } return controlInputStream; } @Override public OutputDataStream getControlOutputStream() throws IOException { if (controlOutputStream == null) { controlOutputStream = new OutputDataStreamImpl(true); } return controlOutputStream; } @Override public PushSourceStream getDataInputStream() throws IOException { if (dataInputStream == null) { dataInputStream = new PushSourceStreamImpl(false); } return dataInputStream; } @Override public OutputDataStreamImpl getDataOutputStream() throws IOException { if (dataOutputStream == null) { dataOutputStream = new OutputDataStreamImpl(false); } return dataOutputStream; } @Override public double getRTCPBandwidthFraction() { return -1; } @Override public double getRTCPSenderBandwidthFraction() { return -1; } @Override public int getReceiveBufferSize() { // TODO Auto-generated method stub return 0; } @Override public int getSendBufferSize() { // TODO Auto-generated method stub return 0; } @Override public void setReceiveBufferSize(int arg0) throws IOException { // TODO Auto-generated method stub } @Override public void setSendBufferSize(int arg0) throws IOException { // TODO Auto-generated method stub } private class OutputDataStreamImpl implements OutputDataStream { boolean isControlStream; private RawPacket[] rawPacketArray = new RawPacket[1]; public OutputDataStreamImpl(boolean isControlStream) { this.isControlStream = isControlStream; } public synchronized int write(byte[] buffer, int offset, int length) { return write(buffer, offset, length, true); } public synchronized int write(byte[] buffer, int offset, int length, boolean transform) { RawPacket pkt = rawPacketArray[0]; if (pkt == null) pkt = new RawPacket(); rawPacketArray[0] = pkt; byte[] pktBuf = pkt.getBuffer(); if (pktBuf == null || pktBuf.length < length) { pktBuf = new byte[length]; pkt.setBuffer(pktBuf); } System.arraycopy(buffer, offset, pktBuf, 0, length); pkt.setOffset(0); pkt.setLength(length); if (transform) { PacketTransformer packetTransformer = isControlStream ? rtcpPacketTransformer : rtpPacketTransformer; if (packetTransformer != null) rawPacketArray = packetTransformer.reverseTransform(rawPacketArray); } SourceTransferHandler transferHandler; PushSourceStream pushSourceStream; try { if (isControlStream) { transferHandler = controlTransferHandler; pushSourceStream = getControlInputStream(); } else { transferHandler = dataTransferHandler; pushSourceStream = getDataInputStream(); } } catch (IOException ioe) { throw new UndeclaredThrowableException(ioe); } for (int i = 0; i < rawPacketArray.length; i++) { RawPacket packet = rawPacketArray[i]; //keep the first element for reuse if (i != 0) rawPacketArray[i] = null; if (packet != null) { if (isControlStream) pendingControlPacket = packet; else pendingDataPacket = packet; if (transferHandler != null) { transferHandler.transferData(pushSourceStream); } } } return length; } public void close() throws IOException { } } /** * A dummy implementation of {@link PushSourceStream}. * @author Vladimir Marinov */ private class PushSourceStreamImpl implements PushSourceStream { private boolean isControlStream = false; public PushSourceStreamImpl(boolean isControlStream) { this.isControlStream = isControlStream; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public boolean endOfStream() { return false; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public ContentDescriptor getContentDescriptor() { return null; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public long getContentLength() { return 0; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public Object getControl(String arg0) { return null; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public Object[] getControls() { return null; } /** * Not implemented because there are currently no uses of the underlying * functionality. */ @Override public int getMinimumTransferSize() { if (isControlStream) { if (pendingControlPacket.getBuffer() != null) { return pendingControlPacket.getLength(); } } else { if (pendingDataPacket.getBuffer() != null) { return pendingDataPacket.getLength(); } } return 0; } @Override public int read(byte[] buffer, int offset, int length) throws IOException { RawPacket pendingPacket; if (isControlStream) { pendingPacket = pendingControlPacket; } else { pendingPacket = pendingDataPacket; } int bytesToRead = 0; byte[] pendingPacketBuffer = pendingPacket.getBuffer(); if (pendingPacketBuffer != null) { int pendingPacketLength = pendingPacket.getLength(); bytesToRead = length > pendingPacketLength ? pendingPacketLength: length; System.arraycopy( pendingPacketBuffer, pendingPacket.getOffset(), buffer, offset, bytesToRead); } return bytesToRead; } /** * {@inheritDoc} * * We keep the first non-null <tt>SourceTransferHandler</tt> that * was set, because we don't want it to be overwritten when we * initialize a second <tt>RTPManager</tt> with this * <tt>RTPConnector</tt>. * * See {@link RecorderRtpImpl#start(String, String)} */ @Override public void setTransferHandler( SourceTransferHandler transferHandler) { if (isControlStream) { if (RTPConnectorImpl.this.controlTransferHandler == null) { RTPConnectorImpl.this. controlTransferHandler = transferHandler; } } else { if (RTPConnectorImpl.this.dataTransferHandler == null) { RTPConnectorImpl.this. dataTransferHandler = transferHandler; } } } } /** * A transform engine implementation which allows * <tt>RecorderRtpImpl</tt> to intercept RTP and RTCP packets in. */ private class TransformEngineImpl implements TransformEngine { SinglePacketTransformer rtpTransformer = new SinglePacketTransformer() { @Override public RawPacket transform(RawPacket pkt) { return pkt; } @Override public RawPacket reverseTransform(RawPacket pkt) { RecorderRtpImpl.this.handleRtpPacket(pkt); return pkt; } @Override public void close() { } }; SinglePacketTransformer rtcpTransformer = new SinglePacketTransformer() { @Override public RawPacket transform(RawPacket pkt) { return pkt; } @Override public RawPacket reverseTransform(RawPacket pkt) { RecorderRtpImpl.this.handleRtcpPacket(pkt); if (pkt != null && pkt.getRTCPPacketType() == 203) { // An RTCP BYE packet. Remove the receive stream before // it gets to FMJ, because we want to, for example, // flush the packet buffer before that. long ssrc = pkt.getRTCPSSRC() & 0xffffffffl; if (logger.isInfoEnabled()) logger.info("RTCP BYE for SSRC="+ssrc); ReceiveStreamDesc receiveStream = findReceiveStream(ssrc); if (receiveStream != null) removeReceiveStream(receiveStream, false); } return pkt; } @Override public void close() { } }; @Override public PacketTransformer getRTPTransformer() { return rtpTransformer; } @Override public PacketTransformer getRTCPTransformer() { return rtcpTransformer; } } } private class RecorderEventHandlerImpl implements RecorderEventHandler { private RecorderEventHandler handler; private final Set<RecorderEvent> pendingEvents = new HashSet<RecorderEvent>(); private RecorderEventHandlerImpl(RecorderEventHandler handler) { this.handler = handler; } @Override public boolean handleEvent(RecorderEvent ev) { if (ev == null) return true; if (RecorderEvent.Type.RECORDING_STARTED.equals(ev.getType())) { long instant = getSynchronizer().getLocalTime(ev.getSsrc(), ev.getRtpTimestamp()); if (instant != -1) { ev.setInstant(instant); return handler.handleEvent(ev); } else { pendingEvents.add(ev); return true; } } return handler.handleEvent(ev); } private void nudge() { for(Iterator<RecorderEvent> iter = pendingEvents.iterator(); iter.hasNext();) { RecorderEvent ev = iter.next(); long instant = getSynchronizer().getLocalTime(ev.getSsrc(), ev.getRtpTimestamp()); if (instant != -1) { iter.remove(); ev.setInstant(instant); handler.handleEvent(ev); } } } @Override public void close() { for (RecorderEvent ev : pendingEvents) handler.handleEvent(ev); } } /** * Represents a <tt>ReceiveStream</tt> for the purposes of this * <tt>RecorderRtpImpl</tt>. */ private class ReceiveStreamDesc { /** * The actual <tt>ReceiveStream</tt> which is represented by this * <tt>ReceiveStreamDesc</tt>. */ private ReceiveStream receiveStream; /** * The SSRC of the stream. */ long ssrc; /** * The <tt>Processor</tt> used to transcode this receive stream into a * format appropriate for saving to a file. */ private Processor processor; /** * The <tt>DataSink</tt> which saves the <tt>this.dataSource</tt> to a * file. */ private DataSink dataSink; /** * The <tt>DataSource</tt> for this receive stream which is to be saved * using a <tt>DataSink</tt> (i.e. the <tt>DataSource</tt> "after" all * needed transcoding is done). */ private DataSource dataSource; /** * The name of the file into which this stream is being saved. */ private String filename; /** * The (original) format of this receive stream. */ private Format format; /** * The <tt>SilenceEffect</tt> used for this stream (for audio streams * only). */ private SilenceEffect silenceEffect; private ReceiveStreamDesc(ReceiveStream receiveStream) { this.receiveStream = receiveStream; this.ssrc = getReceiveStreamSSRC(receiveStream); } } }
package org.spongepowered.api.item.inventory; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.tileentity.TileEntity; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataSerializable; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.manipulator.DataManipulator; import org.spongepowered.api.data.manipulator.ImmutableDataManipulator; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.text.translation.Translatable; import org.spongepowered.api.util.ResettableBuilder; /** * Represents a stack of a specific {@link ItemType}. Supports serialization and * can be compared using the comparators listed in {@link ItemStackComparators}. * * <p>{@link ItemStack}s have varying properties and data, it is adviseable to * use {@link DataHolder#get(Class)} to retrieve different information * regarding this item stack.</p> */ public interface ItemStack extends DataHolder, DataSerializable, Translatable { /** * Creates a new {@link Builder} to build an {@link ItemStack}. * * @return The new builder */ static Builder builder() { return Sponge.getRegistry().createBuilder(Builder.class); } /** * Creates a new {@link ItemStack} of the provided {@link ItemType} * and quantity. * * @param itemType The item type * @param quantity The quantity * @return The new item stack */ static ItemStack of(ItemType itemType, int quantity) { return builder().itemType(itemType).quantity(quantity).build(); } /** * Gets the {@link ItemType} of this {@link ItemStack}. * * @return The item type */ ItemType getItem(); /** * Gets the quantity of items in this stack. This may exceed the max stack * size of the item, and if added to an inventory will then be divided by * the max stack. * * @return Quantity of items */ int getQuantity(); void setQuantity(int quantity) throws IllegalArgumentException; /** * Get the maximum quantity per stack. By default, returns * {@link ItemType#getMaxStackQuantity()}, unless a * different value has been set for this specific stack. * * @return Max stack quantity */ int getMaxStackQuantity(); /** * Gets the {@link ItemStackSnapshot} of this {@link ItemStack}. All known * {@link DataManipulator}s existing on this {@link ItemStack} are added * as copies to the {@link ItemStackSnapshot}. * * @return The newly created item stack snapshot */ ItemStackSnapshot createSnapshot(); @Override ItemStack copy(); interface Builder extends ResettableBuilder<ItemStack, Builder> { /** * Sets the {@link ItemType} of the item stack. * * @param itemType The type of item * @return This builder, for chaining */ Builder itemType(ItemType itemType); Builder quantity(int quantity) throws IllegalArgumentException; /** * Adds a {@link Key} and related {@link Object} value to apply to the * resulting {@link ItemStack}. Note that the resulting * {@link ItemStack} may not actually accept the provided {@code Key} * for various reasons due to support or simply that the value itself * is not supported. Offering custom data is not supported through this, * use {@link #itemData(DataManipulator)} instead. * * @param key The key to identiy the value to * @param value The value to apply * @param <E> The type of value * @return This builder, for chaining */ <E> Builder keyValue(Key<? extends BaseValue<E>> key, E value); Builder itemData(DataManipulator<?, ?> itemData) throws IllegalArgumentException; Builder itemData(ImmutableDataManipulator<?, ?> itemData) throws IllegalArgumentException; <V> Builder add(Key<? extends BaseValue<V>> key, V value) throws IllegalArgumentException; /** * Sets all the settings in this builder from the item stack blueprint. * * @param itemStack The item stack to copy * @return This builder, for chaining */ Builder fromItemStack(ItemStack itemStack); /** * Sets the data to recreate a {@link BlockState} in a held {@link ItemStack} * state. * * @param blockState The block state to use * @return This builder, for chaining */ default Builder fromBlockState(BlockState blockState) { checkNotNull(blockState); final BlockType blockType= blockState.getType(); checkArgument(blockType.getItem().isPresent(), "Missing valid ItemType for BlockType: " + blockType.getId()); itemType(blockType.getItem().get()); blockState.getContainers().forEach(this::itemData); return this; } /** * Attempts to reconstruct the builder with all of the data from * {@link ItemStack#toContainer()} including all custom data. * * @param container The container to deserialize * @return This bulder, for chaining */ Builder fromContainer(DataView container); /** * Reconstructs this builder to use the {@link ItemStackSnapshot} * for all the values and data it may contain. * * @param snapshot The snapshot * @return This builder, for chaining */ default Builder fromSnapshot(ItemStackSnapshot snapshot) { return fromItemStack(snapshot.createStack()); } /** * Attempts to reconstruct a {@link BlockSnapshot} including all data * and {@link TileEntity} related data if necessary for creating an * {@link ItemStack} representation. * * @param blockSnapshot The snapshot to use * @return This builder, for chaining */ Builder fromBlockSnapshot(BlockSnapshot blockSnapshot); ItemStack build() throws IllegalStateException; } }
package org.jitsi.recording.postprocessing; import java.io.*; import java.util.*; import java.util.List; //Disambiguation import java.util.concurrent.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.recording.*; import org.jitsi.service.neomedia.recording.RecorderEvent.*; import org.jitsi.recording.postprocessing.section.*; import org.jitsi.recording.postprocessing.util.*; import org.jitsi.recording.postprocessing.video.concat.*; import org.jitsi.recording.postprocessing.layout.*; import org.jitsi.recording.postprocessing.participant.*; import org.json.simple.*; /** * A unit that processes videos recorded by the video recorder. It reads a * metadata file, and the audio and video files described in it, and produces * a single combined file. * * @author Vladimir Marinov * @author Boris Grozev */ public class PostProcessing { /** * Duration of a single video frame. */ private static final int SINGLE_FRAME_DURATION = 1000 / Config.OUTPUT_FPS; /** * The minimum duration that a section can have (the difference between * two consecutive event instants) in order for it to get processed. */ private static final int MINIMUM_SECTION_DURATION = 50; /** * The length of video trimming result is usually bigger than the section * we wanted to get. This leads to error accumulation that we store in * this variable in order to later compensate it */ private static int videoDurationError = 0; /** * We need to fade in only videos of participants that join the call * after the recording has started. */ private static boolean hasProcessedEvents = false; /** * A list of participants that are currently shown. * */ private static List<ParticipantInfo> activeParticipants; /** * An instance that determines how the active participants should be * placed in the output video. */ private static final LayoutStrategy layoutStrategy = new SmallVideosOverLargeVideoLayoutStrategy(); /** * An instance that takes care of concatenating the video files that are * stored in a specific directory. */ private static final ConcatStrategy concatStrategy = new SimpleConcatStrategy(); /** * An instance that determines which participants are currently active * and what is their order in the list of small videos */ private static ActiveParticipantsManager activeParticipantsManager = new WithSpeakerInVideosListParticipantsManager(); /** * A task queue responsible for decoding the input video files into MJPEG * files. */ private static ExecutorService decodingTaskQueue = Executors.newFixedThreadPool(Config.JIPOPRO_THREADS); /** * A task queue responsible for processing the separate call sections. */ private static ExecutorService sectionProcessingTaskQueue = Executors.newFixedThreadPool(Config.JIPOPRO_THREADS); /** * The time processing has started. */ private static long processingStarted; private static String inDir; private static String outDir; private static String resourcesDir; private static long lastTime = -1; private static List<String> timings = new LinkedList<String>(); public static void main(String[] args) throws IOException, InterruptedException { inDir = new java.io.File( "." ).getCanonicalPath() + "/"; outDir = inDir; resourcesDir = inDir; for (String arg : args) { if (arg.startsWith(Config.IN_ARG_NAME)) inDir = arg.substring(Config.IN_ARG_NAME.length()) + "/"; else if (arg.startsWith(Config.OUT_ARG_NAME)) outDir = arg.substring(Config.OUT_ARG_NAME.length()) + "/"; else if (arg.startsWith(Config.RESOURCES_ARG_NAME)) resourcesDir = arg.substring(Config.RESOURCES_ARG_NAME.length()) + "/"; } log("Input directory: " + inDir); log("Output directory: " + outDir); log("Resources directory: " + resourcesDir); processingStarted = System.currentTimeMillis(); initLogFile(); if (!sanityCheck()) return; layoutStrategy.initialize(Config.OUTPUT_WIDTH, Config.OUTPUT_HEIGHT); int sectionNumber = 0; int eventInstant = 0; int lastEventInstant = 0; int firstVideoStartInstant = -1; // Read the metadata file. JSONObject metadataJSONObject = null; Scanner scanner = new Scanner(new File(inDir + Config.METADATA_FILENAME)); String metadataString = scanner.useDelimiter("\\Z").next(); scanner.close(); metadataJSONObject = (JSONObject) JSONValue.parse(metadataString); if (metadataJSONObject == null) { log("Failed to parse metadata from " + inDir + Config.METADATA_FILENAME + ". Broken json?"); return; } List<RecorderEvent> videoEvents = extractEvents(metadataJSONObject, MediaType.VIDEO); if (videoEvents == null) { return; //error already logged } time("Extracting video events (calculating durations)"); for(RecorderEvent e: videoEvents) { System.err.println("aaaa "+e.getInstant()+" "+e.getType()+" "+e.getSsrc()); } // Decode videos decodeParticipantVideos(videoEvents); time("Decoding videos"); // And now the magic begins :) long firstVideoStartInstantLong = -1; for (RecorderEvent event : videoEvents) { int instant = (int) event.getInstant(); //XXX Boris this is bound to lead to problems (or at least make // debugging harder). Please keep SSRCs in long-s. int ssrc = (int) event.getSsrc(); if (event.getType() != RecorderEvent.Type.RECORDING_STARTED && firstVideoStartInstant == -1) { continue; } if (firstVideoStartInstant == -1) { firstVideoStartInstant = instant; firstVideoStartInstantLong = event.getInstant(); } eventInstant = instant - firstVideoStartInstant; //Once we read an event from the metadata file we process the videos // files from the previous event instant to the current event // instant if (eventInstant != 0 && eventInstant - lastEventInstant >= MINIMUM_SECTION_DURATION) { System.err.println("Processing event: " + event); //processLastEvent(eventInstant, lastEventInstant); SectionDescription sectionDesc = new SectionDescription(); sectionDesc.activeParticipants = activeParticipants; layoutStrategy.calculateDimensions(activeParticipants); sectionDesc.largeVideoDimension = layoutStrategy.getLargeVideoDimensions(); sectionDesc.smallVideosDimensions = layoutStrategy.getSmallVideosDimensions(); sectionDesc.smallVideosPositions = layoutStrategy.getSmallVideosPositions(); sectionDesc.sequenceNumber = sectionNumber; sectionDesc.startInstant = lastEventInstant; videoDurationError += (eventInstant - lastEventInstant) % SINGLE_FRAME_DURATION; int sectionDurationCorrection = 0; if (videoDurationError > SINGLE_FRAME_DURATION) { sectionDurationCorrection = -SINGLE_FRAME_DURATION; videoDurationError -= SINGLE_FRAME_DURATION; } sectionDesc.endInstant = eventInstant; //+ sectionDurationCorrection; sectionProcessingTaskQueue.execute( new SectionProcessingTask(sectionDesc, outDir, resourcesDir)); sectionNumber++; hasProcessedEvents = true; lastEventInstant = eventInstant; } else if (eventInstant - lastEventInstant < MINIMUM_SECTION_DURATION) { System.err.println("Ignoring an event because it's too close" + "to the previous: " + event.getType() + ", " + event.getSsrc() + " " + event); } switch (event.getType()) { case RECORDING_STARTED: int newParticipantSSRC = ssrc; ParticipantInfo participant = new ParticipantInfo(newParticipantSSRC); participant.currentVideoFileStartInstant = eventInstant; participant.lastActiveInstant = eventInstant; //Needs refactoring participant.aspectRatio = event.getAspectRatio() == AspectRatio.ASPECT_RATIO_16_9 ? AspectRatioUtil.ASPECT_RATIO_16_9 : AspectRatioUtil.ASPECT_RATIO_4_3; participant.fileName = inDir + event.getFilename(); participant.decodedFilename = outDir + Utils.trimFileExtension(event.getFilename()) + ".mov"; participant.username = event.getParticipantName(); //XXX Boris: if an event doesn't have a participantName //it now returns null instead of "". This should probably be //fixed somewhere else (participant.setUsername()?) if (participant.username == null) participant.username = ""; participant.description = event.getParticipantDescription(); if (participant.description == null) participant.description = ""; participant.disableOtherVideosOnTop = event.getDisableOtherVideosOnTop(); activeParticipantsManager.addParticipant(participant); break; case RECORDING_ENDED: int participantToRemove = ssrc; activeParticipantsManager. removeParticipant(participantToRemove); break; case SPEAKER_CHANGED: int speakerSSRC = ssrc; activeParticipantsManager. speakerChange(speakerSSRC, eventInstant); break; case OTHER: return; } activeParticipants = activeParticipantsManager.getActiveParticipantsList(); removeSmallVideosIfDisabled(); if (activeParticipants == null || activeParticipants.size() == 0) { break; //video all done. } } sectionProcessingTaskQueue.shutdown(); try { sectionProcessingTaskQueue.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS); time("Processing sections"); } catch (InterruptedException e) { log("Failed to process sections: "+e); e.printStackTrace(); //should we continue? } /* * XXX we concatenate the sections and encode the video in one step, * because it is more efficient. We ignore the Config.OUTPUT_FORMAT * setting and have hard-coded webm settings in SimpleConcatStrategy. */ String videoFilename = outDir + "output.webm"; concatStrategy.concatFiles(outDir+"sections", videoFilename); time("Concatenating sections and encode video"); Exec.exec("rm -rf " + outDir + "sections"); // Handle audio List<RecorderEvent> audioEvents = extractEvents(metadataJSONObject, MediaType.AUDIO); if (audioEvents == null) return; //error already logged String audioMix = outDir + "resultAudio.wav"; long firstAudioInstant = mixAudio(audioEvents, audioMix); time("Mixing audio"); long audioOffset = 0, videoOffset = 0; long diff = firstAudioInstant - firstVideoStartInstantLong; if (diff > 0) audioOffset = diff; else if (diff < 0) videoOffset = -diff; merge(audioMix, audioOffset, videoFilename, videoOffset, videoFilename); time("Merging audio and video"); // XXX encoding is now done during concatenation //String finalResult = encodeResultVideo(videoFilename); //time("Encoding final result"); for (String s : timings) log(s); log("All done, result saved in " + videoFilename + ". And it took only " + Utils.millisToSeconds(System.currentTimeMillis() - processingStarted) + " seconds."); Exec.closeLogFile(); } private static void time(String s) { long lastTime; if (timings.isEmpty()) lastTime = processingStarted; else lastTime = PostProcessing.lastTime; long now = System.currentTimeMillis(); PostProcessing.lastTime = now; timings.add("[TIME] " + s + ": " + Utils.millisToSeconds(now - lastTime)); } /** * Merges and audio and video file, using the given offsets. * @param audioFilename the name of the audio file. * @param audioStartOffset the offset at which audio should start in the * merged file. * @param videoFilename the name of the video file. * @param videoStartOffset the offset at which video should start in the * merged file. * @param outputFilename the name of the file where the result should be * stored. * @throws InterruptedException * @throws IOException */ private static void merge(String audioFilename, long audioStartOffset, String videoFilename, long videoStartOffset, String outputFilename) throws InterruptedException, IOException { Exec.exec(Config.FFMPEG + " -y" + " -itsoffset " + Utils.millisToSeconds(videoStartOffset) + " -i " + videoFilename + " -itsoffset " + Utils.millisToSeconds(audioStartOffset) + " -i " + audioFilename + " -vcodec copy " + outDir + "temp.webm"); //Exec.exec("mv " + videoFilename + " output-no-sound.mov"); //keep for debugging // use temp.mov to allow videoFilename == outputFilename Exec.exec("mv " + outDir + "temp.webm " + outputFilename); } /** * Mixes the audio according the the events in <tt>audioEvents</tt> * @param audioEvents the list of audio events. * @param outputFilename the name of the file where to store the mix. * @return the instant of the first event which is included in the mix. * @throws InterruptedException * @throws IOException */ private static long mixAudio(List<RecorderEvent> audioEvents, String outputFilename) throws InterruptedException, IOException { long nextAudioFileInstant; long firstAudioFileInstant = 0; String[] filenames = new String[audioEvents.size()]; long[] padding = new long[audioEvents.size()]; int i = 0; for (RecorderEvent event : audioEvents) { nextAudioFileInstant = event.getInstant(); if (event.getType() == Type.RECORDING_STARTED) { // workaround a current problem with the recorder which leaves // empty files. also, sox chokes on small files int minAudioFileSize = 4000; File file = new File(inDir + event.getFilename()); if (!file.exists() || file.length() < minAudioFileSize) continue; if (i == 0) { firstAudioFileInstant = nextAudioFileInstant; } else { padding[i] = nextAudioFileInstant - firstAudioFileInstant; } filenames[i] = inDir + event.getFilename(); i++; } } Exec.exec("mkdir -p " + outDir + "audio_tmp"); // the first file is just converted to wav Exec.exec("sox " + filenames[0] + " " + outDir + "audio_tmp/padded0.wav"); // TODO in threads // the rest need padding for (int j = 1; j < i; j++) Exec.exec("sox " + filenames[j] + " " + outDir + "audio_tmp/padded" + j + ".wav pad " + Utils.millisToSeconds(padding[j])); String exec = "sox --combine mix-power "; for (int j = 0; j < i; j++) exec += outDir + "audio_tmp/padded" + j + ".wav "; exec += outputFilename; Exec.exec(exec); Exec.exec("rm -rf " + outDir + "audio_tmp"); return firstAudioFileInstant; } /** * Extracts a list of <tt>RecorderEvent</tt> with a specific media type * from JSON format. * @param json the JSON object containing all events in the recorder * metadata format. * @param mediaType the media type specifying which events to extract. * @return A list of <tt>RecorderEvent</tt>, ordered by "instant". */ private static List<RecorderEvent> extractEvents(JSONObject json, MediaType mediaType) { Object array = json.get(mediaType.toString()); if (array == null || !(array instanceof JSONArray)) { log("Failed to extract events from metadata, mediaType=" + mediaType + "; json:\n" +json.toJSONString()); return null; } List<RecorderEvent> eventList = new LinkedList<RecorderEvent>(); for (Object o : (JSONArray) array) { RecorderEvent event = new RecorderEvent((JSONObject) o); MediaType eventMediaType = event.getMediaType(); Type eventType = event.getType(); // For video, we generate RECORDING_ENDED events on our own, based // on the actual length of the video files. if (MediaType.VIDEO.equals(eventMediaType)) { if (Type.RECORDING_ENDED.equals(eventType)) continue; else if (Type.RECORDING_STARTED.equals(eventType)) { //Insert a RECORDING_ENDED event for this file try { long duration = getVideoDurationMillis(event.getFilename()); if (duration == -1) { // Failed to calculate the duration of the video. // Drop the RECORDING_STARTED event as well log("Failed to calculate video duration for " + event.getFilename() + ". Ignoring " + "the file"); continue; } RecorderEvent newEndedEvent = new RecorderEvent(); newEndedEvent.setType(Type.RECORDING_ENDED); newEndedEvent.setInstant(event.getInstant() + duration); newEndedEvent.setMediaType(MediaType.VIDEO); newEndedEvent.setSsrc(event.getSsrc()); newEndedEvent.setFilename(event.getFilename()); eventList.add(newEndedEvent); } catch (Exception e) { log("Failed to insert RECORDING_ENDED event: " + e); return null; // is it safe to continue here? } } } eventList.add(event); } Collections.sort(eventList, new Comparator<RecorderEvent>() { @Override public int compare(RecorderEvent o1, RecorderEvent o2) { return (int) (o1.getInstant() - o2.getInstant()); } }); return eventList; } /** * Logs a message. * @param s the message to log. */ private static void log(String s) { System.err.println(s); } /** * Extracts duration of a video file using ffprobe * @return the duration of the webm file <tt>filename</tt> in milliseconds. * @param filename the video file which duration is about to be extracted * @throws InterruptedException * @throws IOException */ private static long getVideoDurationMillis(String filename) throws IOException, InterruptedException { long videoDuration = 0; if (Config.USE_MKVINFO) { String exec = "mkvinfo -v -s " + filename + " | tail -n 1 | awk '{print $6;}'"; Process p = Runtime.getRuntime(). exec(new String[] { "bash", "-c", exec }); int ret = p.waitFor(); if (ret != 0) { log("Failed to extract file duration for " + filename); return -1; } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); videoDuration = Integer.parseInt(reader.readLine()); } else { String videoInfoFilename = outDir + "video_info.txt"; //note: this is slow String exec = "ffprobe -v quiet -print_format json=c=1 -show_frames " + filename + " | tail -n 3 | head -n 1 | tee " + videoInfoFilename; Exec.execArray(new String[] { "bash", "-c", exec }); try { JSONObject videoInfo = (JSONObject) JSONValue.parse(new FileReader(videoInfoFilename)); videoDuration = (Long) videoInfo.get("pkt_pts"); } catch (FileNotFoundException e) { e.printStackTrace(); } } return videoDuration; } /** * Prevent small videos from showing */ private static void removeSmallVideosIfDisabled() { for (ParticipantInfo participant : activeParticipants) { if (participant.isCurrentlySpeaking && participant.disableOtherVideosOnTop) { activeParticipants = new ArrayList<ParticipantInfo>(); activeParticipants.add(participant); break; } } } /** Encodes the result video in the chosen file format * @throws InterruptedException * @throws IOException */ private static String encodeResultVideo(String inputFilename) throws IOException, InterruptedException { String outputFilename = Utils.trimFileExtension(inputFilename); if (Config.OUTPUT_FORMAT == Config.WEBM_OUTPUT_FORMAT) { outputFilename += ".webm"; Exec.exec(Config.FFMPEG + " -y -i " + inputFilename + " -c:v libvpx " + "-cpu-used " + Config.FFMPEG_CPU_USED + " -threads " + Config.FFMPEG_THREADS + " -b:v 1M " + outputFilename); return outputFilename; } else if (Config.OUTPUT_FORMAT == Config.MP4_OUTPUT_FORMAT) { outputFilename += ".mp4"; Exec.exec(Config.FFMPEG + " -y -i " + inputFilename + " -vcodec " + "libx264 " + "-acodec copy " + outputFilename); return outputFilename; } return null; } /** Decodes an input video file and encodes it using MJPEG */ private static void decodeParticipantVideoFile(String participantFileName) throws IOException, InterruptedException { String fadeFilter = ""; if (hasProcessedEvents) { fadeFilter = "-vf fade=in:st=0:d=1:color=black "; } Exec.exec( Config.FFMPEG + " -y -vcodec libvpx -i " + inDir + participantFileName + " -vcodec mjpeg -cpu-used " + Config.FFMPEG_CPU_USED //+ " -threads " + Config.FFMPEG_THREADS + " -an -q:v " + Config.QUALITY_LEVEL + " " + "-r " + Config.OUTPUT_FPS + " " + fadeFilter + outDir + Utils.trimFileExtension(participantFileName) + ".mov"); } private static void decodeParticipantVideos(List<RecorderEvent> videoEvents) { for (RecorderEvent event : videoEvents) { if (event.getType() == Type.RECORDING_STARTED) { final String filename = event.getFilename(); decodingTaskQueue.execute(new Runnable() { @Override public void run() { try { decodeParticipantVideoFile(filename); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } decodingTaskQueue.shutdown(); try { decodingTaskQueue.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { log("Faied to decode participant videos: " + e); e.printStackTrace(); } } /** Perform some initial tests and fail early if they fail. */ private static boolean sanityCheck() { Runtime runtime = Runtime.getRuntime(); Process p; int ret; try { /* p = runtime.exec("which phantomjs"); ret = p.waitFor(); if (ret != 0) { System.err.println("Cannot find 'phantomjs' executable."); return false; } */ p = runtime.exec("which " + Config.FFMPEG); ret = p.waitFor(); if (ret != 0) { System.err.println("Cannot find 'ffmpeg' executable."); return false; } BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String ffmpeg = reader.readLine(); System.err.println("Using ffmpeg: " + ffmpeg); } catch (Exception e) { e.printStackTrace(); return false; } if (!new File(inDir + Config.METADATA_FILENAME).exists()) { System.err.println("Metadata file " + inDir + Config.METADATA_FILENAME + " does not exist."); return false; } return true; } private static void initLogFile() { File logFile = new File(outDir + Config.LOG_FILENAME); boolean fail = false; Exception e = null; try { if (!logFile.exists()) logFile.createNewFile(); } catch (IOException ioe) { fail = true; e = ioe; } if (!logFile.canWrite()) fail = true; if (fail) { System.err.println("Could not open log file for writing." + " Continuing without a log file.\n" + (e == null ? "" : e)); } else { Exec.setLogFile(logFile); } } }
package org.netmelody.cieye.server.observation; import static com.google.common.collect.Lists.newArrayList; import static java.lang.System.currentTimeMillis; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.netmelody.cieye.core.domain.Feature; import org.netmelody.cieye.core.domain.Target; import org.netmelody.cieye.core.domain.TargetGroup; import org.netmelody.cieye.core.observation.CiSpy; import org.netmelody.cieye.server.CiSpyHandler; import com.google.common.collect.MapMaker; public final class PollingSpy implements CiSpyHandler { private static final long POLLING_PERIOD_SECONDS = 5L; private final CiSpy delegate; private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private final ConcurrentMap<Feature, Long> trackedFeatures = new MapMaker() .expireAfterWrite(10, TimeUnit.MINUTES) .makeMap(); private final ConcurrentMap<Feature, StatusResult> statuses = new MapMaker().makeMap(); public PollingSpy(CiSpy delegate) { this.delegate = delegate; executor.scheduleWithFixedDelay(new StatusUpdater(), 0L, POLLING_PERIOD_SECONDS, TimeUnit.SECONDS); } @Override public TargetGroup statusOf(Feature feature) { final long currentTimeMillis = currentTimeMillis(); trackedFeatures.put(feature, currentTimeMillis); final StatusResult result = statuses.get(feature); if (null != result) { return result.status(); } final TargetGroup digest = new TargetGroup(delegate.targetsConstituting(feature)); statuses.putIfAbsent(feature, new StatusResult(digest, currentTimeMillis)); return digest; } @Override public long millisecondsUntilNextUpdate(Feature feature) { final StatusResult statusResult = statuses.get(feature); if (null != statusResult) { return Math.max(0L, (POLLING_PERIOD_SECONDS * 1000L) - (currentTimeMillis() - statusResult.timestamp)); } return 0L; } @Override public boolean takeNoteOf(String targetId, String note) { return delegate.takeNoteOf(targetId, note); } private void update() { for (Feature feature : trackedFeatures.keySet()) { StatusResult intermediateStatus = statuses.putIfAbsent(feature, new StatusResult()); if (null == intermediateStatus) { intermediateStatus = new StatusResult(); } final TargetGroup snapshot = delegate.statusOf(feature); final List<Target> newStatus = newArrayList(); for (Target target : snapshot) { newStatus.add(target); intermediateStatus = intermediateStatus.updatedWith(target); statuses.put(feature, intermediateStatus); } statuses.put(feature, new StatusResult(newStatus, currentTimeMillis())); } } private static final class StatusResult { private final Iterable<Target> targets; public final long timestamp; public StatusResult() { this(new ArrayList<Target>(), currentTimeMillis()); } public StatusResult(Iterable<Target> targets, long timestamp) { this.targets = targets; this.timestamp = timestamp; } public TargetGroup status() { return new TargetGroup(targets); } public StatusResult updatedWith(Target target) { final List<Target> newStatus = newArrayList(targets); Iterator<Target> iterator = newStatus.iterator(); while (iterator.hasNext()) { if(iterator.next().id().equals(target.id())) { iterator.remove(); break; } } newStatus.add(target); return new StatusResult(newStatus, timestamp); } } private final class StatusUpdater implements Runnable { @Override public void run() { update(); } } }
package programminglife.gui.controller; import javafx.geometry.Bounds; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Text; import programminglife.gui.ResizableCanvas; import programminglife.model.GenomeGraph; import programminglife.model.XYCoordinate; import programminglife.model.drawing.*; import programminglife.utility.Console; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; public class GraphController { private GenomeGraph graph; private double locationCenterY; private double locationCenterX; private LinkedList<DrawableNode> oldMinMaxList = new LinkedList<>(); private SubGraph subGraph; private AnchorPane anchorGraphInfo; private LinkedList<DrawableNode> oldGenomeList = new LinkedList<>(); private HashMap<DrawableEdge, Line> edgeLocation = new HashMap<>(); private ResizableCanvas canvas; private double zoomLevel = 1; private int centerNodeInt; /** * Initialize controller object. * @param graph The genome graph to control * @param canvas the {@link Canvas} to draw in * @param anchorGraphInfo the {@link AnchorPane} were to show the info of a node or edge. */ public GraphController(GenomeGraph graph, ResizableCanvas canvas, AnchorPane anchorGraphInfo) { this.graph = graph; this.canvas = canvas; this.anchorGraphInfo = anchorGraphInfo; } public int getCenterNodeInt() { return this.centerNodeInt; } /** * Method to draw the subGraph decided by a center node and radius. * @param center the node of which the radius starts. * @param radius the amount of layers to be drawn. */ public void draw(int center, int radius) { long startTimeProgram = System.nanoTime(); GraphicsContext gc = canvas.getGraphicsContext2D(); long startTimeSubGraph = System.nanoTime(); DrawableSegment centerNode = new DrawableSegment(graph, center); centerNodeInt = centerNode.getIdentifier(); subGraph = new SubGraph(centerNode, radius); long finishTimeSubGraph = System.nanoTime(); long startLayoutTime = System.nanoTime(); subGraph.layout(); long finishTimeLayout = System.nanoTime(); long startTimeColorize = System.nanoTime(); colorize(); long finishTimeColorize = System.nanoTime(); long startTimeDrawing = System.nanoTime(); draw(gc); long finishTimeDrawing = System.nanoTime(); // long startHighlight = System.nanoTime(); highlightNode(center, Color.DARKORANGE); centerOnNodeId(center); System.out.println(this.subGraph.getNodes().get(center).getLocation()); // Console.println("Time to highlight: " + (System.nanoTime() - startHighlight) / 1000000 + " ms"); long finishTime = System.nanoTime(); long differenceTimeProgram = finishTime - startTimeProgram; long differenceTimeDrawing = finishTimeDrawing - startTimeDrawing; long differenceTimeLayout = finishTimeLayout - startLayoutTime; long differenceTimeSubGraph = finishTimeSubGraph - startTimeSubGraph; long differenceTimeColorize = finishTimeColorize - startTimeColorize; long msDifferenceTimeProgram = differenceTimeProgram / 1000000; long millisecondTimeDrawing = differenceTimeDrawing / 1000000; long msDifferenceTimeLayout = differenceTimeLayout / 1000000; long msDifferenceTimeSubGraph = differenceTimeSubGraph / 1000000; long msDifferenceTimeColorize = differenceTimeColorize / 1000000; Console.println("time of SubGraph: " + msDifferenceTimeSubGraph); Console.println("Time of layout: " + msDifferenceTimeLayout); Console.println("Time of Colorize: " + msDifferenceTimeColorize); Console.println("Time of Drawing: " + millisecondTimeDrawing); Console.println("Time of Total Program: " + msDifferenceTimeProgram); } /** * Method to do the coloring of the to be drawn graph. */ private void colorize() { canvas.getGraphicsContext2D().setLineWidth(3.0); for (DrawableNode drawableNode : subGraph.getNodes().values()) { drawableNode.colorize(subGraph); } } /** * Fill the rectangles with the color. * @param nodes the Collection of {@link Integer Integers} to highlight. * @param color the {@link Color} to highlight with. */ private void highlightNodesByID(Collection<Integer> nodes, Color color) { for (int i : nodes) { highlightNode(i, color); } } /** * Method to highlight a collection of nodes. * @param nodes The nodes to highlight. * @param color The color to highlight with. */ private void highlightNodes(Collection<DrawableNode> nodes, Color color) { for (DrawableNode drawNode: nodes) { highlightNode(drawNode, color); } } /** * Fill the rectangle with the color. * @param nodeID the nodeID of the node to highlight. * @param color the {@link Color} to highlight with. */ public void highlightNode(int nodeID, Color color) { DrawableNode node = subGraph.getNodes().get(nodeID); highlightNode(node, color); } /** * Highlights a single node. * @param node {@link DrawableNode} to highlight. * @param color {@link Color} to color with. */ public void highlightNode(DrawableNode node, Color color) { node.setStrokeColor(color); node.setStrokeWidth(5.0); drawNode(canvas.getGraphicsContext2D(), node); } /** * Method to highlight a Link. Changes the stroke color of the Link. * @param edge {@link DrawableEdge} is the edge to highlight. * @param color {@link Color} is the color in which the Link node needs to highlight. */ private void highlightEdge(DrawableEdge edge, Color color) { edge.setStrokeColor(color); } /** * Method to highlight a dummy node. Changes the stroke color of the node. * @param node {@link DrawableDummy} is the dummy node that needs highlighting. * @param color {@link Color} is the color in which the dummy node needs a highlight. */ private void highlightDummyNode(DrawableDummy node, Color color) { node.setStrokeColor(color); } /** * Draws a edge on the location it has. * @param gc {@link GraphicsContext} is the GraphicsContext required to draw. * @param parent {@link DrawableNode} is the node to be draw from. * @param child {@link DrawableNode} is the node to draw to. */ private void drawEdge(GraphicsContext gc, DrawableNode parent, DrawableNode child) { DrawableEdge edge = new DrawableEdge(parent, child); edge.colorize(subGraph); gc.setLineWidth(edge.getStrokeWidth() * zoomLevel); gc.setStroke(edge.getStrokeColor()); XYCoordinate startLocation = edge.getStartLocation(); XYCoordinate endLocation = edge.getEndLocation(); Line line = new Line(startLocation.getX(), startLocation.getY(), endLocation.getX(), endLocation.getY()); line.setStrokeWidth(edge.getStrokeWidth()); this.edgeLocation.put(edge, line); gc.strokeLine(startLocation.getX(), startLocation.getY(), endLocation.getX(), endLocation.getY()); } /** * Draws a node on the location it has. * @param gc {@link GraphicsContext} is the GraphicsContext required to draw. * @param drawableNode {@link DrawableNode} is the node to be drawn. */ public void drawNode(GraphicsContext gc, DrawableNode drawableNode) { gc.setStroke(drawableNode.getStrokeColor()); gc.setFill(drawableNode.getFillColor()); gc.setLineWidth(drawableNode.getStrokeWidth()); gc.strokeRect(drawableNode.getLeftBorderCenter().getX(), drawableNode.getLocation().getY(), drawableNode.getWidth(), drawableNode.getHeight()); gc.fillRect(drawableNode.getLeftBorderCenter().getX(), drawableNode.getLocation().getY(), drawableNode.getWidth(), drawableNode.getHeight()); } /** * Getter for the graph. * @return - The graph */ public GenomeGraph getGraph() { return graph; } /** * Setter for the graph. * @param graph The graph */ void setGraph(GenomeGraph graph) { this.graph = graph; } /** * Clear the draw area. */ public void clear() { this.canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); } public double getLocationCenterX() { return locationCenterX; } public double getLocationCenterY() { return locationCenterY; } /** * Centers on the given node. * @param nodeId is the node to center on. */ public void centerOnNodeId(int nodeId) { DrawableNode drawableCenterNode = subGraph.getNodes().get(nodeId); double xCoordinate = drawableCenterNode.getCenter().getX(); Bounds bounds = canvas.getParent().getLayoutBounds(); double boundsHeight = bounds.getHeight(); double boundsWidth = bounds.getWidth(); locationCenterY = boundsHeight / 4; locationCenterX = boundsWidth / 2 - xCoordinate; translate(locationCenterX, locationCenterY); } /** * Translate function for the nodes. Used to change the location of nodes instead of mocing the canvas. * @param xDifference double with the value of the change in the X (horizontal) direction. * @param yDifference double with the value of the change in the Y (vertical) direction. */ public void translate(double xDifference, double yDifference) { for (DrawableNode node : subGraph.getNodes().values()) { double oldXLocation = node.getLocation().getX(); double oldYLocation = node.getLocation().getY(); node.setLocation(oldXLocation + xDifference, oldYLocation + yDifference); } draw(canvas.getGraphicsContext2D()); } /** * Zoom function for the nodes. Used to increase the size of the nodes instead of zooming in on the canvas itself. * @param scale double with the value of the increase of the nodes. Value higher than 1 means that the node size * decreases, value below 1 means that the node size increases. */ public void zoom(double scale) { for (DrawableNode node : subGraph.getNodes().values()) { double oldXLocation = node.getLocation().getX(); double oldYLocation = node.getLocation().getY(); node.setHeight(node.getHeight() / scale); node.setWidth(node.getWidth() / scale); node.setStrokeWidth(node.getStrokeWidth() / scale); node.setLocation(oldXLocation / scale, oldYLocation / scale); } zoomLevel /= scale; draw(canvas.getGraphicsContext2D()); } /** * Draw method for the whole subgraph. Calls draw node and draw Edge for every node and edge. * @param gc is the {@link GraphicsContext} required to draw. */ public void draw(GraphicsContext gc) { gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); for (DrawableNode drawableNode : subGraph.getNodes().values()) { drawNode(gc, drawableNode); for (DrawableNode child : subGraph.getChildren(drawableNode)) { drawEdge(gc, drawableNode, child); } } } /** * Method to show the information of an edge. * @param edge DrawableEdge the edge which has been clicked on. * @param x int the x location of the TextField. */ private void showInfoEdge(DrawableEdge edge, int x) { anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x); Text idText = new Text("Genomes: "); idText.setLayoutX(x); idText.setLayoutY(65); Text parentsText = new Text("Parent: "); parentsText.setLayoutX(x); parentsText.setLayoutY(115); Text childrenText = new Text("Child: "); childrenText.setLayoutX(x); childrenText.setLayoutY(165); TextField id = getTextField("Genomes: ", x, 70, graph.getGenomeNames(edge.getGenomes()).toString()); TextField parent = getTextField("Parent Node: ", x, 120, Integer.toString(edge.getStart().getIdentifier())); TextField child = getTextField("Child Node: ", x, 170, Integer.toString(edge.getEnd().getIdentifier())); anchorGraphInfo.getChildren().addAll(idText, parentsText, childrenText, id, parent, child); } /** * Method to show the information of a node. * @param node DrawableSegment the node which has been clicked on. * @param x int the x location of the TextField. */ private void showInfoNode(DrawableSegment node, int x) { Text idText = new Text("ID: "); idText.setLayoutX(x); idText.setLayoutY(65); Text parentText = new Text("Parents: "); parentText.setLayoutX(x); parentText.setLayoutY(105); Text childText = new Text("Children: "); childText.setLayoutX(x); childText.setLayoutY(145); Text inEdgeText = new Text("Incoming Edges: "); inEdgeText.setLayoutX(x); inEdgeText.setLayoutY(185); Text outEdgeText = new Text("Outgoing Edges: "); outEdgeText.setLayoutX(x); outEdgeText.setLayoutY(225); Text seqLengthText = new Text("Sequence Length: "); seqLengthText.setLayoutX(x); seqLengthText.setLayoutY(265); Text genomeText = new Text("Genomes: "); genomeText.setLayoutX(x); genomeText.setLayoutY(305); Text seqText = new Text("Sequence: "); seqText.setLayoutX(x); seqText.setLayoutY(370); anchorGraphInfo.getChildren().removeIf(node1 -> node1.getLayoutX() == x); TextField idTextField = getTextField("ID: ", x, 70, Integer.toString(node.getIdentifier())); StringBuilder parentSB = new StringBuilder(); node.getParents().forEach(id -> parentSB.append(id).append(", ")); TextField parents; if (parentSB.length() > 2) { parentSB.setLength(parentSB.length() - 2); parents = getTextField("Parents: ", x, 110, parentSB.toString()); } else { parentSB.replace(0, parentSB.length(), "This node has no parent(s)"); parents = getTextField("Parents: ", x, 110, parentSB.toString()); } StringBuilder childSB = new StringBuilder(); node.getChildren().forEach(id -> childSB.append(id).append(", ")); TextField children; if (childSB.length() > 2) { childSB.setLength(childSB.length() - 2); children = getTextField("Children: ", x, 150, childSB.toString()); } else { childSB.replace(0, childSB.length(), "This node has no child(ren)"); children = getTextField("Children: ", x, 150, childSB.toString()); } String genomesString = graph.getGenomeNames(node.getGenomes()).toString(); String sequenceString = node.getSequence().replaceAll("(.{24})", "$1" + System.getProperty("line.separator")); TextField inEdges = getTextField("Incoming Edges: ", x, 190, Integer.toString(node.getParents().size())); TextField outEdges = getTextField("Outgoing Edges: ", x, 230, Integer.toString(node.getChildren().size())); TextField seqLength = getTextField("Sequence Length: ", x, 270, Integer.toString(node.getSequence().length())); TextArea genome = getTextArea("Genome: ", x, 310, genomesString.substring(1, genomesString.length() - 1), 40); genome.setWrapText(true); TextArea seq = getTextArea("Sequence: ", x, 375, sequenceString, 250); anchorGraphInfo.getChildren().addAll(idText, parentText, childText, inEdgeText, outEdgeText, genomeText, seqLengthText, seqText); anchorGraphInfo.getChildren().addAll(idTextField, parents, children, inEdges, outEdges, genome, seqLength, seq); } /** * Returns a textField to be used by the edge and node information show panel. * @param id String the id of the textField. * @param x int the x coordinate of the textField inside the anchorPane. * @param y int the y coordinate of the textField inside the anchorPane. * @param text String the text to be shown by the textField. * @param height int of the height of the area. * @return TextField the created textField. */ private TextArea getTextArea(String id, int x, int y, String text, int height) { TextArea textArea = new TextArea(); textArea.setId(id); textArea.setText(text); textArea.setLayoutX(x); textArea.setLayoutY(y); textArea.setEditable(false); textArea.setStyle("-fx-text-box-border: transparent;-fx-background-color: none; -fx-background-insets: 0;" + " -fx-padding: 1 3 1 3; -fx-focus-color: transparent; " + "-fx-faint-focus-color: transparent; -fx-font-family: monospace;"); textArea.setPrefSize(225, height); return textArea; } /** * Returns a textField to be used by the edge and node information show panel. * @param id String the id of the textField. * @param x int the x coordinate of the textField inside the anchorPane. * @param y int the y coordinate of the textField inside the anchorPane. * @param text String the text to be shown by the textField. * @return TextField the created textField. */ private TextField getTextField(String id, int x, int y, String text) { TextField textField = new TextField(); textField.setId(id); textField.setText(text); textField.setLayoutX(x); textField.setLayoutY(y); textField.setEditable(false); textField.setStyle("-fx-text-box-border: transparent;-fx-background-color: none; -fx-background-insets: 0;" + " -fx-padding: 1 3 1 3; -fx-focus-color: transparent; " + "-fx-faint-focus-color: transparent; -fx-font-family: monospace;"); textField.setPrefSize(220, 20); return textField; } /** * Method to do highlighting based on a min and max amount of genomes in a node. * @param min The minimal amount of genomes * @param max The maximal amount of genomes * @param color the {@link Color} in which the highlight has to be done. */ public void highlightMinMax(int min, int max, Color color) { LinkedList<DrawableNode> drawNodeList = new LinkedList<>(); removeHighlight(oldMinMaxList); removeHighlight(oldGenomeList); for (DrawableNode drawableNode: subGraph.getNodes().values()) { if (drawableNode != null && !(drawableNode instanceof DrawableDummy)) { int genomeCount = drawableNode.getGenomes().size(); if (genomeCount >= min && genomeCount <= max) { drawNodeList.add(drawableNode); } } } oldMinMaxList = drawNodeList; highlightNodes(drawNodeList, color); } /** * Resets the node highlighting to remove highlights. * @param nodes are the nodes to remove the highlight from. */ private void removeHighlight(Collection<DrawableNode> nodes) { for (DrawableNode node: nodes) { node.colorize(subGraph); } this.draw(canvas.getGraphicsContext2D()); } /** * Highlights based on genomeID. * @param genomeID the GenomeID to highlight on. */ public void highlightByGenome(int genomeID) { LinkedList<DrawableNode> drawNodeList = new LinkedList<>(); removeHighlight(oldGenomeList); removeHighlight(oldMinMaxList); for (DrawableNode drawableNode: subGraph.getNodes().values()) { Collection<Integer> genomes = drawableNode.getGenomes(); for (int genome : genomes) { if (genome == genomeID && !(drawableNode instanceof DrawableDummy)) { drawNodeList.add(drawableNode); } } } oldGenomeList = drawNodeList; highlightNodes(drawNodeList, Color.YELLOW); } /** * Returns the node clicked on else returns null. * @param x position horizontally where clicked * @param y position vertically where clicked */ void onClick(double x, double y) { System.out.println("Canvas clicked " + x + ", " + y); //TODO implement this with a tree instead of iterating. for (DrawableNode drawableNode : subGraph.getNodes().values()) { if (x >= drawableNode.getLocation().getX() && y >= drawableNode.getLocation().getY() && x <= drawableNode.getLocation().getX() + drawableNode.getWidth() && y <= drawableNode.getLocation().getY() + drawableNode.getHeight()) { showInfoNode((DrawableSegment) drawableNode, 10); } } this.edgeLocation.forEach((drawableEdge, line) -> { if (line.contains(x, y)) { showInfoEdge(drawableEdge, 10); } }); } }
package org.objectweb.proactive.ic2d.gui.util; import org.objectweb.proactive.core.util.UrlBuilder; import org.objectweb.proactive.ic2d.data.WorldObject; import org.objectweb.proactive.ic2d.gui.data.IC2DPanel; import org.objectweb.proactive.ic2d.gui.data.WorldPanel; import org.objectweb.proactive.ic2d.gui.dialog.FilteredClassesPanel; import org.objectweb.proactive.ic2d.util.ActiveObjectFilter; import org.objectweb.proactive.ic2d.util.IC2DMessageLogger; import org.objectweb.proactive.ic2d.util.MonitorThread; public class DialogUtils { private DialogUtils() { } public static void openNewRMIHostDialog( java.awt.Component parentComponent, WorldPanel worldPanel, IC2DMessageLogger logger) { WorldObject worldObject = worldPanel.getWorldObject(); String initialHostValue = "localhost"; try { initialHostValue = UrlBuilder.getHostNameorIP(java.net.InetAddress.getLocalHost()) + ":" + System.getProperty("proactive.rmi.port"); } catch (java.net.UnknownHostException e) { logger.log(e.getMessage()); return; } // calling dlg for host or ip and depth control HostDialog rmihostdialog = HostDialog.showHostDialog((javax.swing.JFrame) parentComponent, initialHostValue); if (!rmihostdialog.isButtonOK()) { return; } rmihostdialog.setButtonOK(false); String host = rmihostdialog.getJTextFieldHostIp(); worldPanel.monitoredHostAdded(host, "rmi:"); worldPanel.getMonitorThread().updateHosts(); //new MonitorThread("rmi:", host, rmihostdialog.getJTextFielddepth(),worldObject, logger);//.start(); } public static void openNewHTTPHostDialog( java.awt.Component parentComponent, WorldPanel worldPanel, IC2DMessageLogger logger) { WorldObject worldObject = worldPanel.getWorldObject(); String initialHostValue = "localhost"; try { initialHostValue = UrlBuilder.getHostNameorIP(java.net.InetAddress.getLocalHost()) + ":" + System.getProperty("proactive.http.port"); ; } catch (java.net.UnknownHostException e) { logger.log(e.getMessage()); return; } HostDialog httphostdialog = HostDialog.showHostDialog((javax.swing.JFrame) parentComponent, initialHostValue); if (!httphostdialog.isButtonOK()) { return; } httphostdialog.setButtonOK(false); String host = httphostdialog.getJTextFieldHostIp(); //new MonitorThread("http:", host, httphostdialog.getJTextFielddepth(),worldObject, logger);//.start(); worldPanel.monitoredHostAdded(host, "http:"); worldPanel.getMonitorThread().updateHosts(); // Object result = javax.swing.JOptionPane.showInputDialog(parentComponent, // Component parentComponent, // "Please enter the name or the IP of the host to monitor :", // Object message, // "Adding a host to monitor", // String title, // javax.swing.JOptionPane.PLAIN_MESSAGE, // int messageType, // null, // Icon icon, // null, // Object[] selectionValues, // initialHostValue // Object initialSelectionValue) // if ((result == null) || (!(result instanceof String))) { // return; // String host = (String) result; // System.out.println("host " + host); // try { // worldObject.addHostObject(host, asso); // } catch (RemoteException e1) { // e1.printStackTrace(); } public static void openNewIbisHostDialog( java.awt.Component parentComponent, WorldPanel worldPanel, IC2DMessageLogger logger) { WorldObject worldObject = worldPanel.getWorldObject(); String initialHostValue = "localhost"; try { initialHostValue = UrlBuilder.getHostNameorIP(java.net.InetAddress.getLocalHost()) + ":" + System.getProperty("proactive.rmi.port"); } catch (java.net.UnknownHostException e) { logger.log(e.getMessage()); return; } HostDialog ibishostdialog = HostDialog.showHostDialog((javax.swing.JFrame) parentComponent, initialHostValue); if (!ibishostdialog.isButtonOK()) { return; } ibishostdialog.setButtonOK(false); String host = ibishostdialog.getJTextFieldHostIp(); worldPanel.monitoredHostAdded(host, "ibis:"); worldPanel.getMonitorThread().updateHosts(); //new MonitorThread("ibis:", host, ibishostdialog.getJTextFielddepth(), worldObject, logger);//.start(); } public static void openNewJINIHostDialog( java.awt.Component parentComponent, WorldPanel worldPanel, IC2DMessageLogger logger) { WorldObject worldObject = worldPanel.getWorldObject(); String initialHostValue = "localhost"; try { initialHostValue = UrlBuilder.getHostNameorIP(java.net.InetAddress.getLocalHost()); } catch (java.net.UnknownHostException e) { logger.log(e.getMessage()); return; } HostDialog jinihostdialog = HostDialog.showHostDialog((javax.swing.JFrame) parentComponent, initialHostValue); if (!jinihostdialog.isButtonOK()) { return; } jinihostdialog.setButtonOK(false); String host = jinihostdialog.getJTextFieldHostIp(); worldPanel.monitoredHostAdded(host, "jini:"); worldPanel.getMonitorThread().updateHosts(); //new MonitorThread("jini:", host, jinihostdialog.getJTextFielddepth(), worldObject, logger);//.start(); } public static void openNewJINIHostsDialog( java.awt.Component parentComponent, WorldPanel worldPanel, IC2DMessageLogger logger) { WorldObject worldObject = worldPanel.getWorldObject(); // String initialHostValue = "localhost"; // try { // initialHostValue = UrlBuilder.getHostNameorIP(java.net.InetAddress.getLocalHost()); // } catch (java.net.UnknownHostException e) { // logger.log(e.getMessage()); // HostDialog jinihostdialog = HostDialog.showHostDialog((javax.swing.JFrame) parentComponent, // initialHostValue); // if (!jinihostdialog.isButtonOK()) { // return; // jinihostdialog.setButtonOK(false); // String host = jinihostdialog.getJTextFieldHostIp(); worldPanel.monitoredHostAdded(null, "jini:"); worldPanel.getMonitorThread().updateHosts(); //new MonitorThread("jini:", null, "3", worldObject, logger);//.start(); } // public static void openNewNodeDialog(java.awt.Component parentComponent, // WorldObject worldObject, IC2DMessageLogger logger) { // Object result = javax.swing.JOptionPane.showInputDialog(parentComponent, // Component parentComponent, // "Please enter the URL of the node in the form //hostname/nodename :", // Object message, // "Adding a JVM to monitor with ", // String title, // javax.swing.JOptionPane.PLAIN_MESSAGE, // int messageType, // null, // Icon icon, // null, // Object[] selectionValues, // "//hostname/nodename" // Object initialSelectionValue) // if ((result == null) || (!(result instanceof String))) { // return; // String url = (String) result; // String host = UrlBuilder.getHostNameFromUrl() // String nodeName = url.substring(n2 + 1); // // try { // // worldObject.addHostObject(host, null, nodeName); // // } catch (java.rmi.RemoteException e) { // // logger.log("Cannot create the RMI Host " + host, e); public static void displayMessageDialog( java.awt.Component parentComponent, Object message) { javax.swing.JOptionPane.showMessageDialog(parentComponent, // Component parentComponent, message, // Object message, "IC2D Message", // String title, javax.swing.JOptionPane.INFORMATION_MESSAGE // int messageType, ); } public static void displayWarningDialog( java.awt.Component parentComponent, Object message) { javax.swing.JOptionPane.showMessageDialog(parentComponent, // Component parentComponent, message, // Object message, "IC2D Message", // String title, javax.swing.JOptionPane.WARNING_MESSAGE // int messageType, ); } public static void openFilteredClassesDialog( java.awt.Component parentComponent, IC2DPanel ic2dPanel, ActiveObjectFilter filter) { FilteredClassesPanel panel = new FilteredClassesPanel(filter); int result = javax.swing.JOptionPane.showOptionDialog(parentComponent, // Component parentComponent, panel, // Object message, "Filtered classes dialog", // String title, javax.swing.JOptionPane.OK_CANCEL_OPTION, // option buttons javax.swing.JOptionPane.PLAIN_MESSAGE, // int messageType, null, // Icon icon, null, // Object[] selectionValues null); if (result != javax.swing.JOptionPane.OK_OPTION) { return; } if (panel.updateFilter(filter)) { ic2dPanel.updateFilteredClasses(); } } }
package org.jetel.plugin; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.naming.directory.InvalidAttributesException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.exception.ComponentNotReadyException; import org.jetel.util.file.FileUtils; import org.jetel.util.string.StringUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * This class describes plugin. Major part information is from xml manifest of plugin. * @author Martin Zatopek * */ public class PluginDescriptor { static Log logger = LogFactory.getLog(Plugins.class); /** * Identifier of plugin. */ private String id; /** * Plugin version. */ private String version; /** * Name of provider. */ private String providerName; /** * Name of plugin root class. */ private String pluginClassName; /** * Whether greedy classloader should be used for this plugin. * 'Greedy' means, that class loading does not follow standard parent-first strategy, * it uses self-first strategy instead. * (current classloader is preferred for class name resolution). */ private boolean greedyClassLoader = false; /** * List of package prefixes which are excluded from greedy/regular class loading. i.e. "java." "javax." "sun.misc." etc. * Prevents GreedyClassLoader from loading standard java interfaces and classes from third-party libs. */ private String[] excludedPackages; /** * List of all requires plugins. */ private List<PluginPrerequisite> prerequisites; /** * List of all class path. Definition for plugin class loader. */ private List<String> libraries; /** * List of all native library directories. It is used to extend system property java.library.path variable. */ private List<String> nativeLibraries; /** * List of all imlemented extensions points by this plugin. */ private List<Extension> extensions; /** * ClassLoader for this plugin. Is defined base on all libraries. */ private ClassLoader classLoader; /** * This class loader is optional and is used as a parent for {@link PluginClassLoader}. * This feature is used for example by clover designer in engine initialization. * @see GuiPlugin */ private ClassLoader parentClassLader; /** * Instance of plugin described by this desriptor. * If the plugin is not active, is <b>null</b>. */ private PluginActivator pluginActivator; /** * Link to manifest file (plugin.xml). */ private URL manifest; /** * Is true if plugin is already active. */ private boolean isActive = false; /** * @param manifest * @param parentClassLoader can be null */ public PluginDescriptor(URL manifest, ClassLoader parentClassLoader) { this.manifest = manifest; this.parentClassLader = parentClassLoader; prerequisites = new ArrayList<PluginPrerequisite>(); libraries = new ArrayList<String>(); nativeLibraries = new ArrayList<String>(); extensions = new ArrayList<Extension>(); } public void init() throws ComponentNotReadyException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setCoalescing(true); Document doc; try { doc = dbf.newDocumentBuilder().parse(manifest.openStream()); } catch (SAXException e) { throw new ComponentNotReadyException("Parse error occure in plugin manifest reading - " + manifest + ".", e); } catch (IOException e) { throw new ComponentNotReadyException("IO error occure in plugin manifest reading - " + manifest + ".", e); } catch (ParserConfigurationException e) { throw new ComponentNotReadyException("Parse error occure in plugin manifest reading - " + manifest+ ".", e); } PluginDescriptionBuilder builder = new PluginDescriptionBuilder(this); try { builder.read(doc); } catch (InvalidAttributesException e) { throw new ComponentNotReadyException("Parse error occure in plugin manifest reading - " + manifest + ".", e); } } //getters and setters// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProviderName() { return providerName; } public void setProviderName(String providerName) { this.providerName = providerName; } public boolean isGreedyClassLoader() { return greedyClassLoader; } public void setGreedyClassLoader(boolean greedyClassLoader) { this.greedyClassLoader = greedyClassLoader; } public String[] getExcludedPackages() { return excludedPackages; } public void setExcludedPackages(String[] excludedPackages) { this.excludedPackages = excludedPackages; } public String getPluginClassName() { return pluginClassName; } public void setPluginClassName(String className) { this.pluginClassName = className; } public URL getManifest() { return manifest; } public void setManifest(URL manifest) { this.manifest = manifest; } public String getVersion() { return version; } /** * @return major version parsed out from {@link #getVersion()} */ public int getMajorVersion() { String[] versionSegments = getVersionSegments(); return Integer.valueOf(versionSegments[0]); } /** * @return minor version parsed out from {@link #getVersion()} */ public int getMinorVersion() { String[] versionSegments = getVersionSegments(); return Integer.valueOf(versionSegments[1]); } private String[] getVersionSegments() { PluginDescriptor pluginDescriptor = Plugins.getPluginDescriptor(getId()); String version = pluginDescriptor.getVersion(); String[] subversions = version.split("\\."); //$NON-NLS-1$ return subversions; } public void setVersion(String version) { this.version = version; } public ClassLoader getClassLoader() { if(!isActive()) { activatePlugin(); // logger.warn("PluginDescription.getClassLoader(): Plugin " + getId() + " is not already active."); // return null; } if (classLoader == null) { ClassLoader realParentCL = parentClassLader != null ? parentClassLader : PluginDescriptor.class.getClassLoader(); if (Plugins.isSimpleClassLoading()) { classLoader = realParentCL; } else { classLoader = new PluginClassLoader(realParentCL, this, greedyClassLoader, excludedPackages); } } return classLoader; } public URL[] getLibraryURLs() { URL[] urls = new URL[libraries.size()]; for(int i = 0; i < libraries.size(); i++) { try { urls[i] = getURL(libraries.get(i)); } catch (MalformedURLException e) { logger.error("Cannot create URL to plugin (" + getManifest() + ") library " + libraries.get(i) + "."); urls[i] = null; } } return urls; } /** * Converts path relative to the plugin home directory. * @param path * @return * @throws MalformedURLException */ public URL getURL(String path) throws MalformedURLException { return FileUtils.getFileURL(manifest, path); } public Extension addExtension(String pointId) { Extension ret = new Extension(pointId, this); extensions.add(ret); return ret; } public List<Extension> getExtensions(String pointId) { List<Extension> ret = new ArrayList<Extension>(); for(Extension extension : extensions) { if(extension.getPointId().equals(pointId)) { ret.add(extension); } } return ret; } public List<Extension> getExtensions() { return Collections.unmodifiableList(extensions); } public void addLibrary(String library) { libraries.add(library); } public void addNativeLibrary(String nativeLibrary) { nativeLibraries.add(nativeLibrary); } public void addPrerequisites(String pluginId, String pluginVersion, String match) { prerequisites.add(new PluginPrerequisite(pluginId, pluginVersion, match)); } public List<PluginPrerequisite> getPrerequisites() { return prerequisites; } public void checkDependences() { for(PluginPrerequisite prerequisite : prerequisites) { if(Plugins.getPluginDescriptor(prerequisite.getPluginId()) == null) { logger.error("Plugin " + getId() + " depend on unknown plugin " + prerequisite.getPluginId()); } } } /** * Activate this plugin. Method registers this plugin description in Plugins class as active plugin. */ public void activatePlugin() { Plugins.activatePlugin(getId()); } /** * Deactivate this plugin. Method registers this plugin description in Plugins class as deactive plugin. */ public void deactivatePlugin() { Plugins.deactivatePlugin(getId()); } /** * This method is called only from Plugins.activatePlugin() method. */ protected void activate() { isActive = true; //first, we activate all prerequisites plugins for(Iterator it = getPrerequisites().iterator(); it.hasNext();) { PluginPrerequisite prerequisite = (PluginPrerequisite) it.next(); if(!Plugins.isActive(prerequisite.getPluginId())) { Plugins.activatePlugin(prerequisite.pluginId); } } //invoke plugin activator pluginActivator = instantiatePlugin(); if(pluginActivator != null) { pluginActivator.activate(); } //update java.library.path according native libraries applyNativeLibraries(); } /** * This method is called only from Plugins.deactivatePlugin() method. */ protected void deactivate() { isActive = false; if(pluginActivator != null) { pluginActivator.deactivate(); } } public boolean isActive() { return isActive; } /** * Create instance of plugin class. */ private PluginActivator instantiatePlugin() { if(!StringUtils.isEmpty(getPluginClassName())) { try { Class pluginClass = Class.forName(getPluginClassName(), true, getClassLoader()); Object plugin = pluginClass.newInstance(); if(!(plugin instanceof PluginActivator)) { logger.error("Plugin " + getId() + " activation message: Plugin class is not instance of Plugin ascendant - " + getPluginClassName()); return null; } //i have got plugin instance return (PluginActivator) plugin; } catch (ClassNotFoundException e) { logger.error("Plugin " + getId() + " activation message: Plugin class does not found - " + getPluginClassName(), e); } catch (Exception e) { logger.error("Plugin " + getId() + " activation message: Cannot create plugin instance - " + getPluginClassName() + " - class is abstract, interface or its nullary constructor is not accessible.", e); } } return null; } @Override public String toString() { StringBuffer ret = new StringBuffer(); ret.append("\tid - " + getId() + "\n"); ret.append("\tversion - " + getVersion() + "\n"); ret.append("\tprovider-name - " + getProviderName() + "\n"); for(Extension extension : extensions) { ret.append("\t\t" + extension + "\n"); //ret.append("\t\tpoint-id - " + extension.getPointId() + " - " + extension.getParameters() + "\n" ); } return ret.toString(); } /** * This is attempt to change 'java.library.path' system property in runtime. * Success of this attempt is not guaranteed. We are trying to administer * loading of dlls in runtime. * This method should be externalized to a seperated utils class. */ private void applyNativeLibraries() { if (nativeLibraries.size() > 0) { // Reset the "sys_paths" field of the ClassLoader to null. try { Class clazz = ClassLoader.class; Field field = clazz.getDeclaredField("sys_paths"); boolean accessible = field.isAccessible(); if (!accessible) field.setAccessible(true); field.set(clazz, null); field.setAccessible(accessible); // Change the value of system property java.library.path String pathSepartor = System.getProperty("path.separator"); StringBuilder additionalLibraryPathes = new StringBuilder(); for (String nativeLibrary : nativeLibraries) { additionalLibraryPathes.append(pathSepartor); nativeLibrary = URLDecoder.decode((new File(FileUtils.getFile(manifest, nativeLibrary))).getAbsolutePath(), "UTF-8"); additionalLibraryPathes.append(nativeLibrary); } if (additionalLibraryPathes.length() > 0) { System.setProperty("java.library.path", System.getProperty("java.library.path") + additionalLibraryPathes); } } catch (Throwable e) { logger.warn("Probably non-standard jvm is used. The native libraries in '" + getId() + "' plugin are ignored."); } } } }
package ru.yandex.market.graphouse.server; import com.google.common.base.Strings; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import ru.yandex.market.graphouse.Metric; import ru.yandex.market.graphouse.cacher.MetricCacher; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author Dmitry Andreev <a href="mailto:AndreevDm@yandex-team.ru"></a> * @date 02/04/15 */ public class MetricServer implements InitializingBean { private static final Logger log = LogManager.getLogger(); @Value("${graphouse.cacher.port}") private int port; @Value("${graphouse.cacher.bind-address}") private String bindAddress; @Value("${graphouse.cacher.socket-timeout-millis}") private int socketTimeoutMillis; @Value("${graphouse.cacher.threads}") private int threadCount; @Value("${graphouse.cacher.read-batch-size}") private int readBatchSize; @Value("${graphouse.log.remote-socket-address:false}") private boolean shouldLogRemoteSocketAddress; private ServerSocket serverSocket; private ExecutorService executorService; private final MetricCacher metricCacher; private final MetricFactory metricFactory; public MetricServer(MetricCacher metricCacher, MetricFactory metricFactory) { this.metricCacher = metricCacher; this.metricFactory = metricFactory; } @Override public void afterPropertiesSet() throws Exception { log.info("Starting metric server on port: " + port); serverSocket = new ServerSocket(); SocketAddress socketAddress; if (Strings.isNullOrEmpty(bindAddress)) { socketAddress = new InetSocketAddress(port); } else { socketAddress = new InetSocketAddress(bindAddress, port); } serverSocket.bind(socketAddress); log.info("Starting " + threadCount + " metric server threads"); executorService = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { executorService.submit(new MetricServerWorker()); } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { log.info("Shutting down metric server"); executorService.shutdownNow(); try { serverSocket.close(); } catch (IOException ignored) { } log.info("Metric server stopped"); } })); log.info("Metric server started on port " + port); } private class MetricServerWorker implements Runnable { private final List<Metric> metrics = new ArrayList<>(readBatchSize); @Override public void run() { while (!Thread.interrupted() && !serverSocket.isClosed()) { try { read(); } catch (Exception e) { log.warn("Failed to read data", e); } } log.info("MetricServerWorker stopped"); } private void read() throws IOException { metrics.clear(); Socket socket = serverSocket.accept(); if (shouldLogRemoteSocketAddress) { log.info("Connection accepted. Client's address: '{}'", socket.getRemoteSocketAddress().toString()); } try { socket.setSoTimeout(socketTimeoutMillis); socket.setKeepAlive(false); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; while ((line = reader.readLine()) != null) { int updatedSeconds = (int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); Metric metric = metricFactory.createMetric(line, updatedSeconds); if (metric != null) { metrics.add(metric); if (metrics.size() >= readBatchSize) { metricCacher.submitMetrics(metrics); metrics.clear(); } } } } catch (SocketTimeoutException e) { log.warn("Socket timeout from " + socket.getRemoteSocketAddress().toString()); } finally { socket.close(); } metricCacher.submitMetrics(metrics); metrics.clear(); } } public void setSocketTimeoutMillis(int socketTimeoutMillis) { this.socketTimeoutMillis = socketTimeoutMillis; } public void setThreadCount(int threadCount) { this.threadCount = threadCount; } public void setPort(int port) { this.port = port; } }
package org.jetel.lookup; import java.io.ByteArrayInputStream; import java.security.InvalidParameterException; import java.text.Collator; import java.text.RuleBasedCollator; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import java.util.TreeSet; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.HashKey; import org.jetel.data.RecordComparator; import org.jetel.data.RecordKey; import org.jetel.data.StringDataField; import org.jetel.data.lookup.Lookup; import org.jetel.data.lookup.LookupTable; import org.jetel.data.parser.DataParser; import org.jetel.data.parser.Parser; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.GraphConfigurationException; import org.jetel.exception.NotInitializedException; import org.jetel.exception.XMLConfigurationException; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.graph.GraphElement; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.MiscUtils; import org.jetel.util.file.FileUtils; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; public class RangeLookupTable extends GraphElement implements LookupTable { private static final String XML_LOOKUP_TYPE_RANGE_LOOKUP = "rangeLookup"; private static final String XML_FILE_URL = "fileURL"; private static final String XML_START_FIELDS = "startFields"; private static final String XML_END_FIELDS = "endFields"; private static final String XML_CHARSET = "charset"; private static final String XML_USE_I18N = "useI18N"; private static final String XML_LOCALE = "locale"; private static final String XML_START_INCLUDE = "startInclude"; private static final String XML_END_INCLUDE = "endInclude"; private static final String XML_DATA_ATTRIBUTE = "data"; private final static String[] REQUESTED_ATTRIBUTE = {XML_ID_ATTRIBUTE, XML_TYPE_ATTRIBUTE, XML_METADATA_ID, XML_START_FIELDS, XML_END_FIELDS }; public static final boolean DEFAULT_START_INCLUDE = true; public static final boolean DEFAULT_END_INCLUDE = false; protected DataRecordMetadata metadata;//defines lookup table protected String metadataId; protected Parser dataParser; protected SortedSet<DataRecord> lookupTable;//set of intervals protected RecordKey startKey; protected String[] startFields; protected int[] startField; protected RecordKey endKey; protected String[] endFields; protected int[] endField; protected IntervalRecordComparator comparator; protected RuleBasedCollator collator = null; protected boolean[] startInclude; protected boolean[] endInclude; protected boolean useI18N; protected String locale; protected String charset; protected String fileURL; // data of the lookup table, can be used instead of an input file protected String data; /** * Constructor for most general range lookup table * * @param id id * @param metadata metadata defining this lookup table * @param parser parser for reading defining records * @param collator collator for comparing string fields * @param startInclude indicates whether start points belong to the intervals or not * @param endInclude indicates whether end points belong to the intervals or not */ public RangeLookupTable(String id, DataRecordMetadata metadata, String[] startFields, String[] endFields, Parser parser, RuleBasedCollator collator, boolean[] startInclude, boolean[] endInclude){ super(id); this.metadata = metadata; this.startFields = startFields; this.endFields = endFields; this.dataParser = parser; this.collator = collator; if (startInclude.length != (metadata.getNumFields() - 1)/2) { throw new InvalidParameterException("startInclude parameter has wrong number " + "of elements: " + startInclude.length + " (should be " + (metadata.getNumFields() - 1)/2 + ")"); } this.startInclude = startInclude; if (endInclude.length != (metadata.getNumFields() - 1)/2) { throw new InvalidParameterException("endInclude parameter has wrong number " + "of elements: " + endInclude.length + " (should be " + (metadata.getNumFields() - 1)/2 + ")"); } this.endInclude = endInclude; } /** * Constructor with standard settings for start and end points * * @param id * @param metadata * @param parser * @param collator */ public RangeLookupTable(String id, DataRecordMetadata metadata, String[] startFields, String[] endFields, Parser parser, RuleBasedCollator collator){ this(id,metadata,startFields, endFields, parser,collator,new boolean[(metadata.getNumFields() - 1)/2], new boolean[(metadata.getNumFields() - 1)/2]); Arrays.fill(startInclude, DEFAULT_START_INCLUDE); Arrays.fill(endInclude, DEFAULT_END_INCLUDE); } public RangeLookupTable(String id, DataRecordMetadata metadata, String[] startFields, String[] endFields, Parser parser, boolean[] startInclude, boolean[] endInclude){ this(id,metadata,startFields, endFields, parser,null,startInclude,endInclude); } public RangeLookupTable(String id, DataRecordMetadata metadata, String[] startFields, String[] endFields, Parser parser){ this(id,metadata,startFields, endFields, parser,null); } public RangeLookupTable(String id, String metadataId, String[] startFields, String[] endFields){ super(id); this.metadataId = metadataId; this.startFields = startFields; this.endFields = endFields; } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if (metadata == null) { metadata = getGraph().getDataRecordMetadata(metadataId); } if (metadata == null) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadataId) + " does not exist!!!", Severity.ERROR, this, Priority.NORMAL, XML_METADATA_ID)); } if (startKey == null) { startKey = new RecordKey(startFields, metadata); } if (endKey == null) { endKey = new RecordKey(endFields, metadata); } RecordKey.checkKeys(startKey, XML_START_FIELDS, endKey, XML_END_FIELDS, status, this); if (startInclude == null) { startInclude = new boolean[startFields.length]; Arrays.fill(startInclude, DEFAULT_START_INCLUDE); } if (endInclude == null) { endInclude = new boolean[endFields.length]; Arrays.fill(endInclude, DEFAULT_END_INCLUDE); } for (int i = 0; i < startFields.length; i++) { if (startFields[i].equals(endFields[i]) && !(startInclude[i] && endInclude[i])) { status.add(new ConfigurationProblem("Interval " + StringUtils.quote(startFields[i] + " - " + endFields[i]) + " is empty (" + (!startInclude[i] ? "startInclude[" : "endInclude[") + i + "] is false).", Severity.WARNING, this, Priority.NORMAL)); } } return status; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public synchronized void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); if (metadata == null) { metadata = getGraph().getDataRecordMetadata(metadataId); } if (metadata == null) { throw new ComponentNotReadyException("Metadata " + StringUtils.quote(metadataId) + " does not exist!!!"); } if (startKey == null) { startKey = new RecordKey(startFields, metadata); startKey.init(); } startField = startKey.getKeyFields(); if (endKey == null) { endKey = new RecordKey(endFields, metadata); endKey.init(); } endField = endKey.getKeyFields(); if (startInclude == null) { startInclude = new boolean[startFields.length]; Arrays.fill(startInclude, DEFAULT_START_INCLUDE); } if (endInclude == null) { endInclude = new boolean[endFields.length]; Arrays.fill(endInclude, DEFAULT_END_INCLUDE); } if (collator == null && useI18N) { if (locale != null) { collator = (RuleBasedCollator)Collator.getInstance(MiscUtils.createLocale(locale)); }else{ collator = (RuleBasedCollator)Collator.getInstance(); } } comparator = new IntervalRecordComparator(metadata, startField, endField, collator); lookupTable = Collections.synchronizedSortedSet(new TreeSet<DataRecord>(comparator)); if (dataParser == null && (fileURL != null || data!= null)) { dataParser = new DataParser(charset); } DataRecord tmpRecord = new DataRecord(metadata); tmpRecord.init(); //read records from file if (dataParser != null) { dataParser.init(metadata); try { if (fileURL != null) { dataParser.setDataSource(FileUtils.getReadableChannel( getGraph() != null ? getGraph().getProjectURL() : null, fileURL)); }else if (data != null) { dataParser.setDataSource(new ByteArrayInputStream(data.getBytes())); } while (dataParser.getNext(tmpRecord) != null) { lookupTable.add(tmpRecord.duplicate()); } } catch (Exception e) { throw new ComponentNotReadyException(this, e.getMessage(), e); } dataParser.close(); } } @Override public synchronized void reset() throws ComponentNotReadyException { super.reset(); lookupTable.clear(); //read records from file if (dataParser != null) { DataRecord tmpRecord = new DataRecord(metadata); tmpRecord.init(); dataParser.reset(); try { if (fileURL != null) { dataParser.setDataSource(FileUtils.getReadableChannel( getGraph() != null ? getGraph().getProjectURL() : null, fileURL)); }else if (data != null) { dataParser.setDataSource(new ByteArrayInputStream(data.getBytes())); } while (dataParser.getNext(tmpRecord) != null) { lookupTable.add(tmpRecord.duplicate()); } } catch (Exception e) { throw new ComponentNotReadyException(this, e.getMessage(), e); } dataParser.close(); } } /* (non-Javadoc) * @see org.jetel.data.lookup.LookupTable#getMetadata() */ public DataRecordMetadata getMetadata() { return metadata; } public boolean isPutSupported() { return true; } public boolean isRemoveSupported() { return true; } public boolean put(DataRecord dataRecord) { lookupTable.add(dataRecord.duplicate()); return true; } public boolean remove(DataRecord dataRecord) { return lookupTable.remove(dataRecord); } public boolean remove(HashKey key) { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see java.lang.Iterable#iterator() */ public Iterator<DataRecord> iterator() { return lookupTable.iterator(); } public static RangeLookupTable fromProperties(TypedProperties properties) throws AttributeNotFoundException, GraphConfigurationException { for (String property : REQUESTED_ATTRIBUTE) { if (!properties.containsKey(property)) { throw new AttributeNotFoundException(property); } } String type = properties.getProperty(XML_TYPE_ATTRIBUTE); if (!type.equalsIgnoreCase(XML_LOOKUP_TYPE_RANGE_LOOKUP)){ throw new GraphConfigurationException("Can't create range lookup table from type " + type); } String id = properties.getProperty(XML_ID_ATTRIBUTE); String metadataString = properties.getProperty(XML_METADATA_ID); String[] startFields = properties.getProperty(XML_START_FIELDS).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); String[] endFields = properties.getProperty(XML_END_FIELDS).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); RangeLookupTable lookupTable = new RangeLookupTable(id, metadataString, startFields, endFields); if (properties.containsKey(XML_NAME_ATTRIBUTE)){ lookupTable.setName(properties.getProperty(XML_NAME_ATTRIBUTE)); } lookupTable.setUseI18N(properties.getBooleanProperty(XML_USE_I18N, false)); if (properties.containsKey(XML_LOCALE)){ lookupTable.setLocale(XML_LOCALE); } if (properties.containsKey(XML_FILE_URL)){ lookupTable.setFileURL(properties.getProperty(XML_FILE_URL)); } lookupTable.setCharset(properties.getProperty(XML_CHARSET, Defaults.DataParser.DEFAULT_CHARSET_DECODER)); boolean[] startInclude = null; if (properties.containsKey(XML_START_INCLUDE)){ String[] sI = properties.getProperty(XML_START_INCLUDE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); startInclude = new boolean[sI.length]; for (int i = 0; i < sI.length; i++) { startInclude[i] = Boolean.parseBoolean(sI[i]); } } boolean[] endInclude = null; if (properties.containsKey(XML_END_INCLUDE)){ String[] eI = properties.getProperty(XML_END_INCLUDE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); endInclude = new boolean[eI.length]; for (int i = 0; i < eI.length; i++) { endInclude[i] = Boolean.parseBoolean(eI[i]); } if (startInclude == null) { startInclude = new boolean[endInclude.length]; for (int i = 0; i < endInclude.length; i++) { startInclude[i] = true; } } }else if (properties.containsKey(XML_START_INCLUDE)){ endInclude = new boolean[startInclude.length]; for (int i = 0; i < endInclude.length; i++) { endInclude[i] = false; } } lookupTable.setStartInclude(startInclude); lookupTable.setEndInclude(endInclude); if (properties.containsKey(XML_DATA_ATTRIBUTE)) { lookupTable.setData(properties.getProperty(XML_DATA_ATTRIBUTE)); } return lookupTable; } public static RangeLookupTable fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); RangeLookupTable lookupTable = null; String id; String type; String metadata; String[] startFields; String[] endFields; //reading obligatory attributes try { id = xattribs.getString(XML_ID_ATTRIBUTE); type = xattribs.getString(XML_TYPE_ATTRIBUTE); metadata = xattribs.getString(XML_METADATA_ID); startFields = xattribs.getString(XML_START_FIELDS).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); endFields = xattribs.getString(XML_END_FIELDS).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); } catch(AttributeNotFoundException ex) { throw new XMLConfigurationException("Can't create lookup table - " + ex.getMessage(),ex); } //check type if (!type.equalsIgnoreCase(XML_LOOKUP_TYPE_RANGE_LOOKUP)) { throw new XMLConfigurationException("Can't create range lookup table from type " + type); } lookupTable = new RangeLookupTable(id, metadata, startFields, endFields); try { if (xattribs.exists(XML_NAME_ATTRIBUTE)){ lookupTable.setName(xattribs.getString(XML_NAME_ATTRIBUTE)); } lookupTable.setUseI18N(xattribs.getBoolean(XML_USE_I18N, false)); if (xattribs.exists(XML_LOCALE)){ lookupTable.setLocale(XML_LOCALE); } if (xattribs.exists(XML_FILE_URL)){ lookupTable.setFileURL(xattribs.getString(XML_FILE_URL)); } lookupTable.setCharset(xattribs.getString(XML_CHARSET, Defaults.DataParser.DEFAULT_CHARSET_DECODER)); boolean[] startInclude = null; if (xattribs.exists(XML_START_INCLUDE)){ String[] sI = xattribs.getString(XML_START_INCLUDE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); startInclude = new boolean[sI.length]; for (int i = 0; i < sI.length; i++) { startInclude[i] = Boolean.parseBoolean(sI[i]); } } boolean[] endInclude = null; if (xattribs.exists(XML_END_INCLUDE)){ String[] eI = xattribs.getString(XML_END_INCLUDE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); endInclude = new boolean[eI.length]; for (int i = 0; i < eI.length; i++) { endInclude[i] = Boolean.parseBoolean(eI[i]); } if (startInclude == null) { startInclude = new boolean[endInclude.length]; for (int i = 0; i < endInclude.length; i++) { startInclude[i] = true; } } }else if (xattribs.exists(XML_START_INCLUDE)){ endInclude = new boolean[startInclude.length]; for (int i = 0; i < endInclude.length; i++) { endInclude[i] = false; } } lookupTable.setStartInclude(startInclude); lookupTable.setEndInclude(endInclude); if (xattribs.exists(XML_DATA_ATTRIBUTE)) { lookupTable.setData(xattribs.getString(XML_DATA_ATTRIBUTE)); } return lookupTable; } catch (AttributeNotFoundException e) { throw new XMLConfigurationException("can't create simple lookup table",e); } } public boolean[] getEndInclude() { return endInclude; } public void setEndInclude(boolean[] endInclude) { this.endInclude = endInclude; } public void setEndInclude(boolean endInclude){ setEndInclude(new boolean[]{endInclude}); } public boolean[] getStartInclude() { return startInclude; } public void setStartInclude(boolean[] startInclude) { this.startInclude = startInclude; } public void setStartInclude(boolean startInclude){ setStartInclude(new boolean[]{startInclude}); } public int[] getStartFields(){ if (startField == null) { startKey = new RecordKey(startFields, metadata); startKey.init(); startField = startKey.getKeyFields(); } return startField; } public int[] getEndFields(){ if (endField == null) { endKey = new RecordKey(endFields, metadata); endKey.init(); endField = endKey.getKeyFields(); } return endField; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public boolean isUseI18N() { return useI18N; } public void setUseI18N(boolean useI18N) { this.useI18N = useI18N; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public String getFileURL() { return fileURL; } public void setFileURL(String fileURL) { this.fileURL = fileURL; } public String getData() { return data; } public void setData(String data) { this.data = data; } public RuleBasedCollator getCollator() { return collator; } public Lookup createLookup(RecordKey key) { return createLookup(key, null); } public Lookup createLookup(RecordKey key, DataRecord keyRecord) { return new RangeLookup(this, key, keyRecord); } public char[] getKey() throws ComponentNotReadyException, UnsupportedOperationException, NotInitializedException { if (!isInitialized()) throw new NotInitializedException(this); char[] result = new char[startField.length]; for (int i = 0; i < result.length; i++) { result[i] = metadata.getFieldType(startField[i]); } return result; } } class RangeLookup implements Lookup{ private SortedSet<DataRecord> lookup; private RangeLookupTable lookupTable; private DataRecord tmpRecord; private int[] startField; private int[] endField; private RecordKey key; private DataRecord inRecord; private int[] keyFields; private SortedSet<DataRecord> subTable; private Iterator<DataRecord> subTableIterator; private DataRecord next; private RuleBasedCollator collator; private int[] comparison; private int numFound; private boolean[] startInclude; private boolean[] endInclude; RangeLookup(RangeLookupTable lookup, RecordKey key, DataRecord record){ this.lookupTable = lookup; tmpRecord=new DataRecord(lookupTable.getMetadata()); tmpRecord.init(); startField = lookupTable.getStartFields(); endField = lookupTable.getEndFields(); startInclude = lookupTable.getStartInclude(); endInclude = lookupTable.getEndInclude(); collator = lookupTable.getCollator(); this.lookup = lookupTable.lookupTable; this.key = key; this.inRecord = record; this.keyFields = key.getKeyFields(); } public RecordKey getKey() { return key; } public LookupTable getLookupTable() { return lookupTable; } public synchronized int getNumFound() { int alreadyFound = numFound; while (getNext() != null) {}; int tmp = numFound; subTableIterator = subTable.iterator(); for (int i=0;i<alreadyFound;i++){ getNext(); } return tmp; } public void seek() { if (inRecord == null) throw new IllegalStateException("No key data for performing lookup"); for (int i = 0; i < startField.length; i++){ tmpRecord.getField(startField[i]).setValue(inRecord.getField(keyFields[i])); tmpRecord.getField(endField[i]).setValue(inRecord.getField(keyFields[i])); } synchronized (lookup) { subTable = lookup.tailSet(tmpRecord); subTableIterator = subTable.iterator(); } numFound = 0; next = getNext(); } public void seek(DataRecord keyRecord) { inRecord = keyRecord; seek(); } private DataRecord getNext(){ DataRecord result; if (subTableIterator != null && subTableIterator.hasNext()) { result = subTableIterator.next(); }else{ return null; } //if value is not in interval try next for (int i=0;i<startField.length;i++){ comparison = compare(tmpRecord, result, i); if ((comparison[0] < 0 || (comparison[0] == 0 && !startInclude[i])) || (comparison[1] > 0 || (comparison[1] == 0 && !endInclude[i])) ) { return getNext(); } } numFound++; return result; } public boolean hasNext() { return next != null; } public DataRecord next() { if (next == null) { throw new NoSuchElementException(); } DataRecord tmp = next.duplicate(); next = getNext(); return tmp; } private int[] compare(DataRecord keyRecord, DataRecord lookupRecord, int keyFieldNo) { int startComp = 0, endComp = 0; //if start field of lookup record is null, start field of key record is always greater if (lookupRecord.getField(startField[keyFieldNo]).isNull()) { startComp = 1; } //if end field of lookup record is null, end field of key record is always smaller if (lookupRecord.getField(endField[keyFieldNo]).isNull()){ endComp = -1; } if (startComp != 1) {//lookup record's start field is not null if (collator != null && lookupRecord.getField(startField[keyFieldNo]).getMetadata().getType() == DataFieldMetadata.STRING_FIELD){ startComp = ((StringDataField)keyRecord.getField(startField[keyFieldNo])).compareTo( lookupRecord.getField(startField[keyFieldNo]), collator); }else{ startComp = keyRecord.getField(startField[keyFieldNo]).compareTo( lookupRecord.getField(startField[keyFieldNo])); } } if (endComp != -1) {//lookup record's end field is not null if (collator != null && lookupRecord.getField(endField[keyFieldNo]).getMetadata().getType() == DataFieldMetadata.STRING_FIELD){ endComp = ((StringDataField)keyRecord.getField(startField[keyFieldNo])).compareTo( lookupRecord.getField(endField[keyFieldNo]), collator); }else{ endComp = keyRecord.getField(endField[keyFieldNo]).compareTo( lookupRecord.getField(endField[keyFieldNo])); } } return new int[]{startComp, endComp}; } public void remove() { throw new UnsupportedOperationException("Method not supported!"); } } /** * Comparator for special records (defining range lookup table). * It compares given start and end fields of two records using RecordComparator class. * * @see RecordComparator * */ class IntervalRecordComparator implements Comparator<DataRecord>{ RecordComparator[] startComparator;//comparators for start fields int[] startFields; RecordComparator[] endComparator;//comparators for end fields int[] endFields; int startComparison; int endComparison; /** * Costructor * * @param metadata metadata of records, which defines lookup table * @param collator collator for comparing string data fields */ public IntervalRecordComparator(DataRecordMetadata metadata, int[] startFields, int[] endFields, RuleBasedCollator collator) { if (startFields.length != endFields.length) { throw new IllegalArgumentException("Number of start fields is diffrent then number of and fields!!!"); } this.startFields = startFields; this.endFields = endFields; startComparator = new RecordComparator[startFields.length]; endComparator = new RecordComparator[endFields.length]; for (int i=0;i<startComparator.length;i++){ startComparator[i] = new RecordComparator(new int[]{startFields[i]},collator); endComparator[i] = new RecordComparator(new int[]{endFields[i]},collator); } } public IntervalRecordComparator(DataRecordMetadata metadata, int[] startFields, int[] endFields) { this(metadata, startFields, endFields, null); } /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) * * Intervals are equal if their start and end points are equal. Null values are treated as "infinities". * Interval o2 is after interval o1 if o1 is subinterval of o2 or start of o2 is * after start of o1 and end of o2 is after end of o1: * startComparison endComparison intervalComparison * o1.start.compareTo(o2.start) o1.end.compareTo(o2.end)o1.compareTo(o2) * -1 -1 -1 * -1 0 1(o2 is subinterval of o1) * -1 1 1(o2 is subinterval of o1) * 0 -1 -1(o1 is subinterval of o2) * 0 0 0(equal) * 0 1 1(o2 is subinterval of o1) * 1 -1 -1(o1 is subinterval of o2) * 1 0 -1(o1 is subinterval of o2) * 1 1 1 */ public int compare(DataRecord o1, DataRecord o2) { for (int i=0;i<startComparator.length;i++){ if (o1.getField(startFields[i]).isNull() && o2.getField(startFields[i]).isNull()) { startComparison = 0; }else if (o1.getField(startFields[i]).isNull()) { startComparison = -1; }else if (o2.getField(startFields[i]).isNull()) { startComparison = 1; }else{ startComparison = startComparator[i].compare(o1, o2); } if (o1.getField(endFields[i]).isNull() && o2.getField(endFields[i]).isNull()) { endComparison = 0; }else if (o1.getField(endFields[i]).isNull()) { endComparison = 1; }else if (o2.getField(endFields[i]).isNull()){ endComparison = -1; }else{ endComparison = endComparator[i].compare(o1, o2); } if (endComparison < 0) return -1; if (!(startComparison == 0 && endComparison == 0) ){ if (startComparison > 0 && endComparison == 0) { return -1; }else{ return 1; } } } return 0; } }
package seedu.taskmanager.logic.commands; import java.util.List; import java.util.Optional; import seedu.taskmanager.commons.core.Messages; import seedu.taskmanager.commons.util.CollectionUtil; import seedu.taskmanager.logic.commands.exceptions.CommandException; import seedu.taskmanager.model.category.UniqueCategoryList; import seedu.taskmanager.model.task.EndDate; import seedu.taskmanager.model.task.EndTime; import seedu.taskmanager.model.task.ReadOnlyTask; import seedu.taskmanager.model.task.StartDate; import seedu.taskmanager.model.task.StartTime; import seedu.taskmanager.model.task.Task; import seedu.taskmanager.model.task.TaskName; import seedu.taskmanager.model.task.UniqueTaskList; // @@author A0142418L /** * Updates the details of an existing task in the task manager. */ public class UpdateCommand extends Command { public static final String COMMAND_WORD = "UPDATE"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Updates the details of the task identified " + "by the index number used in the last task listing. " + "Existing values will be overwritten by the input values.\n" + "Parameters: INDEX (must be a positive integer) [TASK] ON [DATE] FROM [STARTTIME] TO [ENDTIME]\n" + "Example: " + COMMAND_WORD + " 1 ON 04/03/17 FROM 1630 TO 1830"; public static final String MESSAGE_UPDATE_TASK_SUCCESS = "Updated Task: %1$s"; public static final String MESSAGE_NOT_UPDATED = "At least one field to edit must be provided."; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager."; public static final String EMPTY_FIELD = "EMPTY_FIELD"; private final int filteredTaskListIndex; private UpdateTaskDescriptor updateTaskDescriptor; private final Boolean isUpdateToDeadlineTask; /** * @param filteredTaskListIndex * the index of the task in the filtered task list to update * @param updateTaskDescriptor * details to update the task with */ public UpdateCommand(int filteredTaskListIndex, UpdateTaskDescriptor updateTaskDescriptor, Boolean isUpdateToDeadlineTask) { assert filteredTaskListIndex > 0; assert updateTaskDescriptor != null; // converts filteredTaskListIndex from one-based to zero-based. this.filteredTaskListIndex = filteredTaskListIndex - 1; this.updateTaskDescriptor = new UpdateTaskDescriptor(updateTaskDescriptor); this.isUpdateToDeadlineTask = isUpdateToDeadlineTask; } @Override public CommandResult execute() throws CommandException { // UpdateTaskDescriptor newUpdateTaskDescriptor = new // UpdateTaskDescriptor(); List<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (filteredTaskListIndex >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask taskToUpdate = lastShownList.get(filteredTaskListIndex); if (!isUpdateToDeadlineTask) { if ((isOnlyStartUpdated() || isOnlyEndUpdated()) && isToUpdateFloatingTask(taskToUpdate)) { throw new CommandException(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE)); } else { if (isOnlyStartUpdated()) { updateTaskDescriptor.setEndDate(Optional.of(taskToUpdate.getEndDate())); updateTaskDescriptor.setEndTime(Optional.of(taskToUpdate.getEndTime())); } else { if (isOnlyEndUpdated()) { updateTaskDescriptor.setStartDate(Optional.of(taskToUpdate.getStartDate())); updateTaskDescriptor.setStartTime(Optional.of(taskToUpdate.getStartTime())); } } } if ((isOnlyStartTimeUpdated() || isOnlyEndTimeUpdated()) && (isToUpdateFloatingTask(taskToUpdate) || isDeadlineTaskToUpdate(taskToUpdate))) { throw new CommandException(String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE)); } else { if (isOnlyEndTimeUpdated()) { updateTaskDescriptor.setStartTime(Optional.of(taskToUpdate.getStartTime())); updateTaskDescriptor.setStartDate(Optional.of(taskToUpdate.getStartDate())); updateTaskDescriptor.setEndDate(Optional.of(taskToUpdate.getEndDate())); } else { if (isOnlyStartTimeUpdated()) { updateTaskDescriptor.setEndTime(Optional.of(taskToUpdate.getEndTime())); updateTaskDescriptor.setStartDate(Optional.of(taskToUpdate.getStartDate())); updateTaskDescriptor.setEndDate(Optional.of(taskToUpdate.getEndDate())); } } } } if (isOnlyCategoriesUpdate() || isOnlyTaskNameUpdated()) { updateTaskDescriptor.setStartDate(Optional.of(taskToUpdate.getStartDate())); updateTaskDescriptor.setStartTime(Optional.of(taskToUpdate.getStartTime())); updateTaskDescriptor.setEndDate(Optional.of(taskToUpdate.getEndDate())); updateTaskDescriptor.setEndTime(Optional.of(taskToUpdate.getEndTime())); } Task updatedTask = createUpdatedTask(taskToUpdate, updateTaskDescriptor); try { model.updateTask(filteredTaskListIndex, updatedTask); } catch (UniqueTaskList.DuplicateTaskException dpe) { throw new CommandException(MESSAGE_DUPLICATE_TASK); } model.updateFilteredListToShowAll(); return new CommandResult(String.format(MESSAGE_UPDATE_TASK_SUCCESS, taskToUpdate)); } /** * Checks if only the task name field has been identified by user to be * updated To ensure that other task details like startTime startDate * endTime endDate are not lost * * @return true if only task name has been identified by user to be updated */ private boolean isOnlyTaskNameUpdated() { if (updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getTaskName().isPresent()) { return true; } else { return false; } } /** * Checks if only the category field has been identified by user to be * updated To ensure that other task details like startTime startDate * endTime endDate are not lost * * @return true if only categories are identified by user to be updated */ private boolean isOnlyCategoriesUpdate() { if (updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getCategories().isPresent()) { return true; } else { return false; } } private boolean isDeadlineTaskToUpdate(ReadOnlyTask taskToUpdate) { if (taskToUpdate.getStartDate().value.equals(EMPTY_FIELD) && taskToUpdate.getStartTime().value.equals(EMPTY_FIELD) && !taskToUpdate.getEndDate().value.equals(EMPTY_FIELD) && !taskToUpdate.getEndTime().value.equals(EMPTY_FIELD)) { return true; } else { return false; } } private boolean isOnlyStartTimeUpdated() { if (updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && !updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD)) { return true; } else { return false; } } private boolean isOnlyEndTimeUpdated() { if (updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && !updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD)) { return true; } else { return false; } } private boolean isToUpdateFloatingTask(ReadOnlyTask taskToUpdate) { if (taskToUpdate.getStartDate().value.equals(EMPTY_FIELD) && taskToUpdate.getStartTime().value.equals(EMPTY_FIELD) && taskToUpdate.getEndDate().value.equals(EMPTY_FIELD) && taskToUpdate.getEndTime().value.equals(EMPTY_FIELD)) { return true; } else { return false; } } private boolean isOnlyStartUpdated() { if (!updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && !updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD)) { return true; } else { return false; } } private boolean isOnlyEndUpdated() { if (updateTaskDescriptor.getStartDate().get().toString().equals(EMPTY_FIELD) && updateTaskDescriptor.getStartTime().get().toString().equals(EMPTY_FIELD) && !updateTaskDescriptor.getEndDate().get().toString().equals(EMPTY_FIELD) && !updateTaskDescriptor.getEndTime().get().toString().equals(EMPTY_FIELD)) { return true; } else { return false; } } /** * Creates and returns a {@code Task} with the details of {@code taskToEdit} * edited with {@code editTaskDescriptor}. */ private static Task createUpdatedTask(ReadOnlyTask taskToUpdate, UpdateTaskDescriptor updateTaskDescriptor) { assert taskToUpdate != null; TaskName updatedTaskName = updateTaskDescriptor.getTaskName().orElseGet(taskToUpdate::getTaskName); StartDate updatedStartDate = updateTaskDescriptor.getStartDate().orElseGet(taskToUpdate::getStartDate); StartTime updatedStartTime = updateTaskDescriptor.getStartTime().orElseGet(taskToUpdate::getStartTime); EndDate updatedEndDate = updateTaskDescriptor.getEndDate().orElseGet(taskToUpdate::getEndDate); EndTime updatedEndTime = updateTaskDescriptor.getEndTime().orElseGet(taskToUpdate::getEndTime); UniqueCategoryList updatedCategories = updateTaskDescriptor.getCategories() .orElseGet(taskToUpdate::getCategories); return new Task(updatedTaskName, updatedStartDate, updatedStartTime, updatedEndDate, updatedEndTime, false, updatedCategories); } /** * Stores the details to edit the task with. Each non-empty field value will * replace the corresponding field value of the task. */ public static class UpdateTaskDescriptor { private Optional<TaskName> taskname = Optional.empty(); private Optional<StartDate> startDate = Optional.empty(); private Optional<StartTime> startTime = Optional.empty(); private Optional<EndDate> endDate = Optional.empty(); private Optional<EndTime> endTime = Optional.empty(); private Optional<UniqueCategoryList> categories = Optional.empty(); public UpdateTaskDescriptor() { } public UpdateTaskDescriptor(UpdateTaskDescriptor toCopy) { this.taskname = toCopy.getTaskName(); this.startDate = toCopy.getStartDate(); this.startTime = toCopy.getStartTime(); this.endDate = toCopy.getEndDate(); this.endTime = toCopy.getEndTime(); this.categories = toCopy.getCategories(); } /** * Returns true if at least one field is updated. */ public boolean isAnyFieldUpdated() { return CollectionUtil.isAnyPresent(this.taskname, this.startDate, this.startTime, this.endDate, this.endTime, this.categories); } public void setTaskName(Optional<TaskName> taskname) { assert taskname != null; this.taskname = taskname; } public Optional<TaskName> getTaskName() { return taskname; } public void setStartDate(Optional<StartDate> startDate) { assert startDate != null; this.startDate = startDate; } public Optional<StartDate> getStartDate() { return startDate; } public void setStartTime(Optional<StartTime> startTime) { assert startTime != null; this.startTime = startTime; } public Optional<StartTime> getStartTime() { return startTime; } public void setEndDate(Optional<EndDate> endDate) { assert endDate != null; this.endDate = endDate; } public Optional<EndDate> getEndDate() { return endDate; } public void setEndTime(Optional<EndTime> endTime) { assert endTime != null; this.endTime = endTime; } public Optional<EndTime> getEndTime() { return endTime; } public void setCategories(Optional<UniqueCategoryList> categories) { assert categories != null; this.categories = categories; } public Optional<UniqueCategoryList> getCategories() { return categories; } } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc2619.PlyBot2017.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc2619.PlyBot2017.Robot; public class XboxDrive extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public XboxDrive() { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.driveTrain); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { double rightSpeed, leftSpeed; leftSpeed = -1*Robot.oi.getLeftJoystick().getRawAxis(1); rightSpeed = -1*Robot.oi.getRightJoystick().getRawAxis(5); Robot.driveTrain.run(leftSpeed, rightSpeed); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { // TODO: Use stop instead of run 0, 0 Robot.driveTrain.run(0, 0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
package zmaster587.advancedRocketry.util; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map.Entry; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import zmaster587.advancedRocketry.block.BlockPress; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.material.AllowedProducts; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.multiblock.TileMultiblockMachine; public class RecipeHandler { private List<Class<? extends TileMultiblockMachine>> machineList = new ArrayList<Class<? extends TileMultiblockMachine>>(); public void registerMachine(Class<? extends TileMultiblockMachine> clazz) { if(!machineList.contains(clazz)) machineList.add(clazz); } public void clearAllMachineRecipes() { for(Class<? extends TileMultiblockMachine> clazz : machineList) { RecipesMachine.getInstance().getRecipes(clazz).clear(); } } public void registerXMLRecipes() { //Load XML recipes LibVulpes.instance.loadXMLRecipe(TileCuttingMachine.class); LibVulpes.instance.loadXMLRecipe(TilePrecisionAssembler.class); LibVulpes.instance.loadXMLRecipe(TileChemicalReactor.class); LibVulpes.instance.loadXMLRecipe(TileCrystallizer.class); LibVulpes.instance.loadXMLRecipe(TileElectrolyser.class); LibVulpes.instance.loadXMLRecipe(TileElectricArcFurnace.class); LibVulpes.instance.loadXMLRecipe(TileLathe.class); LibVulpes.instance.loadXMLRecipe(TileRollingMachine.class); LibVulpes.instance.loadXMLRecipe(BlockPress.class); } public void registerAllMachineRecipes() { for(Class<? extends TileMultiblockMachine> clazz : machineList) try { clazz.newInstance().registerRecipes(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public void createAutoGennedRecipes(HashMap<AllowedProducts, HashSet<String>> modProducts) { //AutoGenned Recipes for(zmaster587.libVulpes.api.material.Material ore : MaterialRegistry.getAllMaterials()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("ORE")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); if(AllowedProducts.getProductByName("NUGGET").isOfType(ore.getAllowedProducts())) { ItemStack nugget = ore.getProduct(AllowedProducts.getProductByName("NUGGET")); nugget.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(nugget, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("INGOT")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("NUGGET").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("CRYSTAL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("CRYSTAL")), 300, 20, AllowedProducts.getProductByName("DUST").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("BOULE").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("BOULE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str, AllowedProducts.getProductByName("NUGGET").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("STICK").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) { for(String name : ore.getOreDictNames()) if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name)) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("STICK"),4), "x ", " x ", " x", 'x', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name)); RecipesMachine.getInstance().addRecipe(TileLathe.class, ore.getProduct(AllowedProducts.getProductByName("STICK"),2), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name); //ore.getProduct(AllowedProducts.getProductByName("INGOT"))); } } if(AllowedProducts.getProductByName("PLATE").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + oreDictNames)) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("PLATE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + oreDictNames); if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("PLATE"),4), 0, 0, AllowedProducts.getProductByName("BLOCK").name().toLowerCase(Locale.ENGLISH) + oreDictNames); } } } if(AllowedProducts.getProductByName("SHEET").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("SHEET")), 300, 200, AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + oreDictNames); } } if(AllowedProducts.getProductByName("COIL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("COIL")), "ooo", "o o", "ooo",'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } if(AllowedProducts.getProductByName("FAN").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("FAN")), "p p", " r ", "p p", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + str, 'r', AllowedProducts.getProductByName("STICK").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("GEAR").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("GEAR")), "sps", " r ", "sps", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + str, 's', AllowedProducts.getProductByName("STICK").name().toLowerCase(Locale.ENGLISH) + str, 'r', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts())) { ItemStack ingot = ore.getProduct(AllowedProducts.getProductByName("INGOT")); ingot.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(ingot, AllowedProducts.getProductByName("BLOCK").name().toLowerCase(Locale.ENGLISH) + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("BLOCK")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("DUST").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) { ItemStack stack = ore.getProduct(AllowedProducts.getProductByName("DUST")); stack.stackSize = 2; RecipesMachine.getInstance().addRecipe(BlockPress.class, stack, 0, 0, AllowedProducts.getProductByName("ORE").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("DUST")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); } } } //Handle vanilla integration if(zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood) { for(int i = 0; i < 4; i++) { RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, i), 80, 10, new ItemStack(Blocks.LOG,1, i)); } RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, 4), 80, 10, new ItemStack(Blocks.LOG2,1, 0)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, 5), 80, 10, new ItemStack(Blocks.LOG2,1, 1)); } //Handle items from other mods if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) { for(Entry<AllowedProducts, HashSet<String>> entry : modProducts.entrySet()) { if(entry.getKey() == AllowedProducts.getProductByName("PLATE")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("PLATE").isOfType(material.getAllowedProducts())) ) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, OreDictionary.getOres("plate" + str).get(0), 300, 20, "ingot" + str); } } } else if(entry.getKey() == AllowedProducts.getProductByName("STICK")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("STICK").isOfType(material.getAllowedProducts())) ) { //GT registers rods as sticks ItemStack stackToAdd = null; if(OreDictionary.doesOreNameExist("rod" + str) && OreDictionary.getOres("rod" + str).size() > 0) { stackToAdd = OreDictionary.getOres("rod" + str).get(0).copy(); stackToAdd.stackSize = 2; } else if(OreDictionary.doesOreNameExist("stick" + str) && OreDictionary.getOres("stick" + str).size() > 0) { stackToAdd = OreDictionary.getOres("stick" + str).get(0).copy(); stackToAdd.stackSize = 2; } else continue; RecipesMachine.getInstance().addRecipe(TileLathe.class, stackToAdd, 300, 20, "ingot" + str); } } } } } } }
package pitt.search.semanticvectors; import java.io.File; import java.io.IOException; import java.lang.Integer; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Logger; import org.apache.lucene.index.*; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorUtils; /** * Generates document vectors incrementally. * * @author Trevor Cohen, Dominic Widdows */ public class IncrementalDocVectors { private static final Logger logger = Logger.getLogger( IncrementalDocVectors.class.getCanonicalName()); // TODO: Refactor to make more depend on flag config as appropriate. private FlagConfig flagConfig; //private VectorType vectorType; //private int dimension; private VectorStore termVectorData; private IndexReader indexReader; //private String[] fieldsToIndex; private LuceneUtils lUtils; private String vectorFileName; private IncrementalDocVectors() {}; /** * Creates incremental doc vectors, getting everything it needs from a * TermVectorsFromLucene object and a Lucene Index directory, and writing to a named file. * * @param termVectorData Has all the information needed to create doc vectors. * @param flagConfig Any extra flag configurations * @param indexDir Directory of the Lucene Index used to generate termVectorData * @param vectorStoreName Filename for the document vectors */ public static void createIncrementalDocVectors( VectorStore termVectorData, FlagConfig flagConfig, String indexDir, String vectorStoreName) throws IOException { IncrementalDocVectors incrementalDocVectors = new IncrementalDocVectors(); incrementalDocVectors.flagConfig = flagConfig; incrementalDocVectors.termVectorData = termVectorData; incrementalDocVectors.indexReader = IndexReader.open(FSDirectory.open(new File(indexDir))); incrementalDocVectors.vectorFileName = VectorStoreUtils.getStoreFileName(vectorStoreName, flagConfig); if (incrementalDocVectors.lUtils == null) { incrementalDocVectors.lUtils = new LuceneUtils(flagConfig); } incrementalDocVectors.trainIncrementalDocVectors(); } private void trainIncrementalDocVectors() throws IOException { int numdocs = indexReader.numDocs(); // Open file and write headers. File vectorFile = new File(vectorFileName); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(new File(parentPath)); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName()); VerbatimLogger.info("Writing vectors incrementally to file " + vectorFile + " ... "); // Write header giving number of dimension for all vectors. outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); Vector docVector = null; ArrayList<Vector> toBeSuperposed = null; ArrayList<Double> superpositionWeights = null; // Iterate through documents. for (int dc = 0; dc < numdocs; dc++) { // Output progress counter. if ((dc > 0) && ((dc % 10000 == 0) || ( dc < 10000 && dc % 1000 == 0 ))) { VerbatimLogger.info("Processed " + dc + " documents ... "); } String docID = Integer.toString(dc); // Use filename and path rather than Lucene index number for document vector. if (this.indexReader.document(dc).getField(flagConfig.docidfield()) != null) { docID = this.indexReader.document(dc).getField(flagConfig.docidfield()).stringValue(); if (docID.length() == 0) { logger.warning("Empty document name!!! This will cause problems ..."); logger.warning("Please set -docidfield to a nonempty field in your Lucene index."); } } docVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension()); for (String fieldName: flagConfig.contentsfields()) { TermFreqVector vex = indexReader.getTermFreqVector(dc, fieldName); if (vex != null) { // Get terms in document and term frequencies. String[] terms = vex.getTerms(); int[] freqs = vex.getTermFrequencies(); for (int b = 0; b < freqs.length; ++b) { String termString = terms[b]; int freq = freqs[b]; float localweight = freq; float globalweight = lUtils.getGlobalTermWeight(new Term(fieldName,termString)); float fieldweight = 1; if (flagConfig.fieldweight()) { //field weight: 1/sqrt(number of terms in field) fieldweight = (float) (1/Math.sqrt(terms.length)); } // Add contribution from this term, excluding terms that // are not represented in termVectorData. try { Vector termVector = termVectorData.getVector(termString); if (termVector != null && termVector.getDimension() > 0) { docVector.superpose(termVector, localweight * globalweight * fieldweight, null); } } catch (NullPointerException npe) { // Don't normally print anything - too much data! logger.finest("term " + termString + " not represented"); } } } } // All fields in document have been processed. // Write out documentID and normalized vector. outputStream.writeString(docID); docVector.normalize(); docVector.writeToLuceneStream(outputStream); } // Finish iterating through documents. VerbatimLogger.info("Finished writing vectors.\n"); outputStream.flush(); outputStream.close(); fsDirectory.close(); } public static void main(String[] args) throws Exception { FlagConfig flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; // Only two arguments should remain, the name of the initial term vectors and the // path to the Lucene index. if (args.length != 2) { throw (new IllegalArgumentException("After parsing command line flags, there were " + args.length + " arguments, instead of the expected 2.")); } String vectorFile = args[0].replaceAll("\\.bin","")+"_docvectors.bin"; VectorStoreRAM vsr = new VectorStoreRAM(flagConfig); vsr.initFromFile(args[0]); logger.info("Minimum frequency = " + flagConfig.minfrequency()); logger.info("Maximum frequency = " + flagConfig.maxfrequency()); logger.info("Number non-alphabet characters = " + flagConfig.maxnonalphabetchars()); logger.info("Contents fields are: " + Arrays.toString(flagConfig.contentsfields())); createIncrementalDocVectors(vsr, flagConfig, args[1], vectorFile); } }
package protocolsupport.api.chat.components; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import protocolsupport.api.chat.modifiers.ClickAction; import protocolsupport.api.chat.modifiers.HoverAction; import protocolsupport.api.chat.modifiers.Modifier; import protocolsupport.protocol.transformer.utils.LegacyUtils; public abstract class BaseComponent { private List<BaseComponent> siblings = new ArrayList<BaseComponent>(); private Modifier modifier; private ClickAction clickAction; private HoverAction hoverAction; private String clickInsertion; public boolean isSimple() { return siblings.isEmpty() && getModifier().isEmpty() && clickAction == null && hoverAction == null && clickInsertion == null; } public List<BaseComponent> getSiblings() { return Collections.unmodifiableList(this.siblings); } public void clearSiblings() { this.siblings.clear(); } public void addSibling(BaseComponent sibling) { this.siblings.add(sibling); } public void addSiblings(BaseComponent... siblings) { for (BaseComponent sibling : siblings) { this.siblings.add(sibling); } } public void addSiblings(Collection<BaseComponent> siblings) { this.siblings.addAll(siblings); } public Modifier getModifier() { if (this.modifier == null) { this.modifier = new Modifier(); } return this.modifier; } public void setModifier(Modifier modifier) { this.modifier = modifier; } public ClickAction getClickAction() { return clickAction; } public void setClickAction(ClickAction clickAction) { this.clickAction = clickAction; } public HoverAction getHoverAction() { return hoverAction; } public void setHoverAction(HoverAction hoverAction) { this.hoverAction = hoverAction; } public String getClickInsertion() { return clickInsertion; } public void setClickInsertion(String clickInsertion) { this.clickInsertion = clickInsertion; } public abstract String getValue(); public String toLegacyText() { return LegacyUtils.toText(this); } }
package keel.Algorithms.Discretizers.ecpsd; import weka.classifiers.bayes.NaiveBayes; import weka.core.DenseInstance; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; public class Chromosome implements Comparable, Serializable { private boolean [] individual; // Boolean array selecting cutpoints from a list of cutpoints private boolean n_e; // Indicates whether this chromosome has been evaluated or not float fitness;// Fitness associated to the cut points represented by the boolean array int n_cutpoints; // Fitness associated to the dataset, it indicates the number of cutpoints selected int inconsistencies; float perc_err; /** * Default constructor */ public Chromosome () { } /** * Creates a CHC chromosome from another chromosome (copies a chromosome) * * @param orig Original chromosome that is going to be copied */ public Chromosome (Chromosome orig) { individual = new boolean [orig.individual.length]; for (int i=0; i<orig.individual.length; i++) { individual[i] = orig.individual[i]; } n_e = orig.n_e; fitness = orig.fitness; n_cutpoints = orig.n_cutpoints; } /** * Creates a random CHC_Chromosome of specified size * * @param size Size of the new chromosome */ public Chromosome (int size) { individual = new boolean [size]; Random rnd = new Random(); for (int i=0; i<size; i++) { float u = rnd.nextFloat(); if (u < 0.5) { individual[i] = false; } else { individual[i] = true; } } n_e = true; fitness = .0f; n_cutpoints = size; } /** * Creates a CHC_Chromosome of specified size with all its elements set to the specified value * * @param size Size of the new chromosome * @param value Value that all elements of the chromosome are going to have */ public Chromosome (int size, boolean value) { individual = new boolean [size]; for (int i=0; i<size; i++) { individual[i] = value; } n_e = true; fitness = .0f; n_cutpoints = size; } /** * Creates a CHC chromosome from a boolean array representing a chromosome * * @param data boolean array representing a chromosome */ public Chromosome (boolean data[]) { individual = new boolean [data.length]; for (int i=0; i<data.length; i++) { individual[i] = data[i]; } n_e = true; fitness = .0f; n_cutpoints = data.length; } /** * Creates a CHC chromosome from another chromosome using the CHC diverge procedure * * @param orig Best chromosome of the population that is going to be used to create another chromosome * @param r R factor of diverge */ public Chromosome (Chromosome orig, float r) { individual = new boolean [orig.individual.length]; Random rnd = new Random(); for (int i=0; i<orig.individual.length; i++) { if (rnd.nextFloat() < r) { individual[i] = !orig.individual[i]; } else { individual[i] = orig.individual[i]; } } n_e = true; fitness = .0f; n_cutpoints = orig.n_cutpoints; } /** * Creates a CHC chromosome from another chromosome using the CHC diverge procedure * * @param orig Best chromosome of the population that is going to be used to create another chromosome * @param r R factor of diverge */ public Chromosome (Chromosome orig, float r, float prob0to1Div) { individual = new boolean [orig.individual.length]; Random rnd = new Random(); for (int i=0; i<orig.individual.length; i++) { if (rnd.nextFloat() < r) { if (rnd.nextFloat() < prob0to1Div) { individual[i] = true; } else { individual[i] = false; } } else { individual[i] = orig.individual[i]; } } n_e = true; fitness = .0f; n_cutpoints = individual.length; } /** * Checks if the current chromosome has been evaluated or not. * * @return true, if this chromosome was evaluated previously; * false, if it has never been evaluated */ public boolean not_eval() { return n_e; } /** * Evaluates this chromosome, computing the fitness of the chromosome * * @param dataset Training dataset used in this algorithm * @param all_cut_points Proposed cut points that are selected by the CHC chromosome * @param alpha Coefficient for the number of cut points importance * @param beta Coefficient for the number of inconsistencies importance */ public void evaluate (weka.core.Instances base, float[][] dataset, float [][] cut_points, float alpha, float beta) { weka.core.Instances datatrain = new weka.core.Instances(base); int nInputs = dataset[0].length - 1; // Obtain the cut points for this chromosome ArrayList<Float[]> selected_points = new ArrayList<Float[]>(cut_points.length); int acc = 0, n_selected_cut_points = 0; for (int i=0; i < cut_points.length; i++) { ArrayList<Float> arr = new ArrayList<Float>(); for (int j = 0; j < cut_points[i].length; j++) { if (individual[acc + j]){ arr.add(cut_points[i][j]); n_selected_cut_points++; } } Float[] aux = new Float[arr.size()]; selected_points.add(arr.toArray(aux)); acc += cut_points[i].length; } /*Instance adaptation to the WEKA format*/ int j; for (int i=0; i < dataset.length; i++) { float [] sample = dataset[i]; double[] tmp = new double[sample.length]; for (j=0; j < nInputs; j++) tmp[j] = discretize (sample[j], selected_points.get(j)); tmp[j] = sample[nInputs]; // the class DenseInstance inst = new DenseInstance(1.0, tmp); datatrain.add(inst); } /* Use unpruned C4.5 to detect errors * Second type of evaluator in precision: C45 classifier * c45er is the error counter * */ //long t_ini = System.currentTimeMillis(); /*double c45er = 0; J48 baseTree = new J48(); try { baseTree.buildClassifier(datatrain); } catch (Exception ex) { ex.printStackTrace(); } for (int i=0; i < datatrain.numInstances(); i++) { try { if ((int)baseTree.classifyInstance(datatrain.instance(i)) != dataset[i][nInputs]) { c45er++; } } catch (Exception ex) { ex.printStackTrace(); } }*/ /* Use simple Naive Bayes to detect errors * Third type of evaluator in precision: Naive Bayes classifier * nber is the error counter * */ int nber = 0; NaiveBayes baseBayes = new NaiveBayes(); try { baseBayes.buildClassifier(datatrain); } catch (Exception ex) { ex.printStackTrace(); } for (int i=0; i < datatrain.numInstances(); i++) { try { if ((int)baseBayes.classifyInstance(datatrain.instance(i)) != dataset[i][nInputs]) { nber++; } } catch (Exception ex) { ex.printStackTrace(); } } /*long t_fin = System.currentTimeMillis(); long t_exec = t_fin - t_ini; long hours = t_exec / 3600000; long rest = t_exec % 3600000; long minutes = rest / 60000; rest %= 60000; long seconds = rest / 1000; rest %= 1000; System.out.println("Wrapper execution Time: " + hours + ":" + minutes + ":" + seconds + "." + rest); */ float p_err = (float) nber / datatrain.numInstances(); //float proportion = (double) (dataset.getnData() * 2) / (double) initial_cut_points; float perc_points= (float) n_selected_cut_points / individual.length; /* fitness = alpha * ((double) n_selected_cut_points / (double) initial_cut_points) + beta * proportion * ((double) incons / (double) dataset.getnData()) ;*/ fitness = alpha * perc_points + beta * p_err; n_cutpoints = n_selected_cut_points; perc_err = p_err; //System.out.println(fitness); } /** * Obtains the fitness associated to this CHC_Chromosome, its fitness measure * * @return the fitness associated to this CHC_Chromosome */ public float getFitness() { return fitness; } /** * Obtains the Hamming distance between this and another chromosome * * @param ch_b Other chromosome that we want to compute the Hamming distance to * @return the Hamming distance between this and another chromosome */ public int hammingDistance (Chromosome ch_b) { int i; int dist = 0; if (individual.length != ch_b.individual.length) { System.err.println("The CHC Chromosomes have different size so we cannot combine them"); System.exit(-1); } for (i=0; i<individual.length; i++){ if (individual[i] != ch_b.individual[i]) { dist++; } } return dist; } /** * Obtains a new pair of CHC_chromosome from this chromosome and another chromosome, swapping half the differing bits at random * * @param ch_b Other chromosome that we want to use to create another chromosome * @return a new pair of CHC_chromosome from this chromosome and the given chromosome */ public ArrayList <Chromosome> createDescendants (Chromosome ch_b) { int i, pos; int different_values, n_swaps; int [] different_position; Chromosome descendant1 = new Chromosome(); Chromosome descendant2 = new Chromosome(); ArrayList <Chromosome> descendants; if (individual.length != ch_b.individual.length) { System.err.println("The CHC Chromosomes have different size so we cannot combine them"); System.exit(-1); } different_position = new int [individual.length]; descendant1.individual = new boolean[individual.length]; descendant2.individual = new boolean[individual.length]; different_values = 0; for (i=0; i<individual.length; i++){ descendant1.individual[i] = individual[i]; descendant2.individual[i] = ch_b.individual[i]; if (individual[i] != ch_b.individual[i]) { different_position[different_values] = i; different_values++; } } n_swaps = different_values/2; if ((different_values > 0) && (n_swaps == 0)) n_swaps = 1; Random rnd = new Random(); for (int j=0; j<n_swaps; j++) { different_values pos = rnd.nextInt(different_values + 1); boolean tmp = descendant1.individual[different_position[pos]]; descendant1.individual[different_position[pos]] = descendant2.individual[different_position[pos]]; descendant2.individual[different_position[pos]] = tmp; different_position[pos] = different_position[different_values]; } descendant1.n_e = true; descendant2.n_e = true; descendant1.fitness = .0f; descendant2.fitness = .0f; descendant1.n_cutpoints = individual.length; descendant2.n_cutpoints = individual.length; descendants = new ArrayList <Chromosome> (2); descendants.add(descendant1); descendants.add(descendant2); return descendants; } /** * Obtains a new pair of CHC_chromosome from this chromosome and another chromosome, * swapping half the differing bits at random * * @param ch_b Other chromosome that we want to use to create another chromosome * @return a new pair of CHC_chromosome from this chromosome and the given chromosome */ public ArrayList <Chromosome> createDescendants (Chromosome ch_b, float prob0to1Rec) { int i; Chromosome descendant1 = new Chromosome(); Chromosome descendant2 = new Chromosome(); ArrayList <Chromosome> descendants; if (individual.length != ch_b.individual.length) { System.err.println("The CHC Chromosomes have different size so we cannot combine them"); System.exit(-1); } descendant1.individual = new boolean[individual.length]; descendant2.individual = new boolean[individual.length]; for (i=0; i<individual.length; i++){ descendant1.individual[i] = individual[i]; descendant2.individual[i] = ch_b.individual[i]; Random rnd = new Random(); if ((individual[i] != ch_b.individual[i]) && rnd.nextFloat() < 0.5) { if (descendant1.individual[i]) descendant1.individual[i] = false; else if (rnd.nextFloat() < prob0to1Rec) descendant1.individual[i] = true; if (descendant2.individual[i]) descendant2.individual[i] = false; else if (rnd.nextFloat() < prob0to1Rec) descendant1.individual[i] = true; } } descendant1.n_e = true; descendant2.n_e = true; descendant1.fitness = .0f; descendant2.fitness = .0f; descendant1.n_cutpoints = individual.length; descendant2.n_cutpoints = individual.length; descendants = new ArrayList <Chromosome> (2); descendants.add(descendant1); descendants.add(descendant2); return descendants; } /** * Obtain the boolean array representing the CHC Chromosome * * @return boolean array selecting rules from a rule base */ public boolean [] getIndividual () { return individual; } /** * Obtains the discretized value of a real data considering the * cut points vector given and the individual information (uses binary search). * * * @param value Real value we want to discretize according to the considered cutpoints (must be sorted in ascending order) * @param cp Cut points used to discretize (selected by the chromosome) * @return a discrete integer value */ private int discretize(float value, Float[] cp) { if(cp == null) return 0; // No boundary points int ipoint = Arrays.binarySearch(cp, value); if(ipoint < 0) return Math.abs(ipoint) - 1; else return ipoint; } public String toString() { String output = ""; for (int i=0; i<individual.length; i++) { if (individual[i]) { output = output + "1 "; } else { output = output + "0 "; } } return (output); } /** * Compares this object with the specified object for order, according to the fitness measure * * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object */ public int compareTo (Object aThat) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if (this == aThat) return EQUAL; final Chromosome that = (Chromosome)aThat; if (this.fitness < that.fitness) return BEFORE; if (this.fitness > that.fitness) return AFTER; if (this.n_cutpoints < that.n_cutpoints) return AFTER; if (this.n_cutpoints > that.n_cutpoints) return BEFORE; return EQUAL; } }
package ru.thewizardplusplus.wizardbudget; import java.text.*; import java.util.*; import org.json.*; import android.content.*; import android.database.*; import android.database.sqlite.*; import android.net.*; import android.webkit.*; public class SpendingManager { public SpendingManager(Context context) { this.context = context; } public double calculateSpendingsSum() { SQLiteDatabase database = Utils.getDatabase(context); Cursor cursor = database.query( "spendings", new String[]{"ROUND(SUM(amount), 2)"}, null, null, null, null, null ); double spendings_sum = 0.0; boolean moved = cursor.moveToFirst(); if (moved) { spendings_sum = cursor.getDouble(0); } database.close(); return spendings_sum; } @JavascriptInterface public String getSpendingsSum() { double spendings_sum = calculateSpendingsSum(); return String.valueOf(spendings_sum); } @JavascriptInterface public String getAllSpendings() { SQLiteDatabase database = Utils.getDatabase(context); Cursor spendings_cursor = database.query( "spendings", new String[]{"_id", "timestamp", "amount", "comment"}, null, null, null, null, "timestamp DESC, _id DESC" ); JSONArray spendings = new JSONArray(); boolean moved = spendings_cursor.moveToFirst(); while (moved) { try { JSONObject spending = new JSONObject(); spending.put("id", spendings_cursor.getDouble(0)); long timestamp = spendings_cursor.getLong(1); spending.put("timestamp", String.valueOf(timestamp)); spending.put("date", formatDate(timestamp)); spending.put("time", formatTime(timestamp)); spending.put("amount", spendings_cursor.getDouble(2)); String comment = spendings_cursor.getString(3); spending.put("comment", comment); boolean has_credit_card_tag = false; String credit_card_tag = Settings .getCurrent(context) .getCreditCardTag(); if (!credit_card_tag.isEmpty()) { String[] tags = comment.split(","); for (String tag: tags) { if (tag.trim().equals(credit_card_tag)) { has_credit_card_tag = true; break; } } } spending.put("has_credit_card_tag", has_credit_card_tag); spendings.put(spending); } catch (JSONException exception) {} moved = spendings_cursor.moveToNext(); } database.close(); return spendings.toString(); } @JavascriptInterface public String getSpendingsFromSms() { Uri uri = Uri.parse("content://sms/inbox"); Cursor cursor = context.getContentResolver().query( uri, null, null, null, "date DESC" ); JSONArray spendings = new JSONArray(); if (cursor.moveToFirst()) { do { long timestamp = 0; try { String timestamp_string = cursor .getString(cursor.getColumnIndexOrThrow("date")) .toString(); timestamp = Long.valueOf(timestamp_string) / 1000L; } catch (NumberFormatException exception) { continue; } String number = cursor .getString(cursor.getColumnIndexOrThrow("address")) .toString(); String text = cursor .getString(cursor.getColumnIndexOrThrow("body")) .toString(); SmsData sms_data = Utils.getSpendingFromSms( context, number, text ); if (sms_data == null) { continue; } try { JSONObject spending = new JSONObject(); spending.put("timestamp", timestamp); spending.put("date", formatDate(timestamp)); spending.put("time", formatTime(timestamp)); spending.put("amount", sms_data.getSpending()); spending.put("residue", sms_data.getResidue()); spendings.put(spending); } catch (JSONException exception) { continue; } } while (cursor.moveToNext()); } cursor.close(); return spendings.toString(); } @JavascriptInterface public String getSpendingTags() { JSONArray tags = new JSONArray(); List<String> tag_list = getTagList(); for (String tag: tag_list) { tags.put(tag); } return tags.toString(); } @JavascriptInterface public String getPrioritiesTags() { Map<String, Long> tag_map = new HashMap<String, Long>(); List<String> tag_list = getTagList(); for (String tag: tag_list) { if (tag_map.containsKey(tag)) { tag_map.put(tag, tag_map.get(tag) + 1L); } else { tag_map.put(tag, 1L); } } JSONObject serialized_tag_map = new JSONObject(); try { for (Map.Entry<String, Long> entry: tag_map.entrySet()) { serialized_tag_map.put(entry.getKey(), entry.getValue()); } } catch (JSONException exception) {} return serialized_tag_map.toString(); } @JavascriptInterface public String getStatsSum(int number_of_last_days, String prefix) { SQLiteDatabase database = Utils.getDatabase(context); String prefix_length = String.valueOf(prefix.length()); Cursor spendings_cursor = database.query( "spendings", new String[]{"ROUND(SUM(amount), 2)"}, "amount > 0 " + "AND date(timestamp, 'unixepoch')" + ">= date(" + "'now'," + "'-" + String.valueOf(Math.abs(number_of_last_days)) + " days'" + ")" + "AND comment LIKE " + DatabaseUtils.sqlEscapeString(prefix + "%") + "AND (" + prefix_length + " == 0 " + "OR length(comment) == " + prefix_length + " " + "OR substr(comment, " + prefix_length + " + 1, 1) == ','" + ")", null, null, null, null ); double spendings_sum = 0.0; boolean moved = spendings_cursor.moveToFirst(); if (moved) { spendings_sum = spendings_cursor.getDouble(0); } return String.valueOf(spendings_sum); } @JavascriptInterface public String getStats(int number_of_last_days, String prefix) { SQLiteDatabase database = Utils.getDatabase(context); int prefix_length = prefix.length(); String prefix_length_in_string = String.valueOf(prefix_length); Cursor spendings_cursor = database.query( "spendings", new String[]{"comment", "amount"}, "amount > 0 " + "AND date(timestamp, 'unixepoch')" + ">= date(" + "'now'," + "'-" + String.valueOf(Math.abs(number_of_last_days)) + " days'" + ")" + "AND comment LIKE " + DatabaseUtils.sqlEscapeString(prefix + "%") + "AND (" + prefix_length_in_string + " == 0 " + "OR length(comment) == " + prefix_length_in_string + " " + "OR substr(" + "comment," + prefix_length_in_string + " + 1," + "1" + ") == ','" + ")", null, null, null, null ); Map<String, Double> spendings = new HashMap<String, Double>(); boolean moved = spendings_cursor.moveToFirst(); while (moved) { String comment = spendings_cursor.getString(0); if (prefix_length != 0) { if (comment.length() > prefix_length) { comment = comment.substring(prefix_length + 1).trim(); } else if (comment.length() == prefix_length) { comment = ""; } } if (!comment.isEmpty()) { int separator_index = comment.indexOf(","); if (separator_index != -1) { comment = comment.substring(0, separator_index).trim(); } } double amount = spendings_cursor.getDouble(1); if (spendings.containsKey(comment)) { spendings.put(comment, spendings.get(comment) + amount); } else { spendings.put(comment, amount); } moved = spendings_cursor.moveToNext(); } JSONArray serialized_spendings = new JSONArray(); String empty_comment_replacement = UUID.randomUUID().toString(); for (Map.Entry<String, Double> entry: spendings.entrySet()) { try { JSONObject spending = new JSONObject(); String comment = entry.getKey(); if (comment.isEmpty()) { comment = empty_comment_replacement; spending.put("is_rest", true); } else { spending.put("is_rest", false); } spending.put("tag", comment); double amount = entry.getValue(); spending.put("sum", amount); serialized_spendings.put(spending); } catch (JSONException exception) {} } database.close(); return serialized_spendings.toString(); } @JavascriptInterface public void createSpending(double amount, String comment) { ContentValues values = new ContentValues(); long current_timestamp = resetSeconds( System.currentTimeMillis() / 1000L ); values.put("timestamp", current_timestamp); values.put("amount", amount); values.put("comment", comment); SQLiteDatabase database = Utils.getDatabase(context); database.insert("spendings", null, values); database.close(); } @JavascriptInterface public void updateSpending( int id, String date, String time, double amount, String comment ) { try { String formatted_timestamp = date + " " + time + ":00"; SimpleDateFormat timestamp_format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US ); Date parsed_timestamp = timestamp_format.parse( formatted_timestamp ); long timestamp = parsed_timestamp.getTime() / 1000L; ContentValues values = new ContentValues(); values.put("timestamp", timestamp); values.put("amount", amount); values.put("comment", comment); SQLiteDatabase database = Utils.getDatabase(context); database.update( "spendings", values, "_id = ?", new String[]{String.valueOf(id)} ); database.close(); } catch (java.text.ParseException exception) {} } @JavascriptInterface public void deleteSpending(int id) { SQLiteDatabase database = Utils.getDatabase(context); database.delete( "spendings", "_id = ?", new String[]{String.valueOf(id)} ); database.close(); } @JavascriptInterface public void importSms(String sms_data) { String sql = ""; double residue = 0.0; boolean residue_found_tryed = false; String credit_card_tag = Settings.getCurrent(context).getCreditCardTag(); try { JSONArray spendings = new JSONArray(sms_data); for (int i = 0; i < spendings.length(); i++) { if (!sql.isEmpty()) { sql += ","; } JSONObject spending = spendings.getJSONObject(i); long timestamp = resetSeconds(spending.getLong("timestamp")); double amount = spending.getDouble("amount"); if (!residue_found_tryed) { residue = spending.getDouble("residue"); residue_found_tryed = true; } String comment = amount >= 0.0 ? Settings.getCurrent(context).getSmsSpendingComment() : Settings.getCurrent(context).getSmsIncomeComment(); if (!comment.isEmpty() && !credit_card_tag.isEmpty()) { comment += ", "; } comment += credit_card_tag; sql += "(" + String.valueOf(timestamp) + "," + String.valueOf(amount) + "," + DatabaseUtils.sqlEscapeString(comment) + ")"; } } catch (JSONException exception) {} if (!sql.isEmpty()) { SQLiteDatabase database = Utils.getDatabase(context); database.execSQL( "INSERT INTO spendings" + "(timestamp, amount, comment)" + "VALUES" + sql ); if (residue != 0.0) { Date current_date = new Date(); long timestamp = resetSeconds(current_date.getTime() / 1000L); double spendings_sum = calculateSpendingsSum(); double correction = -1 * residue - spendings_sum; String comment = ""; if (correction < 0) { comment = Settings.getCurrent(context).getSmsPositiveCorrectionComment(); } else { comment = Settings.getCurrent(context).getSmsNegativeCorrectionComment(); } if (!comment.isEmpty() && !credit_card_tag.isEmpty()) { comment += ", "; } comment += credit_card_tag; database.execSQL( "INSERT INTO spendings" + "(timestamp, amount, comment)" + "VALUES (" + String.valueOf(timestamp) + "," + String.valueOf(correction) + "," + DatabaseUtils.sqlEscapeString(comment) + ")" ); } database.close(); if (Settings.getCurrent(context).isSmsImportNotification()) { Date current_date = new Date(); DateFormat notification_timestamp_format = DateFormat .getDateTimeInstance( DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US ); String notification_timestamp = notification_timestamp_format .format(current_date); Utils.showNotification( context, context.getString(R.string.app_name), "SMS imported at " + notification_timestamp + ".", null ); } } } private Context context; private String formatDate(long timestamp) { Date date = new Date(timestamp * 1000L); DateFormat date_format = DateFormat.getDateInstance( DateFormat.DEFAULT, Locale.US ); return date_format.format(date); } private String formatTime(long timestamp) { Date date = new Date(timestamp * 1000L); DateFormat date_format = DateFormat.getTimeInstance( DateFormat.DEFAULT, Locale.US ); return date_format.format(date); } private List<String> getTagList() { SQLiteDatabase database = Utils.getDatabase(context); Cursor spendings_cursor = database.query( "spendings", new String[]{"comment"}, null, null, null, null, null ); List<String> tags = new ArrayList<String>(); boolean moved = spendings_cursor.moveToFirst(); while (moved) { String comment = spendings_cursor.getString(0); if (!comment.isEmpty()) { String[] comment_parts = comment.split(","); for (String part: comment_parts) { String trimmed_part = part.trim(); if (!trimmed_part.isEmpty()) { tags.add(trimmed_part); } } } moved = spendings_cursor.moveToNext(); } database.close(); return tags; } long resetSeconds(long timestamp) { return timestamp / 60 * 60; } }
package net.java.sip.communicator.impl.gui.main.call; import java.awt.*; import java.lang.ref.*; import java.text.*; import java.util.*; import java.util.List; import java.util.regex.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.plugin.desktoputil.transparent.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.contactsource.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.media.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import net.java.sip.communicator.util.account.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.codec.*; import org.jitsi.service.neomedia.device.*; import org.jitsi.service.neomedia.format.*; import org.jitsi.service.resources.*; import org.jitsi.util.*; /** * The <tt>CallManager</tt> is the one that handles calls. It contains also * the "Call" and "Hang up" buttons panel. Here are handles incoming and * outgoing calls from and to the call operation set. * * @author Yana Stamcheva * @author Lyubomir Marinov * @author Boris Grozev */ public class CallManager { /** * The <tt>Logger</tt> used by the <tt>CallManager</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(CallManager.class); /** * The name of the property which indicates whether the user should be * warned when starting a desktop sharing session. */ private static final String desktopSharingWarningProperty = "net.java.sip.communicator.impl.gui.main" + ".call.SHOW_DESKTOP_SHARING_WARNING"; /** * The name of the property which indicates whether the preferred provider * will be used when calling UIContact (call history). */ private static final String IGNORE_PREFERRED_PROVIDER_PROP = "net.java.sip.communicator.impl.gui.main" + ".call.IGNORE_PREFERRED_PROVIDER_PROP"; /** * The <tt>CallPanel</tt>s opened by <tt>CallManager</tt> (because * <tt>CallContainer</tt> does not give access to such lists.) */ private static final Map<CallConference, CallPanel> callPanels = new HashMap<CallConference, CallPanel>(); /** * A map of active outgoing calls per <tt>UIContactImpl</tt>. */ private static Map<Call, UIContactImpl> uiContactCalls; /** * The group of notifications dedicated to missed calls. */ private static UINotificationGroup missedCallGroup; /** * A <tt>CallListener</tt>. */ public static class GuiCallListener extends SwingCallListener { /** * Maps for incoming call handlers. The handlers needs to be created * in the protocol thread while their method * incomingCallReceivedInEventDispatchThread will be called on EDT. * On the protocol thread a call state changed listener is added, * if this is done on the EDT there is a almost no gap between incoming * CallEvent and call state changed when doing auto answer and we * end up with call answered and dialog for incoming call. */ private Map<CallEvent,WeakReference<IncomingCallHandler>> inCallHandlers = Collections.synchronizedMap( new WeakHashMap<CallEvent, WeakReference<IncomingCallHandler>>()); /** * Delivers the <tt>CallEvent</tt> in the protocol thread. */ public void incomingCallReceived(CallEvent ev) { inCallHandlers.put( ev, new WeakReference<IncomingCallHandler>( new IncomingCallHandler(ev.getSourceCall()))); super.incomingCallReceived(ev); } /** * Implements {@link CallListener#incomingCallReceived(CallEvent)}. When * a call is received, creates a <tt>ReceivedCallDialog</tt> and plays * the ring phone sound to the user. * * @param ev the <tt>CallEvent</tt> */ @Override public void incomingCallReceivedInEventDispatchThread(CallEvent ev) { WeakReference<IncomingCallHandler> ihRef = inCallHandlers.remove(ev); if(ihRef != null) { ihRef.get().incomingCallReceivedInEventDispatchThread(ev); } } /** * Implements CallListener.callEnded. Stops sounds that are playing at * the moment if there're any. Removes the <tt>CallPanel</tt> and * disables the hang-up button. * * @param ev the <tt>CallEvent</tt> which specifies the <tt>Call</tt> * that has ended */ @Override public void callEndedInEventDispatchThread(CallEvent ev) { CallConference callConference = ev.getCallConference(); closeCallContainerIfNotNecessary(callConference); /* * Notify the existing CallPanels about the CallEvent (in case * they need to update their UI, for example). */ forwardCallEventToCallPanels(ev); // If we're currently in the call history view, refresh TreeContactList contactList = GuiActivator.getContactList(); if (contactList.getCurrentFilter().equals( TreeContactList.historyFilter)) { contactList.applyFilter( TreeContactList.historyFilter); } } /** * Creates and opens a call dialog. Implements * {@link CallListener#outgoingCallCreated(CallEvent)}. * * @param ev the <tt>CallEvent</tt> */ @Override public void outgoingCallCreatedInEventDispatchThread(CallEvent ev) { Call sourceCall = ev.getSourceCall(); openCallContainerIfNecessary(sourceCall); /* * Notify the existing CallPanels about the CallEvent (in case they * need to update their UI, for example). */ forwardCallEventToCallPanels(ev); } } private static class IncomingCallHandler extends CallChangeAdapter { /** * The dialog shown */ private ReceivedCallDialog receivedCallDialog; /** * Peer name. */ private String peerName; /** * The time of the incoming call. */ private long callTime; /** * Construct * @param sourceCall */ IncomingCallHandler(Call sourceCall) { Iterator<? extends CallPeer> peerIter = sourceCall.getCallPeers(); if(!peerIter.hasNext()) { return; } peerName = peerIter.next().getDisplayName(); callTime = System.currentTimeMillis(); sourceCall.addCallChangeListener(this); } /** * State has changed. * @param ev */ @Override public void callStateChanged(final CallChangeEvent ev) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { callStateChanged(ev); } }); return; } if (!CallChangeEvent.CALL_STATE_CHANGE .equals(ev.getPropertyName())) return; // When the call state changes, we ensure here that the // received call notification dialog is closed. if (receivedCallDialog != null && receivedCallDialog.isVisible()) receivedCallDialog.setVisible(false); // Ensure that the CallDialog is created, because it is the // one that listens for CallPeers. Object newValue = ev.getNewValue(); Call call = ev.getSourceCall(); if (CallState.CALL_INITIALIZATION.equals(newValue) || CallState.CALL_IN_PROGRESS.equals(newValue)) { openCallContainerIfNecessary(call); } else if (CallState.CALL_ENDED.equals(newValue)) { if (ev.getOldValue().equals( CallState.CALL_INITIALIZATION)) { // If the call was answered elsewhere, don't mark it // as missed. CallPeerChangeEvent cause = ev.getCause(); if ((cause == null) || (cause.getReasonCode() != CallPeerChangeEvent .NORMAL_CALL_CLEARING)) { addMissedCallNotification(peerName, callTime); } } call.removeCallChangeListener(this); } } /** * Executed on EDT cause will create dialog and will show it. * @param ev */ public void incomingCallReceivedInEventDispatchThread(CallEvent ev) { Call sourceCall = ev.getSourceCall(); boolean isVideoCall = ev.isVideoCall() && ConfigurationUtils.hasEnabledVideoFormat( sourceCall.getProtocolProvider()); receivedCallDialog = new ReceivedCallDialog( sourceCall, isVideoCall, (CallManager.getInProgressCalls().size() > 0)); receivedCallDialog.setVisible(true); Iterator<? extends CallPeer> peerIter = sourceCall.getCallPeers(); if(!peerIter.hasNext()) { if (receivedCallDialog.isVisible()) receivedCallDialog.setVisible(false); return; } /* * Notify the existing CallPanels about the CallEvent (in case they * need to update their UI, for example). */ forwardCallEventToCallPanels(ev); } } /** * Answers the given call. * * @param call the call to answer */ public static void answerCall(Call call) { answerCall(call, null, false /* without video */); } /** * Answers a specific <tt>Call</tt> with or without video and, optionally, * does that in a telephony conference with an existing <tt>Call</tt>. * * @param call * @param existingCall * @param video */ private static void answerCall(Call call, Call existingCall, boolean video) { if (existingCall == null) openCallContainerIfNecessary(call); new AnswerCallThread(call, existingCall, video).start(); } /** * Answers the given call in an existing call. It will end up with a * conference call. * * @param call the call to answer */ public static void answerCallInFirstExistingCall(Call call) { // Find the first existing call. Iterator<Call> existingCallIter = getInProgressCalls().iterator(); Call existingCall = existingCallIter.hasNext() ? existingCallIter.next() : null; answerCall(call, existingCall, false /* without video */); } /** * Merges specific existing <tt>Call</tt>s into a specific telephony * conference. * * @param conference the conference * @param calls list of calls */ public static void mergeExistingCalls( CallConference conference, Collection<Call> calls) { new MergeExistingCalls(conference, calls).start(); } /** * Answers the given call with video. * * @param call the call to answer */ public static void answerVideoCall(Call call) { answerCall(call, null, true /* with video */); } /** * Hang ups the given call. * * @param call the call to hang up */ public static void hangupCall(Call call) { new HangupCallThread(call).start(); } /** * Hang ups the given <tt>callPeer</tt>. * * @param peer the <tt>CallPeer</tt> to hang up */ public static void hangupCallPeer(CallPeer peer) { new HangupCallThread(peer).start(); } /** * Asynchronously hangs up the <tt>Call</tt>s participating in a specific * <tt>CallConference</tt>. * * @param conference the <tt>CallConference</tt> whose participating * <tt>Call</tt>s are to be hanged up */ public static void hangupCalls(CallConference conference) { new HangupCallThread(conference).start(); } /** * Creates a call to the contact represented by the given string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to */ public static void createCall( ProtocolProviderService protocolProvider, String contact) { new CreateCallThread(protocolProvider, contact, false /* audio-only */) .start(); } /** * Creates a call to the contact represented by the given string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to * @param uiContact the meta contact we're calling */ public static void createCall( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact) { new CreateCallThread(protocolProvider, null, null, uiContact, contact, null, null, false /* audio-only */).start(); } /** * Creates a video call to the contact represented by the given string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to */ public static void createVideoCall(ProtocolProviderService protocolProvider, String contact) { new CreateCallThread(protocolProvider, contact, true /* video */) .start(); } /** * Creates a video call to the contact represented by the given string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to * @param uiContact the <tt>UIContactImpl</tt> we're calling */ public static void createVideoCall( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact) { new CreateCallThread(protocolProvider, null, null, uiContact, contact, null, null, true /* video */).start(); } /** * Enables/disables local video for a specific <tt>Call</tt>. * * @param call the <tt>Call</tt> to enable/disable to local video for * @param enable <tt>true</tt> to enable the local video; otherwise, * <tt>false</tt> */ public static void enableLocalVideo(Call call, boolean enable) { new EnableLocalVideoThread(call, enable).start(); } /** * Indicates if the desktop sharing is currently enabled for the given * <tt>call</tt>. * * @param call the <tt>Call</tt>, for which we would to check if the desktop * sharing is currently enabled * @return <tt>true</tt> if the desktop sharing is currently enabled for the * given <tt>call</tt>, <tt>false</tt> otherwise */ public static boolean isLocalVideoEnabled(Call call) { OperationSetVideoTelephony telephony = call.getProtocolProvider().getOperationSet( OperationSetVideoTelephony.class); return (telephony != null) && telephony.isLocalVideoAllowed(call); } /** * Creates a desktop sharing call to the contact represented by the given * string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to * @param uiContact the <tt>UIContactImpl</tt> we're calling */ private static void createDesktopSharing( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact) { // If the user presses cancel on the desktop sharing warning then we // have nothing more to do here. if (!showDesktopSharingWarning()) return; MediaService mediaService = GuiActivator.getMediaService(); List<MediaDevice> desktopDevices = mediaService.getDevices(MediaType.VIDEO, MediaUseCase.DESKTOP); int deviceNumber = desktopDevices.size(); if (deviceNumber == 1) { createDesktopSharing( protocolProvider, contact, uiContact, desktopDevices.get(0)); } else if (deviceNumber > 1) { SelectScreenDialog selectDialog = new SelectScreenDialog(desktopDevices); selectDialog.setVisible(true); if (selectDialog.getSelectedDevice() != null) createDesktopSharing( protocolProvider, contact, uiContact, selectDialog.getSelectedDevice()); } } /** * Creates a region desktop sharing through the given * <tt>protocolProvider</tt> with the given <tt>contact</tt>. * * @param protocolProvider the <tt>ProtocolProviderService</tt>, through * which the sharing session will be established * @param contact the address of the contact recipient * @param uiContact the <tt>UIContactImpl</tt> we're calling */ private static void createRegionDesktopSharing( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact) { if (showDesktopSharingWarning()) { TransparentFrame frame = DesktopSharingFrame .createTransparentFrame( protocolProvider, contact, uiContact, true); frame.setLocationRelativeTo(null); frame.setVisible(true); } } /** * Creates a desktop sharing call to the contact represented by the given * string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to * @param uiContact the <tt>MetaContact</tt> we're calling * @param x the x coordinate of the shared region * @param y the y coordinated of the shared region * @param width the width of the shared region * @param height the height of the shared region */ public static void createRegionDesktopSharing( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact, int x, int y, int width, int height) { MediaService mediaService = GuiActivator.getMediaService(); List<MediaDevice> desktopDevices = mediaService.getDevices( MediaType.VIDEO, MediaUseCase.DESKTOP); int deviceNumber = desktopDevices.size(); if (deviceNumber > 0) { createDesktopSharing( protocolProvider, contact, uiContact, mediaService.getMediaDeviceForPartialDesktopStreaming( width, height, x, y)); } } /** * Creates a desktop sharing call to the contact represented by the given * string. * * @param protocolProvider the protocol provider to which this call belongs. * @param contact the contact to call to * @param uiContact the <tt>UIContactImpl</tt> we're calling * @param mediaDevice the media device corresponding to the screen to share */ private static void createDesktopSharing( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact, MediaDevice mediaDevice) { new CreateDesktopSharingThread( protocolProvider, contact, uiContact, mediaDevice).start(); } /** * Enables the desktop sharing in an existing <tt>call</tt>. * * @param call the call for which desktop sharing should be enabled * @param enable indicates if the desktop sharing should be enabled or * disabled */ public static void enableDesktopSharing(Call call, boolean enable) { if (!enable) enableDesktopSharing(call, null, enable); else if (showDesktopSharingWarning()) { MediaService mediaService = GuiActivator.getMediaService(); List<MediaDevice> desktopDevices = mediaService.getDevices(MediaType.VIDEO, MediaUseCase.DESKTOP); int deviceNumber = desktopDevices.size(); if (deviceNumber == 1) enableDesktopSharing(call, null, enable); else if (deviceNumber > 1) { SelectScreenDialog selectDialog = new SelectScreenDialog(desktopDevices); selectDialog.setVisible(true); if (selectDialog.getSelectedDevice() != null) enableDesktopSharing( call, selectDialog.getSelectedDevice(), enable); } } // in case we switch to video, disable remote control if it was // enabled enableDesktopRemoteControl(call.getCallPeers().next(), false); } /** * Enables the region desktop sharing for the given call. * * @param call the call, for which the region desktop sharing should be * enabled * @param enable indicates if the desktop sharing should be enabled or * disabled */ public static void enableRegionDesktopSharing(Call call, boolean enable) { if (!enable) enableDesktopSharing(call, null, enable); else if (showDesktopSharingWarning()) { TransparentFrame frame = DesktopSharingFrame.createTransparentFrame(call, true); frame.setVisible(true); } } /** * Creates a desktop sharing call to the contact represented by the given * string. * * @param call the call for which desktop sharing should be enabled * @param x the x coordinate of the shared region * @param y the y coordinated of the shared region * @param width the width of the shared region * @param height the height of the shared region */ public static void enableRegionDesktopSharing( Call call, int x, int y, int width, int height) { // Use the default media device corresponding to the screen to share MediaService mediaService = GuiActivator.getMediaService(); List<MediaDevice> desktopDevices = mediaService.getDevices( MediaType.VIDEO, MediaUseCase.DESKTOP); int deviceNumber = desktopDevices.size(); if (deviceNumber > 0) { boolean succeed = enableDesktopSharing( call, mediaService.getMediaDeviceForPartialDesktopStreaming( width, height, x, y), true); // If the region sharing succeed, then display the frame of the // current region shared. if(succeed) { TransparentFrame frame = DesktopSharingFrame.createTransparentFrame(call, false); frame.setVisible(true); } } // in case we switch to video, disable remote control if it was // enabled enableDesktopRemoteControl(call.getCallPeers().next(), false); } /** * Enables the desktop sharing in an existing <tt>call</tt>. * * @param call the call for which desktop sharing should be enabled * @param mediaDevice the media device corresponding to the screen to share * @param enable indicates if the desktop sharing should be enabled or * disabled * * @return True if the desktop sharing succeed (we are currently sharing the * whole or a part of the desktop). False, otherwise. */ private static boolean enableDesktopSharing(Call call, MediaDevice mediaDevice, boolean enable) { OperationSetDesktopStreaming desktopOpSet = call.getProtocolProvider().getOperationSet( OperationSetDesktopStreaming.class); boolean enableSucceeded = false; // This shouldn't happen at this stage, because we disable the button // if the operation set isn't available. if (desktopOpSet != null) { // First make sure the local video button is disabled. if (enable && isLocalVideoEnabled(call)) getActiveCallContainer(call).setVideoButtonSelected(false); try { if (mediaDevice != null) { desktopOpSet.setLocalVideoAllowed( call, mediaDevice, enable); } else desktopOpSet.setLocalVideoAllowed(call, enable); enableSucceeded = true; } catch (OperationFailedException ex) { logger.error( "Failed to toggle the streaming of local video.", ex); } } return (enable && enableSucceeded); } /** * Indicates if the desktop sharing is currently enabled for the given * <tt>call</tt>. * * @param call the <tt>Call</tt>, for which we would to check if the desktop * sharing is currently enabled * @return <tt>true</tt> if the desktop sharing is currently enabled for the * given <tt>call</tt>, <tt>false</tt> otherwise */ public static boolean isDesktopSharingEnabled(Call call) { OperationSetDesktopStreaming desktopOpSet = call.getProtocolProvider().getOperationSet( OperationSetDesktopStreaming.class); if (desktopOpSet != null && desktopOpSet.isLocalVideoAllowed(call)) return true; return false; } /** * Indicates if the desktop sharing is currently enabled for the given * <tt>call</tt>. * * @param call the <tt>Call</tt>, for which we would to check if the desktop * sharing is currently enabled * @return <tt>true</tt> if the desktop sharing is currently enabled for the * given <tt>call</tt>, <tt>false</tt> otherwise */ public static boolean isRegionDesktopSharingEnabled(Call call) { OperationSetDesktopStreaming desktopOpSet = call.getProtocolProvider().getOperationSet( OperationSetDesktopStreaming.class); if (desktopOpSet != null && desktopOpSet.isPartialStreaming(call)) return true; return false; } /** * Enables/disables remote control when in a desktop sharing session with * the given <tt>callPeer</tt>. * * @param callPeer the call peer for which we enable/disable remote control * @param isEnable indicates if the remote control should be enabled */ public static void enableDesktopRemoteControl( CallPeer callPeer, boolean isEnable) { OperationSetDesktopSharingServer sharingOpSet = callPeer.getProtocolProvider().getOperationSet( OperationSetDesktopSharingServer.class); if (sharingOpSet == null) return; if (isEnable) sharingOpSet.enableRemoteControl(callPeer); else sharingOpSet.disableRemoteControl(callPeer); } /** * Creates a call to the given call string. The given component indicates * where should be shown the "call via" menu if needed. * * @param callString the string to call * @param c the component, which indicates where should be shown the "call * via" menu if needed */ public static void createCall( String callString, JComponent c) { createCall(callString, c, null); } /** * Creates a call to the given call string. The given component indicates * where should be shown the "call via" menu if needed. * * @param callString the string to call * @param c the component, which indicates where should be shown the "call * via" menu if needed * @param l listener that is notified when the call interface has been * started after call was created */ public static void createCall( String callString, JComponent c, CallInterfaceListener l) { callString = callString.trim(); // Removes special characters from phone numbers. if (ConfigurationUtils.isNormalizePhoneNumber() && !NetworkUtils.isValidIPAddress(callString)) { callString = GuiActivator.getPhoneNumberI18nService() .normalize(callString); } List<ProtocolProviderService> telephonyProviders = CallManager.getTelephonyProviders(); if (telephonyProviders.size() == 1) { CallManager.createCall( telephonyProviders.get(0), callString); if (l != null) l.callInterfaceStarted(); } else if (telephonyProviders.size() > 1) { /* * Allow plugins which do not have a (Jitsi) UI to create calls by * automagically picking up a telephony provider. */ if (c == null) { ProtocolProviderService preferredTelephonyProvider = null; for (ProtocolProviderService telephonyProvider : telephonyProviders) { try { OperationSetPresence presenceOpSet = telephonyProvider.getOperationSet( OperationSetPresence.class); if ((presenceOpSet != null) && (presenceOpSet.findContactByID(callString) != null)) { preferredTelephonyProvider = telephonyProvider; break; } } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } if (preferredTelephonyProvider == null) preferredTelephonyProvider = telephonyProviders.get(0); CallManager.createCall(preferredTelephonyProvider, callString); if (l != null) l.callInterfaceStarted(); } else { ChooseCallAccountPopupMenu chooseAccountDialog = new ChooseCallAccountPopupMenu( c, callString, telephonyProviders, l); chooseAccountDialog.setLocation(c.getLocation()); chooseAccountDialog.showPopupMenu(); } } else { ResourceManagementService resources = GuiActivator.getResources(); new ErrorDialog( null, resources.getI18NString("service.gui.WARNING"), resources.getI18NString( "service.gui.NO_ONLINE_TELEPHONY_ACCOUNT")) .showDialog(); } } /** * Creates a call to the given list of contacts. * * @param protocolProvider the protocol provider to which this call belongs. * @param callees the list of contacts to call to */ public static void createConferenceCall( String[] callees, ProtocolProviderService protocolProvider) { Map<ProtocolProviderService, List<String>> crossProtocolCallees = new HashMap<ProtocolProviderService, List<String>>(); crossProtocolCallees.put(protocolProvider, Arrays.asList(callees)); createConferenceCall(crossProtocolCallees); } /** * Invites the given list of <tt>callees</tt> to the given conference * <tt>call</tt>. * * @param callees the list of contacts to invite * @param call the protocol provider to which this call belongs */ public static void inviteToConferenceCall(String[] callees, Call call) { Map<ProtocolProviderService, List<String>> crossProtocolCallees = new HashMap<ProtocolProviderService, List<String>>(); crossProtocolCallees.put( call.getProtocolProvider(), Arrays.asList(callees)); inviteToConferenceCall(crossProtocolCallees, call); } /** * Invites the given list of <tt>callees</tt> to the given conference * <tt>call</tt>. * * @param callees the list of contacts to invite * @param call existing call */ public static void inviteToConferenceCall( Map<ProtocolProviderService, List<String>> callees, Call call) { new InviteToConferenceCallThread(callees, call).start(); } /** * Invites specific <tt>callees</tt> to a specific telephony conference. * * @param callees the list of contacts to invite * @param conference the telephony conference to invite the specified * <tt>callees</tt> into */ public static void inviteToConferenceCall( Map<ProtocolProviderService, List<String>> callees, CallConference conference) { /* * InviteToConferenceCallThread takes a specific Call but actually * invites to the telephony conference associated with the specified * Call (if any). In order to not change the signature of its * constructor at this time, just pick up a Call participating in the * specified telephony conference (if any). */ Call call = null; if (conference != null) { List<Call> calls = conference.getCalls(); if (!calls.isEmpty()) call = calls.get(0); } new InviteToConferenceCallThread(callees, call).start(); } /** * Asynchronously creates a new conference <tt>Call</tt> with a specific * list of participants/callees. * * @param callees the list of participants/callees to invite to a * newly-created conference <tt>Call</tt> */ public static void createConferenceCall( Map<ProtocolProviderService, List<String>> callees) { new InviteToConferenceCallThread(callees, null).start(); } /** * Asynchronously creates a new video bridge conference <tt>Call</tt> with * a specific list of participants/callees. * * @param callProvider the <tt>ProtocolProviderService</tt> to use for * creating the call * @param callees the list of participants/callees to invite to the * newly-created video bridge conference <tt>Call</tt> */ public static void createJitsiVideobridgeConfCall( ProtocolProviderService callProvider, String[] callees) { new InviteToConferenceBridgeThread(callProvider, callees, null).start(); } /** * Invites the given list of <tt>callees</tt> to the given conference * <tt>call</tt>. * * @param callees the list of contacts to invite * @param call the protocol provider to which this call belongs */ public static void inviteToJitsiVideobridgeConfCall(String[] callees, Call call) { new InviteToConferenceBridgeThread( call.getProtocolProvider(), callees, call).start(); } /** * Puts on or off hold the given <tt>callPeer</tt>. * @param callPeer the peer to put on/off hold * @param isOnHold indicates the action (on hold or off hold) */ public static void putOnHold(CallPeer callPeer, boolean isOnHold) { new PutOnHoldCallPeerThread(callPeer, isOnHold).start(); } /** * Transfers the given <tt>peer</tt> to the given <tt>target</tt>. * @param peer the <tt>CallPeer</tt> to transfer * @param target the <tt>CallPeer</tt> target to transfer to */ public static void transferCall(CallPeer peer, CallPeer target) { OperationSetAdvancedTelephony<?> telephony = peer.getCall().getProtocolProvider() .getOperationSet(OperationSetAdvancedTelephony.class); if (telephony != null) { try { telephony.transfer(peer, target); } catch (OperationFailedException ex) { logger.error("Failed to transfer " + peer.getAddress() + " to " + target, ex); } } } /** * Transfers the given <tt>peer</tt> to the given <tt>target</tt>. * @param peer the <tt>CallPeer</tt> to transfer * @param target the target of the transfer */ public static void transferCall(CallPeer peer, String target) { OperationSetAdvancedTelephony<?> telephony = peer.getCall().getProtocolProvider() .getOperationSet(OperationSetAdvancedTelephony.class); if (telephony != null) { try { telephony.transfer(peer, target); } catch (OperationFailedException ex) { logger.error("Failed to transfer " + peer.getAddress() + " to " + target, ex); } } } /** * Closes the <tt>CallPanel</tt> of a specific <tt>Call</tt> if it is no * longer necessary (i.e. is not used by other <tt>Call</tt>s participating * in the same telephony conference as the specified <tt>Call</tt>.) * * @param callConference The <tt>CallConference</tt> which is to have its * associated <tt>CallPanel</tt>, if any */ private static void closeCallContainerIfNotNecessary( final CallConference callConference) { CallPanel callPanel = callPanels.get(callConference); if (callPanel != null) closeCallContainerIfNotNecessary( callConference, callPanel.isCloseWaitAfterHangup()); } /** * Closes the <tt>CallPanel</tt> of a specific <tt>Call</tt> if it is no * longer necessary (i.e. is not used by other <tt>Call</tt>s participating * in the same telephony conference as the specified <tt>Call</tt>.) * * @param callConference The <tt>CallConference</tt> which is to have its * associated <tt>CallPanel</tt>, if any, closed * @param wait <tt>true</tt> to set <tt>delay</tt> param of * {@link CallContainer#close(CallPanel, boolean)} (CallPanel)} */ private static void closeCallContainerIfNotNecessary( final CallConference callConference, final boolean wait) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { closeCallContainerIfNotNecessary( callConference, wait); } }); return; } /* * XXX The integrity of the execution of the method may be compromised * if it is not invoked on the AWT event dispatching thread because * findCallPanel and callPanels.remove must be atomically executed. The * uninterrupted execution (with respect to the synchronization) is * guaranteed by requiring all modifications to callPanels to be made on * the AWT event dispatching thread. */ for (Iterator<Map.Entry<CallConference, CallPanel>> entryIter = callPanels.entrySet().iterator(); entryIter.hasNext();) { Map.Entry<CallConference, CallPanel> entry = entryIter.next(); CallConference aConference = entry.getKey(); boolean notNecessary = aConference.isEnded(); if (notNecessary) { CallPanel aCallPanel = entry.getValue(); CallContainer window = aCallPanel.getCallWindow(); try { window.close( aCallPanel, wait && (aConference == callConference)); } finally { /* * We allow non-modifications i.e. reads of callPanels on * threads other than the AWT event dispatching thread so we * have to make sure that we will not cause * ConcurrentModificationException. */ synchronized (callPanels) { entryIter.remove(); } aCallPanel.dispose(); } } } } /** * Opens a <tt>CallPanel</tt> for a specific <tt>Call</tt> if there is none. * <p> * <b>Note</b>: The method can be called only on the AWT event dispatching * thread. * </p> * * @param call the <tt>Call</tt> to open a <tt>CallPanel</tt> for * @return the <tt>CallPanel</tt> associated with the <tt>Call</tt> * @throws RuntimeException if the method is not called on the AWT event * dispatching thread */ private static CallPanel openCallContainerIfNecessary(Call call) { /* * XXX The integrity of the execution of the method may be compromised * if it is not invoked on the AWT event dispatching thread because * findCallPanel and callPanels.put must be atomically executed. The * uninterrupted execution (with respect to the synchronization) is * guaranteed by requiring all modifications to callPanels to be made on * the AWT event dispatching thread. */ assertIsEventDispatchingThread(); /* * CallPanel displays a CallConference (which may contain multiple * Calls.) */ CallConference conference = call.getConference(); CallPanel callPanel = findCallPanel(conference); if (callPanel == null) { // If we're in single-window mode, the single window is the // CallContainer. CallContainer callContainer = GuiActivator.getUIService().getSingleWindowContainer(); // If we're in multi-window mode, we create the CallDialog. if (callContainer == null) callContainer = new CallDialog(); callPanel = new CallPanel(conference, callContainer); callContainer.addCallPanel(callPanel); synchronized (callPanels) { callPanels.put(conference, callPanel); } } return callPanel; } /** * Returns a list of all currently registered telephony providers. * @return a list of all currently registered telephony providers */ public static List<ProtocolProviderService> getTelephonyProviders() { return AccountUtils .getRegisteredProviders(OperationSetBasicTelephony.class); } /** * Returns a list of all currently registered telephony providers supporting * conferencing. * * @return a list of all currently registered telephony providers supporting * conferencing */ public static List<ProtocolProviderService> getTelephonyConferencingProviders() { return AccountUtils .getRegisteredProviders(OperationSetTelephonyConferencing.class); } /** * Returns a list of all currently active calls. * * @return a list of all currently active calls */ private static List<Call> getActiveCalls() { CallConference[] conferences; synchronized (callPanels) { Set<CallConference> keySet = callPanels.keySet(); conferences = keySet.toArray(new CallConference[keySet.size()]); } List<Call> calls = new ArrayList<Call>(); for (CallConference conference : conferences) { for (Call call : conference.getCalls()) { if (call.getCallState() == CallState.CALL_IN_PROGRESS) calls.add(call); } } return calls; } /** * Returns a collection of all currently in progress calls. A call is active * if it is in progress so the method merely delegates to * * @return a collection of all currently in progress calls. */ public static Collection<Call> getInProgressCalls() { return getActiveCalls(); } /** * Returns the <tt>CallContainer</tt> corresponding to the given * <tt>call</tt>. If the call has been finished and no active * <tt>CallContainer</tt> could be found it returns null. * * @param call the <tt>Call</tt>, which dialog we're looking for * @return the <tt>CallContainer</tt> corresponding to the given * <tt>call</tt> */ public static CallPanel getActiveCallContainer(Call call) { return findCallPanel(call.getConference()); } /** * A informative text to show for the peer. If display name is missing * return the address. * @param peer the peer. * @param listener the listener to fire change events for later resolutions * of display name and image, if exist. * @return the text contain display name. */ public static String getPeerDisplayName(CallPeer peer, DetailsResolveListener listener) { String displayName = null; // We try to find the <tt>UIContact</tt>, to which the call was // created if this was an outgoing call. UIContactImpl uiContact = CallManager.getCallUIContact(peer.getCall()); if(uiContact != null) { if(uiContact.getDescriptor() instanceof SourceContact) { // if it is source contact (history record) // search for cusax contact match Contact contact = getPeerCusaxContact(peer, (SourceContact)uiContact.getDescriptor()); if(contact != null) displayName = contact.getDisplayName(); } if(StringUtils.isNullOrEmpty(displayName, true)) displayName = uiContact.getDisplayName(); } // We search for a contact corresponding to this call peer and // try to get its display name. if (StringUtils.isNullOrEmpty(displayName, true) && peer.getContact() != null) { displayName = peer.getContact().getDisplayName(); } // We try to find the an alternative peer address. if (StringUtils.isNullOrEmpty(displayName, true)) { String imppAddress = peer.getAlternativeIMPPAddress(); if (!StringUtils.isNullOrEmpty(imppAddress)) { int protocolPartIndex = imppAddress.indexOf(":"); imppAddress = (protocolPartIndex >= 0) ? imppAddress.substring(protocolPartIndex + 1) : imppAddress; Collection<ProtocolProviderService> cusaxProviders = AccountUtils.getRegisteredProviders( OperationSetCusaxUtils.class); if (cusaxProviders != null && cusaxProviders.size() > 0) { Iterator<ProtocolProviderService> iter = cusaxProviders.iterator(); while(iter.hasNext()) { Contact contact = getPeerContact( peer, iter.next(), imppAddress); displayName = (contact != null) ? contact.getDisplayName() : null; if(!StringUtils.isNullOrEmpty(displayName, true)) break; } } else { MetaContact metaContact = getPeerMetaContact(peer, imppAddress); displayName = (metaContact != null) ? metaContact.getDisplayName() : null; } } } if (StringUtils.isNullOrEmpty(displayName, true)) { displayName = (!StringUtils.isNullOrEmpty (peer.getDisplayName(), true)) ? peer.getDisplayName() : peer.getAddress(); // Try to resolve the display name String resolvedName = queryContactSource(displayName, listener); if(resolvedName != null) { displayName = resolvedName; } } return displayName; } /** * Returns the image corresponding to the given <tt>peer</tt>. * * @param peer the call peer, for which we're returning an image * @return the peer image */ public static byte[] getPeerImage(CallPeer peer) { byte[] image = null; // We search for a contact corresponding to this call peer and // try to get its image. if (peer.getContact() != null) { image = getContactImage(peer.getContact()); } // We try to find the <tt>UIContact</tt>, to which the call was // created if this was an outgoing call. if (image == null || image.length == 0) { UIContactImpl uiContact = CallManager.getCallUIContact(peer.getCall()); if (uiContact != null) { if(uiContact.getDescriptor() instanceof SourceContact && ((SourceContact)uiContact.getDescriptor()) .isDefaultImage()) { // if it is source contact (history record) // search for cusax contact match Contact contact = getPeerCusaxContact(peer, (SourceContact)uiContact.getDescriptor()); if(contact != null) image = contact.getImage(); } else image = uiContact.getAvatar(); } } // We try to find the an alternative peer address. if (image == null || image.length == 0) { String imppAddress = peer.getAlternativeIMPPAddress(); if (!StringUtils.isNullOrEmpty(imppAddress)) { int protocolPartIndex = imppAddress.indexOf(":"); imppAddress = (protocolPartIndex >= 0) ? imppAddress.substring(protocolPartIndex + 1) : imppAddress; Collection<ProtocolProviderService> cusaxProviders = AccountUtils.getRegisteredProviders( OperationSetCusaxUtils.class); if (cusaxProviders != null && cusaxProviders.size() > 0) { Iterator<ProtocolProviderService> iter = cusaxProviders.iterator(); while(iter.hasNext()) { Contact contact = getPeerContact( peer, iter.next(), imppAddress); image = (contact != null) ? getContactImage(contact) : null; if(image != null) break; } } else { MetaContact metaContact = getPeerMetaContact(peer, imppAddress); image = (metaContact != null) ? metaContact.getAvatar() : null; } } } // If the icon is still null we try to get an image from the call // peer. if ((image == null || image.length == 0) && peer.getImage() != null) image = peer.getImage(); return image; } /** * Searches the cusax enabled providers for a contact with * the detail (address) of the call peer if found and the contact * is provided by a provider which is IM capable, return the contact. * @param peer the peer we are calling. * @return the im capable contact corresponding the <tt>peer</tt>. */ public static Contact getIMCapableCusaxContact(CallPeer peer) { // We try to find the <tt>UIContact</tt>, to which the call was // created if this was an outgoing call. UIContactImpl uiContact = CallManager.getCallUIContact(peer.getCall()); if (uiContact != null) { if(uiContact.getDescriptor() instanceof MetaContact) { MetaContact metaContact = (MetaContact)uiContact.getDescriptor(); Iterator<Contact> iter = metaContact.getContacts(); while(iter.hasNext()) { Contact contact = iter.next(); if(contact.getProtocolProvider() .getOperationSet( OperationSetBasicInstantMessaging.class) != null) return contact; } } else if(uiContact.getDescriptor() instanceof SourceContact) { // if it is source contact (history record) // search for cusax contact match Contact contact = getPeerCusaxContact(peer, (SourceContact)uiContact.getDescriptor()); if(contact != null && contact.getProtocolProvider().getOperationSet( OperationSetBasicInstantMessaging.class) != null) return contact; } } // We try to find the an alternative peer address. String imppAddress = peer.getAlternativeIMPPAddress(); if (!StringUtils.isNullOrEmpty(imppAddress)) { int protocolPartIndex = imppAddress.indexOf(":"); imppAddress = (protocolPartIndex >= 0) ? imppAddress.substring(protocolPartIndex + 1) : imppAddress; Collection<ProtocolProviderService> cusaxProviders = AccountUtils.getRegisteredProviders( OperationSetCusaxUtils.class); if (cusaxProviders != null && cusaxProviders.size() > 0) { Iterator<ProtocolProviderService> iter = cusaxProviders.iterator(); while(iter.hasNext()) { ProtocolProviderService cusaxProvider = iter.next(); Contact contact = getPeerContact( peer, cusaxProvider, imppAddress); if(contact != null && cusaxProvider.getOperationSet( OperationSetBasicInstantMessaging.class) != null) { return contact; } } } } return null; } /** * Find is there a linked cusax protocol provider for this source contact, * if it exist we try to resolve current peer to one of its contacts * or details of a contact (numbers). * @param peer the peer to check * @param sourceContact the currently selected source contact. * @return matching cusax contact. */ private static Contact getPeerCusaxContact( CallPeer peer, SourceContact sourceContact) { ProtocolProviderService linkedCusaxProvider = null; for(ContactDetail detail : sourceContact.getContactDetails()) { ProtocolProviderService pps = detail.getPreferredProtocolProvider( OperationSetBasicTelephony.class); if(pps != null) { OperationSetCusaxUtils cusaxOpSet = pps.getOperationSet(OperationSetCusaxUtils.class); if(cusaxOpSet != null) { linkedCusaxProvider = cusaxOpSet.getLinkedCusaxProvider(); break; } } } // if we do not have preferred protocol, lets check the one // used to dial the peer if(linkedCusaxProvider == null) { ProtocolProviderService pps = peer.getProtocolProvider(); OperationSetCusaxUtils cusaxOpSet = pps.getOperationSet(OperationSetCusaxUtils.class); if(cusaxOpSet != null) { linkedCusaxProvider = cusaxOpSet.getLinkedCusaxProvider(); } } if(linkedCusaxProvider != null) { OperationSetPersistentPresence opSetPersistentPresence = linkedCusaxProvider.getOperationSet( OperationSetPersistentPresence.class); if(opSetPersistentPresence != null) { String peerAddress = peer.getAddress(); // will strip the @server-address part, as the regular expression // will match it int index = peerAddress.indexOf("@"); String peerUserID = (index > -1) ? peerAddress.substring(0, index) : peerAddress; // searches for the whole number/username or with the @serverpart String peerUserIDQ = Pattern.quote(peerUserID); Pattern pattern = Pattern.compile( "^(" + peerUserIDQ + "|" + peerUserIDQ + "@.*)$"); return findContactByPeer( peerUserID, pattern, opSetPersistentPresence.getServerStoredContactListRoot(), linkedCusaxProvider.getOperationSet( OperationSetCusaxUtils.class)); } } return null; } /** * Finds a matching cusax contact. * @param peerUserID the userID of the call peer to search for * @param searchPattern the pattern (userID | userID@...) * @param parent the parent group of the groups and contacts to search in * @param cusaxOpSet the opset of the provider which will be used to match * contact's details to peer userID (stored numbers). * @return a cusax matching contac */ private static Contact findContactByPeer( String peerUserID, Pattern searchPattern, ContactGroup parent, OperationSetCusaxUtils cusaxOpSet) { Iterator<Contact> contactIterator = parent.contacts(); while(contactIterator.hasNext()) { Contact contact = contactIterator.next(); if(searchPattern.matcher(contact.getAddress()).find() || cusaxOpSet.doesDetailBelong(contact, peerUserID)) { return contact; } } Iterator<ContactGroup> groupsIterator = parent.subgroups(); while(groupsIterator.hasNext()) { ContactGroup gr = groupsIterator.next(); Contact contact = findContactByPeer( peerUserID, searchPattern, gr, cusaxOpSet); if(contact != null) return contact; } return null; } /** * Returns the image for the given contact. * * @param contact the <tt>Contact</tt>, which image we're looking for * @return the array of bytes representing the image for the given contact * or null if such image doesn't exist */ private static byte[] getContactImage(Contact contact) { MetaContact metaContact = GuiActivator.getContactListService() .findMetaContactByContact(contact); if (metaContact != null) return metaContact.getAvatar(); return null; } /** * Returns the peer contact for the given <tt>alternativePeerAddress</tt> by * checking the if the <tt>callPeer</tt> exists as a detail in the given * <tt>cusaxProvider</tt>. * * @param callPeer the <tt>CallPeer</tt> to check in the cusax provider * details * @param cusaxProvider the linked cusax <tt>ProtocolProviderService</tt> * @param alternativePeerAddress the alternative peer address to obtain the * image from * @return the protocol <tt>Contact</tt> corresponding to the given * <tt>alternativePeerAddress</tt> */ private static Contact getPeerContact( CallPeer callPeer, ProtocolProviderService cusaxProvider, String alternativePeerAddress) { OperationSetPresence presenceOpSet = cusaxProvider.getOperationSet(OperationSetPresence.class); if (presenceOpSet == null) return null; Contact contact = presenceOpSet.findContactByID(alternativePeerAddress); if (contact == null) return null; OperationSetCusaxUtils cusaxOpSet = cusaxProvider.getOperationSet(OperationSetCusaxUtils.class); if (cusaxOpSet != null && cusaxOpSet.doesDetailBelong( contact, callPeer.getAddress())) return contact; return null; } /** * Returns the metacontact for the given <tt>CallPeer</tt> by * checking the if the <tt>callPeer</tt> contact exists, if not checks the * contacts in our contact list that are provided by cusax enabled * providers. * * @param peer the <tt>CallPeer</tt> to check in contact details * @return the <tt>MetaContact</tt> corresponding to the given * <tt>peer</tt>. */ public static MetaContact getPeerMetaContact(CallPeer peer) { if(peer == null) return null; if(peer.getContact() != null) return GuiActivator.getContactListService() .findMetaContactByContact(peer.getContact()); // We try to find the <tt>UIContact</tt>, to which the call was // created if this was an outgoing call. UIContactImpl uiContact = CallManager.getCallUIContact(peer.getCall()); if (uiContact != null) { if(uiContact.getDescriptor() instanceof MetaContact) { return (MetaContact)uiContact.getDescriptor(); } else if(uiContact.getDescriptor() instanceof SourceContact) { // if it is a source contact check for matching cusax contact Contact contact = getPeerCusaxContact(peer, (SourceContact)uiContact.getDescriptor()); if(contact != null) return GuiActivator.getContactListService() .findMetaContactByContact(contact); } } String imppAddress = peer.getAlternativeIMPPAddress(); if (!StringUtils.isNullOrEmpty(imppAddress)) { int protocolPartIndex = imppAddress.indexOf(":"); imppAddress = (protocolPartIndex >= 0) ? imppAddress.substring(protocolPartIndex + 1) : imppAddress; Collection<ProtocolProviderService> cusaxProviders = AccountUtils.getRegisteredProviders( OperationSetCusaxUtils.class); if (cusaxProviders != null && cusaxProviders.size() > 0) { Iterator<ProtocolProviderService> iter = cusaxProviders.iterator(); while(iter.hasNext()) { Contact contact = getPeerContact( peer, iter.next(), imppAddress); MetaContact res = GuiActivator.getContactListService() .findMetaContactByContact(contact); if(res != null) return res; } } else { return getPeerMetaContact(peer, imppAddress); } } return null; } /** * Returns the image for the given <tt>alternativePeerAddress</tt> by * checking the if the <tt>callPeer</tt> exists as a detail in one of the * contacts in our contact list. * * @param callPeer the <tt>CallPeer</tt> to check in contact details * @param alternativePeerAddress the alternative peer address to obtain the * image from * @return the <tt>MetaContact</tt> corresponding to the given * <tt>alternativePeerAddress</tt> */ private static MetaContact getPeerMetaContact( CallPeer callPeer, String alternativePeerAddress) { Iterator<MetaContact> metaContacts = GuiActivator.getContactListService() .findAllMetaContactsForAddress(alternativePeerAddress); while (metaContacts.hasNext()) { MetaContact metaContact = metaContacts.next(); UIPhoneUtil phoneUtil = UIPhoneUtil.getPhoneUtil(metaContact); List<UIContactDetail> additionalNumbers = phoneUtil.getAdditionalNumbers(); if (additionalNumbers == null || additionalNumbers.size() > 0) continue; Iterator<UIContactDetail> numbersIter = additionalNumbers.iterator(); while (numbersIter.hasNext()) { if (numbersIter.next().getAddress() .equals(callPeer.getAddress())) return metaContact; } } return null; } /** * Opens a call transfer dialog to transfer the given <tt>peer</tt>. * @param peer the <tt>CallPeer</tt> to transfer */ public static void openCallTransferDialog(CallPeer peer) { final TransferCallDialog dialog = new TransferCallDialog(peer); final Call call = peer.getCall(); /* * Transferring a call works only when the call is in progress * so close the dialog (if it's not already closed, of course) * once the dialog ends. */ CallChangeListener callChangeListener = new CallChangeAdapter() { /* * Overrides * CallChangeAdapter#callStateChanged(CallChangeEvent). */ @Override public void callStateChanged(CallChangeEvent evt) { // we are interested only in CALL_STATE_CHANGEs if(!evt.getEventType().equals( CallChangeEvent.CALL_STATE_CHANGE)) return; if (!CallState.CALL_IN_PROGRESS.equals(call .getCallState())) { dialog.setVisible(false); dialog.dispose(); } } }; call.addCallChangeListener(callChangeListener); try { dialog.pack(); dialog.setVisible(true); } finally { call.removeCallChangeListener(callChangeListener); } } /** * Checks whether the <tt>callPeer</tt> supports setting video * quality presets. If quality controls is null, its not supported. * @param callPeer the peer, which video quality we're checking * @return whether call peer supports setting quality preset. */ public static boolean isVideoQualityPresetSupported(CallPeer callPeer) { ProtocolProviderService provider = callPeer.getProtocolProvider(); OperationSetVideoTelephony videoOpSet = provider.getOperationSet(OperationSetVideoTelephony.class); if (videoOpSet == null) return false; return videoOpSet.getQualityControl(callPeer) != null; } /** * Sets the given quality preset for the video of the given call peer. * * @param callPeer the peer, which video quality we're setting * @param qualityPreset the new quality settings */ public static void setVideoQualityPreset(final CallPeer callPeer, final QualityPreset qualityPreset) { ProtocolProviderService provider = callPeer.getProtocolProvider(); final OperationSetVideoTelephony videoOpSet = provider.getOperationSet(OperationSetVideoTelephony.class); if (videoOpSet == null) return; final QualityControl qualityControl = videoOpSet.getQualityControl(callPeer); if (qualityControl != null) { new Thread(new Runnable() { public void run() { try { qualityControl.setPreferredRemoteSendMaxPreset( qualityPreset); } catch(org.jitsi.service.protocol.OperationFailedException e) { logger.info("Unable to change video quality.", e); ResourceManagementService resources = GuiActivator.getResources(); new ErrorDialog( null, resources.getI18NString("service.gui.WARNING"), resources.getI18NString( "service.gui.UNABLE_TO_CHANGE_VIDEO_QUALITY"), e) .showDialog(); } } }).start(); } } /** * Indicates if we have video streams to show in this interface. * * @param call the call to check for video streaming * @return <tt>true</tt> if we have video streams to show in this interface; * otherwise, <tt>false</tt> */ public static boolean isVideoStreaming(Call call) { return isVideoStreaming(call.getConference()); } /** * Indicates if we have video streams to show in this interface. * * @param conference the conference we check for video streaming * @return <tt>true</tt> if we have video streams to show in this interface; * otherwise, <tt>false</tt> */ public static boolean isVideoStreaming(CallConference conference) { for (Call call : conference.getCalls()) { OperationSetVideoTelephony videoTelephony = call.getProtocolProvider().getOperationSet( OperationSetVideoTelephony.class); if (videoTelephony == null) continue; if (videoTelephony.isLocalVideoStreaming(call)) return true; Iterator<? extends CallPeer> callPeers = call.getCallPeers(); while (callPeers.hasNext()) { List<Component> remoteVideos = videoTelephony.getVisualComponents(callPeers.next()); if ((remoteVideos != null) && (remoteVideos.size() > 0)) return true; } } return false; } /** * Determines whether two specific addresses refer to one and the same * peer/resource/contact. * <p> * <b>Warning</b>: Use the functionality sparingly because it assumes that * an unspecified service is equal to any service. * </p> * * @param a one of the addresses to be compared * @param b the other address to be compared to <tt>a</tt> * @return <tt>true</tt> if <tt>a</tt> and <tt>b</tt> name one and the same * peer/resource/contact; <tt>false</tt>, otherwise */ public static boolean addressesAreEqual(String a, String b) { if (a.equals(b)) return true; int aProtocolIndex = a.indexOf(':'); if(aProtocolIndex != -1) a = a.substring(aProtocolIndex + 1); int bProtocolIndex = b.indexOf(':'); if(bProtocolIndex != -1) b = b.substring(bProtocolIndex + 1); if (a.equals(b)) return true; int aServiceBegin = a.indexOf('@', aProtocolIndex); String aUserID; String aService; if (aServiceBegin != -1) { aUserID = a.substring(0, aServiceBegin); ++aServiceBegin; int aResourceBegin = a.indexOf('/', aServiceBegin); if (aResourceBegin != -1) aService = a.substring(aServiceBegin, aResourceBegin); else aService = a.substring(aServiceBegin); } else { aUserID = a; aService = null; } int bServiceBegin = b.indexOf('@', bProtocolIndex); String bUserID; String bService; if (bServiceBegin != -1) { bUserID = b.substring(0, bServiceBegin); ++bServiceBegin; int bResourceBegin = b.indexOf('/', bServiceBegin); if (bResourceBegin != -1) bService = b.substring(bServiceBegin, bResourceBegin); else bService = b.substring(bServiceBegin); } else { bUserID = b; bService = null; } boolean userIDsAreEqual; if ((aUserID == null) || (aUserID.length() < 1)) userIDsAreEqual = ((bUserID == null) || (bUserID.length() < 1)); else userIDsAreEqual = aUserID.equals(bUserID); if (!userIDsAreEqual) return false; boolean servicesAreEqual; /* * It's probably a veeery long shot but it's assumed here that an * unspecified service is equal to any service. Such a case is, for * example, RegistrarLess SIP. */ if (((aService == null) || (aService.length() < 1)) || ((bService == null) || (bService.length() < 1))) servicesAreEqual = true; else servicesAreEqual = aService.equals(bService); return servicesAreEqual; } /** * Indicates if the given <tt>ConferenceMember</tt> corresponds to the local * user. * * @param conferenceMember the conference member to check * @return <tt>true</tt> if the given <tt>conferenceMember</tt> is the local * user, <tt>false</tt> - otherwise */ public static boolean isLocalUser(ConferenceMember conferenceMember) { String localUserAddress = conferenceMember.getConferenceFocusCallPeer() .getProtocolProvider().getAccountID().getAccountAddress(); return CallManager.addressesAreEqual( conferenceMember.getAddress(), localUserAddress); } /** * Adds a missed call notification. * * @param peerName the name of the peer * @param callTime the time of the call */ private static void addMissedCallNotification(String peerName, long callTime) { if (missedCallGroup == null) { missedCallGroup = new UINotificationGroup( "MissedCalls", GuiActivator.getResources().getI18NString( "service.gui.MISSED_CALLS_TOOL_TIP")); } UINotificationManager.addNotification( new UINotification(peerName, callTime, missedCallGroup)); } /** * Returns of supported/enabled list of audio formats for a provider. * @param device the <tt>MediaDevice</tt>, which audio formats we're * looking for * @param protocolProvider the provider to check. * @return list of supported/enabled auido formats or empty list * otherwise. */ private static List<MediaFormat> getAudioFormats( MediaDevice device, ProtocolProviderService protocolProvider) { List<MediaFormat> res = new ArrayList<MediaFormat>(); Map<String, String> accountProperties = protocolProvider.getAccountID().getAccountProperties(); String overrideEncodings = accountProperties.get(ProtocolProviderFactory.OVERRIDE_ENCODINGS); List<MediaFormat> formats; if(Boolean.parseBoolean(overrideEncodings)) { /* * The account properties associated with account * override the global EncodingConfiguration. */ EncodingConfiguration encodingConfiguration = ProtocolMediaActivator.getMediaService() .createEmptyEncodingConfiguration(); encodingConfiguration.loadProperties( accountProperties, ProtocolProviderFactory.ENCODING_PROP_PREFIX); formats = device.getSupportedFormats( null, null, encodingConfiguration); } else /* The global EncodingConfiguration is in effect. */ { formats = device.getSupportedFormats(); } // skip the special telephony event for(MediaFormat format : formats) { if(!format.getEncoding().equals(Constants.TELEPHONE_EVENT)) res.add(format); } return res; } /** * Creates a new (audio-only or video) <tt>Call</tt> to a contact specified * as a <tt>Contact</tt> instance or a <tt>String</tt> contact * address/identifier. */ private static class CreateCallThread extends Thread { /** * The contact to call. */ private final Contact contact; /** * The specific contact resource to call. */ private final ContactResource contactResource; /** * The <tt>UIContactImpl</tt> we're calling. */ private final UIContactImpl uiContact; /** * The protocol provider through which the call goes. */ private final ProtocolProviderService protocolProvider; /** * The string to call. */ private final String stringContact; /** * The description of a conference to call, if any. */ private final ConferenceDescription conferenceDescription; /** * The indicator which determines whether this instance is to create a * new video (as opposed to audio-only) <tt>Call</tt>. */ private final boolean video; /** * The chat room associated with the call. */ private final ChatRoom chatRoom; /** * Creates an instance of <tt>CreateCallThread</tt>. * * @param protocolProvider the protocol provider through which the call * is going. * @param contact the contact to call * @param contactResource the specific <tt>ContactResource</tt> we're * calling * @param video indicates if this is a video call */ public CreateCallThread( ProtocolProviderService protocolProvider, Contact contact, ContactResource contactResource, boolean video) { this(protocolProvider, contact, contactResource, null, null, null, null, video); } /** * Creates an instance of <tt>CreateCallThread</tt>. * * @param protocolProvider the protocol provider through which the call * is going. * @param contact the contact to call * @param video indicates if this is a video call */ public CreateCallThread( ProtocolProviderService protocolProvider, String contact, boolean video) { this(protocolProvider, null, null, null, contact, null, null, video); } /** * Initializes a new <tt>CreateCallThread</tt> instance which is to * create a new <tt>Call</tt> to a conference specified via a * <tt>ConferenceDescription</tt>. * @param protocolProvider the <tt>ProtocolProviderService</tt> which is * to perform the establishment of the new <tt>Call</tt>. * @param conferenceDescription the description of the conference to * call. * @param chatRoom the chat room associated with the call. */ public CreateCallThread( ProtocolProviderService protocolProvider, ConferenceDescription conferenceDescription, ChatRoom chatRoom) { this(protocolProvider, null, null, null, null, conferenceDescription, chatRoom, false /* video */); } /** * Initializes a new <tt>CreateCallThread</tt> instance which is to * create a new <tt>Call</tt> to a contact specified either as a * <tt>Contact</tt> instance or as a <tt>String</tt> contact * address/identifier. * <p> * The constructor is private because it relies on its arguments being * validated prior to its invocation. * </p> * * @param protocolProvider the <tt>ProtocolProviderService</tt> which is * to perform the establishment of the new <tt>Call</tt> * @param contact the contact to call * @param contactResource the specific contact resource to call * @param uiContact the ui contact we're calling * @param stringContact the string to call * @param video <tt>true</tt> if this instance is to create a new video * (as opposed to audio-only) <tt>Call</tt> * @param conferenceDescription the description of a conference to call * @param chatRoom the chat room associated with the call. */ public CreateCallThread( ProtocolProviderService protocolProvider, Contact contact, ContactResource contactResource, UIContactImpl uiContact, String stringContact, ConferenceDescription conferenceDescription, ChatRoom chatRoom, boolean video) { this.protocolProvider = protocolProvider; this.contact = contact; this.contactResource = contactResource; this.uiContact = uiContact; this.stringContact = stringContact; this.video = video; this.conferenceDescription = conferenceDescription; this.chatRoom = chatRoom; } @Override public void run() { if(!video) { // if it is not video let's check for available audio codecs // and available audio devices MediaService mediaService = GuiActivator.getMediaService(); MediaDevice dev = mediaService.getDefaultDevice( MediaType.AUDIO, MediaUseCase.CALL); List<MediaFormat> formats = getAudioFormats(dev, protocolProvider); String errorMsg = null; if(!dev.getDirection().allowsSending()) errorMsg = GuiActivator.getResources().getI18NString( "service.gui.CALL_NO_AUDIO_DEVICE"); else if(formats.isEmpty()) { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.CALL_NO_AUDIO_CODEC"); } if(errorMsg != null) { if(GuiActivator.getUIService() .getPopupDialog().showConfirmPopupDialog( errorMsg + " " + GuiActivator.getResources().getI18NString( "service.gui.CALL_NO_DEVICE_CODECS_Q"), GuiActivator.getResources().getI18NString( "service.gui.CALL"), PopupDialog.YES_NO_OPTION, PopupDialog.QUESTION_MESSAGE) == PopupDialog.NO_OPTION) { return; } } } Contact contact = this.contact; String stringContact = this.stringContact; if (ConfigurationUtils.isNormalizePhoneNumber() && !NetworkUtils.isValidIPAddress(stringContact)) { if (contact != null) { stringContact = contact.getAddress(); contact = null; } if (stringContact != null) { stringContact = GuiActivator.getPhoneNumberI18nService() .normalize(stringContact); } } try { if (conferenceDescription != null) { internalCall( protocolProvider, conferenceDescription, chatRoom); } else { if (video) { internalCallVideo( protocolProvider, contact, uiContact, stringContact); } else { internalCall( protocolProvider, contact, stringContact, contactResource, uiContact); } } } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; logger.error("The call could not be created: ", t); String message = GuiActivator.getResources() .getI18NString("servoce.gui.CREATE_CALL_FAILED"); if (t.getMessage() != null) message += " " + t.getMessage(); new ErrorDialog( null, GuiActivator.getResources().getI18NString( "service.gui.ERROR"), message, t) .showDialog(); } } } /** * Creates a video call through the given <tt>protocolProvider</tt>. * * @param protocolProvider the <tt>ProtocolProviderService</tt> through * which to make the call * @param contact the <tt>Contact</tt> to call * @param uiContact the <tt>UIContactImpl</tt> we're calling * @param stringContact the contact string to call * * @throws OperationFailedException thrown if the call operation fails * @throws ParseException thrown if the contact string is malformated */ private static void internalCallVideo( ProtocolProviderService protocolProvider, Contact contact, UIContactImpl uiContact, String stringContact) throws OperationFailedException, ParseException { OperationSetVideoTelephony telephony = protocolProvider.getOperationSet( OperationSetVideoTelephony.class); Call createdCall = null; if (telephony != null) { if (contact != null) { createdCall = telephony.createVideoCall(contact); } else if (stringContact != null) createdCall = telephony.createVideoCall(stringContact); } if (uiContact != null && createdCall != null) addUIContactCall(uiContact, createdCall); } /** * Creates a call through the given <tt>protocolProvider</tt>. * * @param protocolProvider the <tt>ProtocolProviderService</tt> through * which to make the call * @param contact the <tt>Contact</tt> to call * @param stringContact the contact string to call * @param contactResource the specific <tt>ContactResource</tt> to call * @param uiContact the <tt>UIContactImpl</tt> we're calling * * @throws OperationFailedException thrown if the call operation fails * @throws ParseException thrown if the contact string is malformated */ private static void internalCall( ProtocolProviderService protocolProvider, Contact contact, String stringContact, ContactResource contactResource, UIContactImpl uiContact) throws OperationFailedException, ParseException { OperationSetBasicTelephony<?> telephony = protocolProvider.getOperationSet( OperationSetBasicTelephony.class); OperationSetResourceAwareTelephony resourceTelephony = protocolProvider.getOperationSet( OperationSetResourceAwareTelephony.class); Call createdCall = null; if (resourceTelephony != null && contactResource != null) { if (contact != null) createdCall = resourceTelephony.createCall(contact, contactResource); else if (!StringUtils.isNullOrEmpty(stringContact)) createdCall = resourceTelephony.createCall( stringContact, contactResource.getResourceName()); } else if (telephony != null) { if (contact != null) { createdCall = telephony.createCall(contact); } else if (!StringUtils.isNullOrEmpty(stringContact)) createdCall = telephony.createCall(stringContact); } if (uiContact != null && createdCall != null) addUIContactCall(uiContact, createdCall); } /** * Creates a call through the given <tt>protocolProvider</tt>. * * @param protocolProvider the <tt>ProtocolProviderService</tt> through * which to make the call * @param conferenceDescription the description of the conference to call * @param chatRoom the chat room associated with the call. */ private static void internalCall(ProtocolProviderService protocolProvider, ConferenceDescription conferenceDescription, ChatRoom chatRoom) throws OperationFailedException { OperationSetBasicTelephony<?> telephony = protocolProvider.getOperationSet( OperationSetBasicTelephony.class); if (telephony != null) { telephony.createCall(conferenceDescription, chatRoom); } } /** * Returns the <tt>MetaContact</tt>, to which the given <tt>Call</tt> * was initially created. * * @param call the <tt>Call</tt>, which corresponding <tt>MetaContact</tt> * we're looking for * @return the <tt>UIContactImpl</tt>, to which the given <tt>Call</tt> * was initially created */ public static UIContactImpl getCallUIContact(Call call) { if (uiContactCalls != null) return uiContactCalls.get(call); return null; } /** * Adds a call for a <tt>metaContact</tt>. * * @param uiContact the <tt>UIContact</tt> corresponding to the call * @param call the <tt>Call</tt> corresponding to the <tt>MetaContact</tt> */ private static void addUIContactCall( UIContactImpl uiContact, Call call) { if (uiContactCalls == null) uiContactCalls = new WeakHashMap<Call, UIContactImpl>(); uiContactCalls.put(call, uiContact); } /** * Creates a desktop sharing session with the given Contact or a given * String. */ private static class CreateDesktopSharingThread extends Thread { /** * The string contact to share the desktop with. */ private final String stringContact; /** * The protocol provider through which we share our desktop. */ private final ProtocolProviderService protocolProvider; /** * The media device corresponding to the screen we would like to share. */ private final MediaDevice mediaDevice; /** * The <tt>UIContactImpl</tt> we're calling. */ private final UIContactImpl uiContact; /** * Creates a desktop sharing session thread. * * @param protocolProvider protocol provider through which we share our * desktop * @param contact the contact to share the desktop with * @param uiContact the <tt>UIContact</tt>, which initiated the desktop * sharing session * @param mediaDevice the media device corresponding to the screen we * would like to share */ public CreateDesktopSharingThread( ProtocolProviderService protocolProvider, String contact, UIContactImpl uiContact, MediaDevice mediaDevice) { this.protocolProvider = protocolProvider; this.stringContact = contact; this.uiContact = uiContact; this.mediaDevice = mediaDevice; } @Override public void run() { OperationSetDesktopStreaming desktopSharingOpSet = protocolProvider.getOperationSet( OperationSetDesktopStreaming.class); /* * XXX If we are here and we just discover that * OperationSetDesktopStreaming is not supported, then we're * already in trouble - we've already started a whole new thread * just to check that a reference is null. */ if (desktopSharingOpSet == null) return; Throwable exception = null; Call createdCall = null; try { if (mediaDevice != null) { createdCall = desktopSharingOpSet.createVideoCall( stringContact, mediaDevice); } else createdCall = desktopSharingOpSet.createVideoCall(stringContact); } catch (OperationFailedException e) { exception = e; } catch (ParseException e) { exception = e; } if (exception != null) { logger.error("The call could not be created: ", exception); new ErrorDialog( null, GuiActivator.getResources().getI18NString( "service.gui.ERROR"), exception.getMessage(), ErrorDialog.ERROR) .showDialog(); } if (uiContact != null && createdCall != null) addUIContactCall(uiContact, createdCall); } } /** * Answers to all <tt>CallPeer</tt>s associated with a specific * <tt>Call</tt> and, optionally, does that in a telephony conference with * an existing <tt>Call</tt>. */ private static class AnswerCallThread extends Thread { /** * The <tt>Call</tt> which is to be answered. */ private final Call call; /** * The existing <tt>Call</tt>, if any, which represents a telephony * conference in which {@link #call} is to be answered. */ private final Call existingCall; /** * The indicator which determines whether this instance is to answer * {@link #call} with video. */ private final boolean video; public AnswerCallThread(Call call, Call existingCall, boolean video) { this.call = call; this.existingCall = existingCall; this.video = video; } @Override public void run() { if (existingCall != null) call.setConference(existingCall.getConference()); ProtocolProviderService pps = call.getProtocolProvider(); Iterator<? extends CallPeer> peers = call.getCallPeers(); while (peers.hasNext()) { CallPeer peer = peers.next(); if (video) { OperationSetVideoTelephony telephony = pps.getOperationSet(OperationSetVideoTelephony.class); try { telephony.answerVideoCallPeer(peer); } catch (OperationFailedException ofe) { logger.error( "Could not answer " + peer + " with video" + " because of the following exception: " + ofe); } } else { OperationSetBasicTelephony<?> telephony = pps.getOperationSet(OperationSetBasicTelephony.class); try { telephony.answerCallPeer(peer); } catch (OperationFailedException ofe) { logger.error( "Could not answer " + peer + " because of the following exception: ", ofe); } } } } } /** * Invites a list of callees to a conference <tt>Call</tt>. If the specified * <tt>Call</tt> is <tt>null</tt>, creates a brand new telephony conference. */ private static class InviteToConferenceCallThread extends Thread { /** * The addresses of the callees to be invited into the telephony * conference to be organized by this instance. For further details, * refer to the documentation on the <tt>callees</tt> parameter of the * respective <tt>InviteToConferenceCallThread</tt> constructor. */ private final Map<ProtocolProviderService, List<String>> callees; /** * The <tt>Call</tt>, if any, into the telephony conference of which * {@link #callees} are to be invited. If non-<tt>null</tt>, its * <tt>CallConference</tt> state will be shared with all <tt>Call</tt>s * established by this instance for the purposes of having the * <tt>callees</tt> into the same telephony conference. */ private final Call call; /** * Initializes a new <tt>InviteToConferenceCallThread</tt> instance * which is to invite a list of callees to a conference <tt>Call</tt>. * If the specified <tt>call</tt> is <tt>null</tt>, creates a brand new * telephony conference. * * @param callees the addresses of the callees to be invited into a * telephony conference. The addresses are provided in multiple * <tt>List&lt;String&gt;</tt>s. Each such list of addresses is mapped * by the <tt>ProtocolProviderService</tt> through which they are to be * invited into the telephony conference. If there are multiple * <tt>ProtocolProviderService</tt>s in the specified <tt>Map</tt>, the * resulting telephony conference is known by the name * &quot;cross-protocol&quot;. It is also allowed to have a list of * addresses mapped to <tt>null</tt> which means that the new instance * will automatically choose a <tt>ProtocolProviderService</tt> to * invite the respective callees into the telephony conference. * @param call the <tt>Call</tt> to invite the specified * <tt>callees</tt> into. If <tt>null</tt>, this instance will create a * brand new telephony conference. Technically, a <tt>Call</tt> instance * is protocol/account-specific and it is possible to have * cross-protocol/account telephony conferences. That's why the * specified <tt>callees</tt> are invited into one and the same * <tt>CallConference</tt>: the one in which the specified <tt>call</tt> * is participating or a new one if <tt>call</tt> is <tt>null</tt>. Of * course, an attempt is made to have all callees from one and the same * protocol/account into one <tt>Call</tt> instance. */ public InviteToConferenceCallThread( Map<ProtocolProviderService, List<String>> callees, Call call) { this.callees = callees; this.call = call; } /** * Invites {@link #callees} into a telephony conference which is * optionally specified by {@link #call}. */ @Override public void run() { CallConference conference = (call == null) ? null : call.getConference(); for(Map.Entry<ProtocolProviderService, List<String>> entry : callees.entrySet()) { ProtocolProviderService pps = entry.getKey(); /* * We'd like to allow specifying callees without specifying an * associated ProtocolProviderService. */ if (pps != null) { OperationSetBasicTelephony<?> basicTelephony = pps.getOperationSet(OperationSetBasicTelephony.class); if(basicTelephony == null) continue; } List<String> contactList = entry.getValue(); String[] contactArray = contactList.toArray(new String[contactList.size()]); if (ConfigurationUtils.isNormalizePhoneNumber()) normalizePhoneNumbers(contactArray); /* Try to have a single Call per ProtocolProviderService. */ Call ppsCall; if ((call != null) && call.getProtocolProvider().equals(pps)) ppsCall = call; else { ppsCall = null; if (conference != null) { List<Call> conferenceCalls = conference.getCalls(); if (pps == null) { /* * We'd like to allow specifying callees without * specifying an associated ProtocolProviderService. * The simplest approach is to just choose the first * ProtocolProviderService involved in the telephony * conference. */ if (call == null) { if (!conferenceCalls.isEmpty()) { ppsCall = conferenceCalls.get(0); pps = ppsCall.getProtocolProvider(); } } else { ppsCall = call; pps = ppsCall.getProtocolProvider(); } } else { for (Call conferenceCall : conferenceCalls) { if (pps.equals( conferenceCall.getProtocolProvider())) { ppsCall = conferenceCall; break; } } } } } OperationSetTelephonyConferencing telephonyConferencing = pps.getOperationSet( OperationSetTelephonyConferencing.class); try { if (ppsCall == null) { ppsCall = telephonyConferencing.createConfCall( contactArray, conference); if (conference == null) conference = ppsCall.getConference(); } else { for (String contact : contactArray) { telephonyConferencing.inviteCalleeToCall( contact, ppsCall); } } } catch(Exception e) { logger.error( "Failed to invite callees: " + Arrays.toString(contactArray), e); new ErrorDialog( null, GuiActivator.getResources().getI18NString( "service.gui.ERROR"), e.getMessage(), ErrorDialog.ERROR) .showDialog(); } } } } /** * Invites a list of callees to a specific conference <tt>Call</tt>. If the * specified <tt>Call</tt> is <tt>null</tt>, creates a brand new telephony * conference. */ private static class InviteToConferenceBridgeThread extends Thread { private final ProtocolProviderService callProvider; private final String[] callees; private final Call call; public InviteToConferenceBridgeThread( ProtocolProviderService callProvider, String[] callees, Call call) { this.callProvider = callProvider; this.callees = callees; this.call = call; } @Override public void run() { OperationSetVideoBridge opSetVideoBridge = callProvider.getOperationSet( OperationSetVideoBridge.class); // Normally if this method is called then this should not happen // but we check in order to be sure to be able to proceed. if (opSetVideoBridge == null || !opSetVideoBridge.isActive()) return; if (ConfigurationUtils.isNormalizePhoneNumber()) normalizePhoneNumbers(callees); try { if (call == null) { opSetVideoBridge.createConfCall(callees); } else { for (String contact : callees) opSetVideoBridge.inviteCalleeToCall(contact, call); } } catch(Exception e) { logger.error( "Failed to invite callees: " + Arrays.toString(callees), e); new ErrorDialog( null, GuiActivator.getResources().getI18NString( "service.gui.ERROR"), e.getMessage(), e) .showDialog(); } } } /** * Hangs up a specific <tt>Call</tt> (i.e. all <tt>CallPeer</tt>s associated * with a <tt>Call</tt>), <tt>CallConference</tt> (i.e. all <tt>Call</tt>s * participating in a <tt>CallConference</tt>), or <tt>CallPeer</tt>. */ private static class HangupCallThread extends Thread { private final Call call; private final CallConference conference; private final CallPeer peer; /** * Initializes a new <tt>HangupCallThread</tt> instance which is to hang * up a specific <tt>Call</tt> i.e. all <tt>CallPeer</tt>s associated * with the <tt>Call</tt>. * * @param call the <tt>Call</tt> whose associated <tt>CallPeer</tt>s are * to be hanged up */ public HangupCallThread(Call call) { this(call, null, null); } /** * Initializes a new <tt>HangupCallThread</tt> instance which is to hang * up a specific <tt>CallConference</tt> i.e. all <tt>Call</tt>s * participating in the <tt>CallConference</tt>. * * @param conference the <tt>CallConference</tt> whose participating * <tt>Call</tt>s re to be hanged up */ public HangupCallThread(CallConference conference) { this(null, conference, null); } /** * Initializes a new <tt>HangupCallThread</tt> instance which is to hang * up a specific <tt>CallPeer</tt>. * * @param peer the <tt>CallPeer</tt> to hang up */ public HangupCallThread(CallPeer peer) { this(null, null, peer); } /** * Initializes a new <tt>HangupCallThread</tt> instance which is to hang * up a specific <tt>Call</tt>, <tt>CallConference</tt>, or * <tt>CallPeer</tt>. * * @param call the <tt>Call</tt> whose associated <tt>CallPeer</tt>s are * to be hanged up * @param conference the <tt>CallConference</tt> whose participating * <tt>Call</tt>s re to be hanged up * @param peer the <tt>CallPeer</tt> to hang up */ private HangupCallThread( Call call, CallConference conference, CallPeer peer) { this.call = call; this.conference = conference; this.peer = peer; } @Override public void run() { /* * There is only an OperationSet which hangs up a CallPeer at a time * so prepare a list of all CallPeers to be hanged up. */ Set<CallPeer> peers = new HashSet<CallPeer>(); if (call != null) { Iterator<? extends CallPeer> peerIter = call.getCallPeers(); while (peerIter.hasNext()) peers.add(peerIter.next()); } if (conference != null) peers.addAll(conference.getCallPeers()); if (peer != null) peers.add(peer); for (CallPeer peer : peers) { OperationSetBasicTelephony<?> basicTelephony = peer.getProtocolProvider().getOperationSet( OperationSetBasicTelephony.class); try { basicTelephony.hangupCallPeer(peer); } catch (OperationFailedException ofe) { logger.error("Could not hang up: " + peer, ofe); } } } } /** * Creates the enable local video call thread. */ private static class EnableLocalVideoThread extends Thread { private final Call call; private final boolean enable; /** * Creates the enable local video call thread. * * @param call the call, for which to enable/disable * @param enable */ public EnableLocalVideoThread(Call call, boolean enable) { this.call = call; this.enable = enable; } @Override public void run() { OperationSetVideoTelephony videoTelephony = call.getProtocolProvider().getOperationSet( OperationSetVideoTelephony.class); boolean enableSucceeded = false; if (videoTelephony != null) { // First make sure the desktop sharing is disabled. if (enable && isDesktopSharingEnabled(call)) { JFrame frame = DesktopSharingFrame.getFrameForCall(call); if (frame != null) frame.dispose(); } try { videoTelephony.setLocalVideoAllowed(call, enable); enableSucceeded = true; } catch (OperationFailedException ex) { logger.error( "Failed to toggle the streaming of local video.", ex); ResourceManagementService r = GuiActivator.getResources(); String title = r.getI18NString( "service.gui.LOCAL_VIDEO_ERROR_TITLE"); String message = r.getI18NString( "service.gui.LOCAL_VIDEO_ERROR_MESSAGE"); GuiActivator.getAlertUIService().showAlertPopup( title, message, ex); } } // If the operation didn't succeeded for some reason, make sure the // video button doesn't remain selected. if (enable && !enableSucceeded) getActiveCallContainer(call).setVideoButtonSelected(false); } } /** * Puts on hold the given <tt>CallPeer</tt>. */ private static class PutOnHoldCallPeerThread extends Thread { private final CallPeer callPeer; private final boolean isOnHold; public PutOnHoldCallPeerThread(CallPeer callPeer, boolean isOnHold) { this.callPeer = callPeer; this.isOnHold = isOnHold; } @Override public void run() { OperationSetBasicTelephony<?> telephony = callPeer.getProtocolProvider().getOperationSet( OperationSetBasicTelephony.class); try { if (isOnHold) telephony.putOnHold(callPeer); else telephony.putOffHold(callPeer); } catch (OperationFailedException ex) { logger.error( "Failed to put" + callPeer.getAddress() + (isOnHold ? " on hold." : " off hold."), ex); } } } /** * Merges specific existing <tt>Call</tt>s into a specific telephony * conference. */ private static class MergeExistingCalls extends Thread { /** * The telephony conference in which {@link #calls} are to be merged. */ private final CallConference conference; /** * Second call. */ private final Collection<Call> calls; /** * Initializes a new <tt>MergeExistingCalls</tt> instance which is to * merge specific existing <tt>Call</tt>s into a specific telephony * conference. * * @param conference the telephony conference in which the specified * <tt>Call</tt>s are to be merged * @param calls the <tt>Call</tt>s to be merged into the specified * telephony conference */ public MergeExistingCalls( CallConference conference, Collection<Call> calls) { this.conference = conference; this.calls = calls; } /** * Puts off hold the <tt>CallPeer</tt>s of a specific <tt>Call</tt> * which are locally on hold. * * @param call the <tt>Call</tt> which is to have its <tt>CallPeer</tt>s * put off hold */ private void putOffHold(Call call) { Iterator<? extends CallPeer> peers = call.getCallPeers(); OperationSetBasicTelephony<?> telephony = call.getProtocolProvider().getOperationSet( OperationSetBasicTelephony.class); while (peers.hasNext()) { CallPeer callPeer = peers.next(); boolean putOffHold = true; if(callPeer instanceof MediaAwareCallPeer) { putOffHold = ((MediaAwareCallPeer<?,?,?>) callPeer) .getMediaHandler() .isLocallyOnHold(); } if(putOffHold) { try { telephony.putOffHold(callPeer); Thread.sleep(400); } catch(Exception ofe) { logger.error("Failed to put off hold.", ofe); } } } } @Override public void run() { // conference for (Call call : conference.getCalls()) putOffHold(call); // calls if (!calls.isEmpty()) { for(Call call : calls) { if (conference.containsCall(call)) continue; putOffHold(call); /* * Dispose of the CallPanel associated with the Call which * is to be merged. */ closeCallContainerIfNotNecessary(conference, false); call.setConference(conference); } } } } /** * Shows a warning window to warn the user that she's about to start a * desktop sharing session. * * @return <tt>true</tt> if the user has accepted the desktop sharing * session; <tt>false</tt>, otherwise */ private static boolean showDesktopSharingWarning() { Boolean isWarningEnabled = GuiActivator.getConfigurationService().getBoolean( desktopSharingWarningProperty, true); if (isWarningEnabled.booleanValue()) { ResourceManagementService resources = GuiActivator.getResources(); MessageDialog warningDialog = new MessageDialog( null, resources.getI18NString("service.gui.WARNING"), resources.getI18NString( "service.gui.DESKTOP_SHARING_WARNING"), true); switch (warningDialog.showDialog()) { case MessageDialog.OK_RETURN_CODE: return true; case MessageDialog.CANCEL_RETURN_CODE: return false; case MessageDialog.OK_DONT_ASK_CODE: GuiActivator.getConfigurationService().setProperty( desktopSharingWarningProperty, false); return true; } } return true; } /** * Normalizes the phone numbers (if any) in a list of <tt>String</tt> * contact addresses or phone numbers. * * @param callees the list of contact addresses or phone numbers to be * normalized */ private static void normalizePhoneNumbers(String callees[]) { for (int i = 0 ; i < callees.length ; i++) callees[i] = GuiActivator.getPhoneNumberI18nService() .normalize(callees[i]); } /** * Throws a <tt>RuntimeException</tt> if the current thread is not the AWT * event dispatching thread. */ public static void assertIsEventDispatchingThread() { if (!SwingUtilities.isEventDispatchThread()) { throw new RuntimeException( "The methon can be called only on the AWT event dispatching" + " thread."); } } /** * Finds the <tt>CallPanel</tt>, if any, which depicts a specific * <tt>CallConference</tt>. * <p> * <b>Note</b>: The method can be called only on the AWT event dispatching * thread. * </p> * * @param conference the <tt>CallConference</tt> to find the depicting * <tt>CallPanel</tt> of * @return the <tt>CallPanel</tt> which depicts the specified * <tt>CallConference</tt> if such a <tt>CallPanel</tt> exists; otherwise, * <tt>null</tt> * @throws RuntimeException if the method is not called on the AWT event * dispatching thread */ private static CallPanel findCallPanel(CallConference conference) { synchronized (callPanels) { return callPanels.get(conference); } } /** * Notifies {@link #callPanels} about a specific <tt>CallEvent</tt> received * by <tt>CallManager</tt> (because they may need to update their UI, for * example). * <p> * <b>Note</b>: The method can be called only on the AWT event dispatching * thread. * </p> * * @param ev the <tt>CallEvent</tt> received by <tt>CallManager</tt> which * is to be forwarded to <tt>callPanels</tt> for further * <tt>CallPanel</tt>-specific handling * @throws RuntimeException if the method is not called on the AWT event * dispatching thread */ private static void forwardCallEventToCallPanels(CallEvent ev) { assertIsEventDispatchingThread(); CallPanel[] callPanels; synchronized (CallManager.callPanels) { Collection<CallPanel> values = CallManager.callPanels.values(); callPanels = values.toArray(new CallPanel[values.size()]); } for (CallPanel callPanel : callPanels) { try { callPanel.onCallEvent(ev); } catch (Exception ex) { /* * There is no practical reason while the failure of a CallPanel * to handle the CallEvent should cause the other CallPanels to * be left out-of-date. */ logger.error("A CallPanel failed to handle a CallEvent", ex); } } } /** * Creates a call for the supplied operation set. * @param opSetClass the operation set to use to create call. * @param protocolProviderService the protocol provider * @param contact the contact address to call */ static void createCall(Class<? extends OperationSet> opSetClass, ProtocolProviderService protocolProviderService, String contact) { createCall(opSetClass, protocolProviderService, contact, null); } /** * Creates a call for the supplied operation set. * @param opSetClass the operation set to use to create call. * @param protocolProviderService the protocol provider * @param contact the contact address to call * @param uiContact the <tt>MetaContact</tt> we're calling */ static void createCall( Class<? extends OperationSet> opSetClass, ProtocolProviderService protocolProviderService, String contact, UIContactImpl uiContact) { if (opSetClass.equals(OperationSetBasicTelephony.class)) { createCall(protocolProviderService, contact, uiContact); } else if (opSetClass.equals(OperationSetVideoTelephony.class)) { createVideoCall(protocolProviderService, contact, uiContact); } else if (opSetClass.equals(OperationSetDesktopStreaming.class)) { createDesktopSharing( protocolProviderService, contact, uiContact); } } /** * Creates a call for the default contact of the metacontact * * @param metaContact the metacontact that will be called. * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param shareRegion if <tt>true</tt> will share a region of the desktop. */ public static void call(MetaContact metaContact, boolean isVideo, boolean isDesktop, boolean shareRegion) { Contact contact = metaContact .getDefaultContact(getOperationSetForCall(isVideo, isDesktop)); call(contact, isVideo, isDesktop, shareRegion); } /** * A particular contact has been selected no options to select * will just call it. * @param contact the contact to call * @param contactResource the specific contact resource * @param isVideo is video enabled * @param isDesktop is desktop sharing enabled * @param shareRegion is sharing the whole desktop or just a region. */ public static void call(Contact contact, ContactResource contactResource, boolean isVideo, boolean isDesktop, boolean shareRegion) { if(isDesktop) { if(shareRegion) { createRegionDesktopSharing( contact.getProtocolProvider(), contact.getAddress(), null); } else createDesktopSharing(contact.getProtocolProvider(), contact.getAddress(), null); } else { new CreateCallThread( contact.getProtocolProvider(), contact, contactResource, isVideo).start(); } } /** * Creates a call to the conference described in * <tt>conferenceDescription</tt> through <tt>protocolProvider</tt> * * @param protocolProvider the protocol provider through which to create * the call * @param conferenceDescription the description of the conference to call * @param chatRoom the chat room associated with the call. */ public static void call(ProtocolProviderService protocolProvider, ConferenceDescription conferenceDescription, ChatRoom chatRoom) { new CreateCallThread(protocolProvider, conferenceDescription, chatRoom) .start(); } /** * A particular contact has been selected no options to select * will just call it. * @param contact the contact to call * @param isVideo is video enabled * @param isDesktop is desktop sharing enabled * @param shareRegion is sharing the whole desktop or just a region. */ public static void call(Contact contact, boolean isVideo, boolean isDesktop, boolean shareRegion) { if(isDesktop) { if(shareRegion) { createRegionDesktopSharing( contact.getProtocolProvider(), contact.getAddress(), null); } else createDesktopSharing(contact.getProtocolProvider(), contact.getAddress(), null); } else { new CreateCallThread( contact.getProtocolProvider(), contact, null, isVideo).start(); } } /** * Calls a phone showing a dialog to choose a provider. * @param phone phone to call * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param shareRegion if <tt>true</tt> will share a region of the desktop. */ public static void call(final String phone, boolean isVideo, boolean isDesktop, final boolean shareRegion) { call(phone, null, isVideo, isDesktop, shareRegion); } /** * Calls a phone showing a dialog to choose a provider. * @param phone phone to call * @param uiContact the <tt>UIContactImpl</tt> we're calling * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param shareRegion if <tt>true</tt> will share a region of the desktop. */ public static void call(final String phone, final UIContactImpl uiContact, boolean isVideo, boolean isDesktop, final boolean shareRegion) { List<ProtocolProviderService> providers = CallManager.getTelephonyProviders(); if(providers.size() > 1) { ChooseCallAccountDialog chooseAccount = new ChooseCallAccountDialog( phone, getOperationSetForCall(isVideo, isDesktop), providers) { @Override public void callButtonPressed() { if(shareRegion) { createRegionDesktopSharing( getSelectedProvider(), phone, uiContact); } else super.callButtonPressed(); } }; chooseAccount.setUIContact(uiContact); chooseAccount.setVisible(true); } else { createCall(providers.get(0), phone, uiContact); } } /** * Obtain operation set checking the params. * @param isVideo if <tt>true</tt> use OperationSetVideoTelephony. * @param isDesktop if <tt>true</tt> use OperationSetDesktopStreaming. * @return the operation set, default is OperationSetBasicTelephony. */ private static Class<? extends OperationSet> getOperationSetForCall( boolean isVideo, boolean isDesktop) { if(isVideo) { if(isDesktop) return OperationSetDesktopStreaming.class; else return OperationSetVideoTelephony.class; } else return OperationSetBasicTelephony.class; } /** * Call any of the supplied details. * * @param uiContactDetailList the list with details to choose for calling * @param uiContact the <tt>UIContactImpl</tt> to check what is enabled, * available. * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param invoker the invoker component * @param location the location where this was invoked. */ public static void call(List<UIContactDetail> uiContactDetailList, UIContactImpl uiContact, boolean isVideo, boolean isDesktop, JComponent invoker, Point location) { call(uiContactDetailList, uiContact, isVideo, isDesktop, invoker, location, true); } /** * Call any of the supplied details. * * @param uiContactDetailList the list with details to choose for calling * @param uiContact the <tt>UIContactImpl</tt> to check what is enabled, * available. * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param invoker the invoker component * @param location the location where this was invoked. * @param usePreferredProvider whether to use the <tt>uiContact</tt> * preferredProvider if provided. */ private static void call(List<UIContactDetail> uiContactDetailList, UIContactImpl uiContact, boolean isVideo, boolean isDesktop, JComponent invoker, Point location, boolean usePreferredProvider) { ChooseCallAccountPopupMenu chooseCallAccountPopupMenu = null; Class<? extends OperationSet> opsetClass = getOperationSetForCall(isVideo, isDesktop); UIPhoneUtil contactPhoneUtil = null; if (uiContact != null && uiContact.getDescriptor() instanceof MetaContact) contactPhoneUtil = UIPhoneUtil .getPhoneUtil((MetaContact) uiContact.getDescriptor()); if(contactPhoneUtil != null) { boolean addAdditionalNumbers = false; if(!isVideo || ConfigurationUtils .isRouteVideoAndDesktopUsingPhoneNumberEnabled()) { addAdditionalNumbers = true; } else { if(isVideo && contactPhoneUtil != null) { // lets check is video enabled in additional numbers addAdditionalNumbers = contactPhoneUtil.isVideoCallEnabled() ? isDesktop ? contactPhoneUtil.isDesktopSharingEnabled() : true : false; } } if(addAdditionalNumbers) { uiContactDetailList.addAll( contactPhoneUtil.getAdditionalNumbers()); } } if (uiContactDetailList.size() == 1) { UIContactDetail detail = uiContactDetailList.get(0); ProtocolProviderService preferredProvider = null; if(usePreferredProvider) preferredProvider = detail.getPreferredProtocolProvider(opsetClass); List<ProtocolProviderService> providers = null; String protocolName = null; if (preferredProvider != null) { if (preferredProvider.isRegistered()) { createCall(opsetClass, preferredProvider, detail.getAddress(), uiContact); } // If we have a provider, but it's not registered we try to // obtain all registered providers for the same protocol as the // given preferred provider. else { protocolName = preferredProvider.getProtocolName(); providers = AccountUtils.getRegisteredProviders(protocolName, opsetClass); } } // If we don't have a preferred provider we try to obtain a // preferred protocol name and all registered providers for it. else { protocolName = detail.getPreferredProtocol(opsetClass); if (protocolName != null) providers = AccountUtils.getRegisteredProviders(protocolName, opsetClass); else providers = AccountUtils.getRegisteredProviders(opsetClass); } // If our call didn't succeed, try to call through one of the other // protocol providers obtained above. if (providers != null) { int providersCount = providers.size(); if (providersCount <= 0) { new ErrorDialog(null, GuiActivator.getResources().getI18NString( "service.gui.CALL_FAILED"), GuiActivator.getResources().getI18NString( "service.gui.NO_ONLINE_TELEPHONY_ACCOUNT")) .showDialog(); } else if (providersCount == 1) { createCall( opsetClass, providers.get(0), detail.getAddress(), uiContact); } else if (providersCount > 1) { chooseCallAccountPopupMenu = new ChooseCallAccountPopupMenu( invoker, detail.getAddress(), providers, opsetClass); } } } else if (uiContactDetailList.size() > 1) { chooseCallAccountPopupMenu = new ChooseCallAccountPopupMenu(invoker, uiContactDetailList, opsetClass); } // If the choose dialog is created we're going to show it. if (chooseCallAccountPopupMenu != null) { if (uiContact != null) chooseCallAccountPopupMenu.setUIContact(uiContact); chooseCallAccountPopupMenu.showPopupMenu(location.x, location.y); } } /** * Call the ui contact. * * @param uiContact the contact to call. * @param isVideo if <tt>true</tt> will create video call. * @param isDesktop if <tt>true</tt> will share the desktop. * @param invoker the invoker component * @param location the location where this was invoked. */ public static void call(UIContact uiContact, boolean isVideo, boolean isDesktop, JComponent invoker, Point location) { UIContactImpl uiContactImpl = null; if(uiContact instanceof UIContactImpl) { uiContactImpl = (UIContactImpl) uiContact; } List<UIContactDetail> telephonyContacts = uiContact.getContactDetailsForOperationSet( getOperationSetForCall(isVideo, isDesktop)); boolean ignorePreferredProvider = GuiActivator.getConfigurationService().getBoolean( IGNORE_PREFERRED_PROVIDER_PROP, false); call( telephonyContacts, uiContactImpl, isVideo, isDesktop, invoker, location, !ignorePreferredProvider); } /** * Tries to resolves a peer address into a display name, by reqesting the * <tt>ContactSourceService</tt>s. This function returns only the * first match. * * @param peerAddress The peer address. * @param listener the listener to fire change events for later resolutions * of display name and image, if exist. * @return The corresponding display name, if there is a match. Null * otherwise. */ private static String queryContactSource( String peerAddress, DetailsResolveListener listener) { String displayName = null; if(!StringUtils.isNullOrEmpty(peerAddress)) { ContactSourceSearcher searcher = new ContactSourceSearcher(peerAddress, listener); if(listener == null) { searcher.run(); displayName = searcher.displayName; } else new Thread(searcher, searcher.getClass().getName()).start(); } return displayName; } /** * Runnable that will search for a source contact and when found will * fire events to inform that display name or contact image is found. */ private static class ContactSourceSearcher implements Runnable { private final DetailsResolveListener listener; private final String peerAddress; private String displayName; private byte[] displayImage; private ContactSourceSearcher( String peerAddress, DetailsResolveListener listener) { this.peerAddress = peerAddress; this.listener = listener; } @Override public void run() { Vector<ResolveAddressToDisplayNameContactQueryListener> resolvers = new Vector<ResolveAddressToDisplayNameContactQueryListener> (1, 1); // will strip the @server-address part, as the regular expression // will match it int index = peerAddress.indexOf("@"); String peerUserID = (index > -1) ? peerAddress.substring(0, index) : peerAddress; // searches for the whole number/username or with the @serverpart String quotedPeerUserID = Pattern.quote(peerUserID); Pattern pattern = Pattern.compile( "^(" + quotedPeerUserID + "|" + quotedPeerUserID + "@.*)$"); // Queries all available resolvers for(ContactSourceService css : GuiActivator.getContactSources()) { if(css.getType() != ContactSourceService.SEARCH_TYPE) continue; ContactQuery query; if(css instanceof ExtendedContactSourceService) { // use the pattern method of (ExtendedContactSourceService) query = ((ExtendedContactSourceService)css) .createContactQuery(pattern); } else { query = css.createContactQuery(peerUserID); } if(query == null) continue; resolvers.add( new ResolveAddressToDisplayNameContactQueryListener(query)); query.start(); } long startTime = System.currentTimeMillis(); // The detault timeout is set to 500ms. long timeout = listener == null ? 500 : -1; boolean hasRunningResolver = true; // Loops until we found a valid display name and image, // or waits for timeout if any. while((displayName == null || displayImage == null) && hasRunningResolver && (listener == null || listener.isInterested())) { hasRunningResolver = false; for(int i = 0; i < resolvers.size() && (displayName == null || displayImage == null) && (listener == null || listener.isInterested()); ++i) { ResolveAddressToDisplayNameContactQueryListener resolver = resolvers.get(i); if(!resolver.isRunning()) { if(displayName == null && resolver.isFoundName()) { displayName = resolver.getResolvedName(); // If this is the same result as the peer address, // then that is not what we are looking for. Then, // continue the search. if(displayName.equals(peerAddress)) { displayName = null; } if(listener != null && displayName != null) { // fire listener.displayNameUpdated(displayName); } } if(displayImage == null && resolver.isFoundImage()) { displayImage = resolver.getResolvedImage(); String name = resolver.getResolvedName(); // If this is the same result as the peer address, // then that is not what we are looking for. Then, // continue the search. if(name != null && name.equals(peerAddress)) { displayImage = null; } else if(listener != null && displayImage != null) { // fire listener.imageUpdated(displayImage); } } } else hasRunningResolver = true; } Thread.yield(); if( timeout > 0 && System.currentTimeMillis() - startTime >= timeout) break; } // Free lasting resolvers. for(int i = 0; i < resolvers.size(); ++i) { ResolveAddressToDisplayNameContactQueryListener resolver = resolvers.get(i); if(resolver.isRunning()) { resolver.stop(); } } } } /** * A listener that will be notified for found source contacts details. */ public static interface DetailsResolveListener { /** * When a display name is found. * @param displayName the name that was found. */ public void displayNameUpdated(String displayName); /** * The image that was found. * @param image the image that was found. */ public void imageUpdated(byte[] image); /** * Whether the listener is still interested in the events. * When the window/panel using this resolver listener is closed * will return false; * @return whether the listener is still interested in the events. */ public boolean isInterested(); } }
package br.com.caelum.brutal.dao; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import br.com.caelum.brutal.model.Answer; import br.com.caelum.brutal.model.Comment; import br.com.caelum.brutal.model.Question; import br.com.caelum.brutal.model.SubscribableDTO; import br.com.caelum.brutal.model.Tag; import br.com.caelum.brutal.model.User; public class CommentDAOTest extends DatabaseTestCase { private CommentDAO comments; @Before public void setup() { comments = new CommentDAO(session); } @Test public void should_find_recent_comments_and_subscribed_users() { User artur = user("question author", "qauthor@gmail"); User iFag = user("question author", "otherqauthor@gmail"); User valeriano = user("answer author", "aauthor@gmail"); User alcoolatra = user("comment author", "cauthor@gmail"); Tag tagDefault = tag("default"); session.save(tagDefault); Question beberFazMal = question(artur, Arrays.asList(tagDefault)); Answer figadoVaiProSaco = answer("Por que seu figado vai pro saco", beberFazMal, valeriano); Question androidRuim = question(iFag, Arrays.asList(tagDefault)); Answer naoEhRuby = answer("Por que não é ruby, ai não é bacana.", androidRuim, valeriano); Comment naoFazMal = new Comment(alcoolatra, "O que te levou a pensar que faz mal? Faz nada não."); beberFazMal.add(naoFazMal); session.save(artur); session.save(valeriano); session.save(alcoolatra); session.save(iFag); session.save(naoFazMal); session.save(beberFazMal); session.save(figadoVaiProSaco); session.save(androidRuim); session.save(naoEhRuby); List<SubscribableDTO> recentComments = comments.getSubscribablesAfter(new DateTime().minusHours(3)); assertEquals(2, recentComments.size()); assertEquals(valeriano.getId(), recentComments.get(0).getUser().getId()); assertEquals(naoFazMal.getId(), ((Comment) recentComments.get(0).getSubscribable()).getId()); assertEquals(artur.getId(), recentComments.get(1).getUser().getId()); assertEquals(naoFazMal.getId(), ((Comment) recentComments.get(1).getSubscribable()).getId()); assertEquals(beberFazMal.getId(), recentComments.get(0).getQuestion().getId()); } @Test public void should_not_find_unsubscribed_and_find_subscribed_users_for_comments() { User artur = user("question author", "artur@gmail.com"); artur.setSubscribed(false); User valeriano = user("answer author", "valeriano@gmail.com"); valeriano.setSubscribed(false); User iFag = user("question author", "ifag@gmail.com"); User alcoolatra = user("comment author", "alcoolatra@gmail.com"); User leo = user("question author", "leo@gmail.com"); User chico = user("answer author", "chico@gmail.com"); session.save(artur); session.save(valeriano); session.save(alcoolatra); session.save(iFag); session.save(leo); session.save(chico); Tag tagDefault = tag("java"); session.save(tagDefault); //comment added to question but question and answer author should not be notified Question beberFazMal = question(artur, Arrays.asList(tagDefault)); Answer figadoVaiProSaco = answer("Por que seu figado vai pro saco", beberFazMal, valeriano); Comment naoFazMal = new Comment(alcoolatra, "O que te levou a pensar que faz mal? Faz nada não."); beberFazMal.add(naoFazMal); session.save(naoFazMal); session.save(beberFazMal); session.save(figadoVaiProSaco); //comment added to answer (question and answer author must be notified) Question androidRuim = question(iFag, Arrays.asList(tagDefault)); Answer naoEhRuby = answer("Por que não é ruby, ai não é bacana.", androidRuim, alcoolatra); Comment naoEhNao = comment(valeriano, "nao eh ruim nao"); naoEhRuby.add(naoEhNao); session.save(naoEhNao); session.save(androidRuim); session.save(naoEhRuby); //comment added to question (question and answer authors must be notified) Question comoFaz = question(leo, Arrays.asList(tagDefault)); Answer fazAssim = answer("faz assim faz assim faz assim faz assim faz assim", comoFaz, chico); Comment fazerOQue = comment(valeriano, "quer fazer o que?"); comoFaz.add(fazerOQue); session.save(fazerOQue); session.save(comoFaz); session.save(fazAssim); List<User> users = new ArrayList<>(); List<SubscribableDTO> recentComments = comments.getSubscribablesAfter(new DateTime().minusHours(3)); for (SubscribableDTO subscribableDTO : recentComments) { users.add(subscribableDTO.getUser()); } assertThat(users, not(hasItem(artur))); assertThat(users, not(hasItem(valeriano))); assertThat(users, hasItems(alcoolatra, iFag, leo, chico)); } @Test public void should_not_return_dto_with_user_equals_comment_author() { User answerAuthor = user("user","user@x.com"); User questionAuthor = user("other", "other@x.com"); Tag tag = tag("teste"); Question question = question(questionAuthor, Arrays.asList(tag)); Answer answer = answer("descriptiondescriptiondescriptiondescriptiondescriptiondescription", question, answerAuthor); Comment answerComment = comment(answerAuthor, "comentariocomentariocomentariocomentariocomentario"); question.add(answerComment); session.save(questionAuthor); session.save(answerAuthor); session.save(answerComment); session.save(tag); session.save(question); session.save(answer); List<SubscribableDTO> recentComments = comments.getSubscribablesAfter(new DateTime().minusHours(3)); List<User> users = new ArrayList<>(); for (SubscribableDTO subscribableDTO : recentComments) { User user = subscribableDTO.getUser(); users.add(user); System.out.println(user); } assertThat(users, not(hasItem(answerAuthor))); } }
package net.java.sip.communicator.impl.protocol.msn; import net.sf.jml.*; /** * Contactlist modification listener receives events * for successful chngings * * @author Damian Minkov */ public class EventAdapter implements MsnContactListEventListener { /** * Message is successfully delivered * @param transactionID int the transaction that send the message */ public void messageDelivered(int transactionID){} /** * Message is not delivered * @param transactionID int the transaction that send the message */ public void messageDeliveredFailed(int transactionID){} /** * Indicates that a contact is successfully added * @param contact MsnContact the contact */ public void contactAdded(MsnContact contact){} /** * Indicates that a contact is successfully added to the group * @param contact MsnContact the contact * @param group MsnGroup the group */ public void contactAddedInGroup(MsnContact contact, MsnGroup group){} /** * Indicates successful removing of a contact * @param contact MsnContact the removed contact */ public void contactRemoved(MsnContact contact){} /** * Indicates successful removing of a contact from a group * @param contact MsnContact the contact removed * @param group MsnGroup the group */ public void contactRemovedFromGroup(MsnContact contact, MsnGroup group){} /** * Indicates that a group is successfully added * @param group MsnGroup the added group */ public void groupAdded(MsnGroup group){} /** * Indicates that a group is successfully renamed * @param group MsnGroup the renmaed group with the new name */ public void groupRenamed(MsnGroup group){} /** * Indicates successful removing of a group * @param id String the id of the removed group */ public void groupRemoved(String id){} /** * Indicates that we are logged out * beacuse account logged in from other location */ public void loggingFromOtherLocation(){} }
package com.celements.store; import static com.celements.common.test.CelementsTestUtils.*; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang.exception.ExceptionUtils; import org.easymock.IAnswer; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; import org.hibernate.impl.AbstractQueryImpl; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.cache.CacheFactory; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.context.ExecutionContextException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.WikiReference; import com.celements.common.test.AbstractComponentTest; import com.celements.navigation.INavigationClassConfig; import com.celements.pagetype.IPageTypeClassConfig; import com.celements.store.DocumentCacheStore.InvalidateState; import com.celements.web.service.IWebUtilsService; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConfig; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.PropertyInterface; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.store.XWikiCacheStore; import com.xpn.xwiki.store.XWikiCacheStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.hibernate.HibernateSessionFactory; import com.xpn.xwiki.util.AbstractXWikiRunnable; import com.xpn.xwiki.web.Utils; public class ConcurrentCacheTest extends AbstractComponentTest { private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentCacheTest.class); private volatile XWikiCacheStore theCacheStore; private volatile DocumentCacheStore theCacheStoreFixed; private volatile Map<DocumentReference, List<BaseObject>> baseObjMap; private volatile Map<Integer, List<String[]>> propertiesMap; private volatile DocumentReference testDocRef; private static volatile Collection<Object> defaultMocks; private static volatile XWikiContext defaultContext; private final static AtomicBoolean fastFail = new AtomicBoolean(); private final String wikiName = "testWiki"; private final WikiReference wikiRef = new WikiReference(wikiName); private final String testFullName = "TestSpace.TestDoc"; private XWikiConfig configMock; private SessionFactory sessionFactoryMock; private IPageTypeClassConfig pageTypeClassConfig; private INavigationClassConfig navClassConfig; private IWebUtilsService webUtilsService; /** * CAUTION: the doc load counting with AtomicIntegers leads to better memory visibility * and thus reduces likeliness of a race condition. Hence it may camouflage the race condition! * Nevertheless is it important to check that the cache is working at all. * Hence test it with and without counting. */ private final boolean verifyDocLoads = false; private final AtomicInteger countDocLoads = new AtomicInteger(); private final AtomicInteger expectedCountDocLoads = new AtomicInteger(); private final AtomicInteger expectedCountDocLoadsFixed = new AtomicInteger(); private final AtomicInteger failedToRemoveFromCacheCount = new AtomicInteger(0); private final AtomicInteger invalidatedLoadingCount = new AtomicInteger(0); private final AtomicInteger failedToInvalidatedLoadingCount = new AtomicInteger(0); private final AtomicInteger invalidatedMultipleCount = new AtomicInteger(0); @SuppressWarnings("deprecation") @Before public void setUp_ConcurrentCacheTest() throws Exception { pageTypeClassConfig = Utils.getComponent(IPageTypeClassConfig.class); navClassConfig = Utils.getComponent(INavigationClassConfig.class); webUtilsService = Utils.getComponent(IWebUtilsService.class); getContext().setDatabase(wikiName); sessionFactoryMock = createMockAndAddToDefault(SessionFactory.class); Utils.getComponent(HibernateSessionFactory.class).setSessionFactory(sessionFactoryMock); testDocRef = new DocumentReference(wikiName, "TestSpace", "TestDoc"); configMock = createMockAndAddToDefault(XWikiConfig.class); expect(getWikiMock().getConfig()).andReturn(configMock).anyTimes(); expect(configMock.getProperty(eq("xwiki.store.hibernate.path"), eq( "/WEB-INF/hibernate.cfg.xml"))).andReturn("testhibernate.cfg.xml"); expect(getWikiMock().Param(eq("xwiki.store.cache.capacity"))).andReturn(null).anyTimes(); expect(getWikiMock().Param(eq("xwiki.store.cache.pageexistcapacity"))).andReturn( null).anyTimes(); CacheFactory cacheFactory = Utils.getComponent(CacheFactory.class, "jbosscache"); expect(getWikiMock().getCacheFactory()).andReturn(cacheFactory).anyTimes(); expect(getWikiMock().getPlugin(eq("monitor"), isA(XWikiContext.class))).andReturn( null).anyTimes(); expect(getWikiMock().hasDynamicCustomMappings()).andReturn(false).anyTimes(); expect(getWikiMock().isVirtualMode()).andReturn(false).anyTimes(); expect(getWikiMock().Param(eq("xwiki.store.hibernate.useclasstables.read"), eq("1"))).andReturn( "0").anyTimes(); expect(getWikiMock().getXClass(isA(DocumentReference.class), isA( XWikiContext.class))).andStubDelegateTo(new TestXWiki()); createBaseObjects(); createPropertiesMap(); } @Test public void test_singleThreaded_sync_fixed() throws Exception { setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); preloadCache(theCacheStoreFixed); if (verifyDocLoads) { assertEquals(expectedCountDocLoadsFixed.get(), countDocLoads.get()); } assertNotNull("Expecting document in cache.", theCacheStoreFixed.getDocFromCache( theCacheStoreFixed.getKeyWithLang(testDocRef, ""))); verifyDefault(); } @Test public void test_singleThreaded_sync() throws Exception { setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); preloadCache(theCacheStore); if (verifyDocLoads) { assertEquals(expectedCountDocLoads.get(), countDocLoads.get()); } assertNotNull(theCacheStore.getCache().get(theCacheStore.getKey(wikiName, testFullName, ""))); verifyDefault(); } @Test public void test_singleThreaded_async_fixed() throws Exception { setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); preloadCache(theCacheStoreFixed); ScheduledExecutorService theExecutor = Executors.newScheduledThreadPool(1); Future<LoadDocCheckResult> testFuture = theExecutor.submit( (Callable<LoadDocCheckResult>) new LoadXWikiDocCommand(theCacheStoreFixed)); theExecutor.shutdown(); while (!theExecutor.isTerminated()) { theExecutor.awaitTermination(1, TimeUnit.SECONDS); } LoadDocCheckResult result = testFuture.get(); assertTrue(Arrays.deepToString(result.getMessages().toArray()), result.isSuccessfull()); if (verifyDocLoads) { assertEquals(expectedCountDocLoadsFixed.get(), countDocLoads.get()); } verifyDefault(); } @Test public void test_singleThreaded_async() throws Exception { setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); preloadCache(theCacheStore); ScheduledExecutorService theExecutor = Executors.newScheduledThreadPool(1); Future<LoadDocCheckResult> testFuture = theExecutor.submit( (Callable<LoadDocCheckResult>) new LoadXWikiDocCommand(theCacheStore)); theExecutor.shutdown(); while (!theExecutor.isTerminated()) { theExecutor.awaitTermination(1, TimeUnit.SECONDS); } LoadDocCheckResult result = testFuture.get(); assertTrue(Arrays.deepToString(result.getMessages().toArray()), result.isSuccessfull()); if (verifyDocLoads) { assertEquals(expectedCountDocLoads.get(), countDocLoads.get()); } verifyDefault(); } @Test public void test_multiRuns_singleThreaded_scenario1_fixed() throws Exception { int cores = 1; int executeRuns = 5000; setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); assertSuccessFullRuns(testScenario1(theCacheStoreFixed, cores, executeRuns)); if (verifyDocLoads) { assertEquals(expectedCountDocLoadsFixed.get(), countDocLoads.get()); } verifyDefault(); } @Test public void test_multiRuns_singleThreaded_scenario1() throws Exception { int cores = 1; int executeRuns = 5000; setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); assertSuccessFullRuns(testScenario1(theCacheStore, cores, executeRuns)); if (verifyDocLoads) { assertEquals(expectedCountDocLoads.get(), countDocLoads.get()); } verifyDefault(); } @Test public void test_multiThreaded_scenario1_fixed_DocumentCacheStore() throws Exception { int cores = Runtime.getRuntime().availableProcessors(); assertTrue("This tests needs real multi core processors, but found " + cores, cores > 1); // tested on an intel quadcore 4770 // without triggering any race condition! Tested with up to 10'000'000 executeRuns! // int executeRuns = 10000000; int executeRuns = 30000; setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); assertSuccessFullRuns(testScenario1(theCacheStoreFixed, cores, executeRuns)); if (verifyDocLoads) { int countLoads = countDocLoads.get(); int expectedLoads = expectedCountDocLoadsFixed.get(); final String failingDetails = " expected loads '" + expectedLoads + "' must be lower equal to count loads '" + countLoads + "'\n diff '" + (countLoads - expectedLoads) + "'\n invalidatedLoadingCount '" + invalidatedLoadingCount.get() + "'\n invalidatedMultipleCount '" + invalidatedMultipleCount.get() + "'\n failedToInvalidatedLoadingCount '" + failedToInvalidatedLoadingCount.get() + "'\n failedToRemoveFromCacheCount '" + failedToRemoveFromCacheCount.get() + "'"; assertTrue("invalidating during load leads to multiple loads for one invalidation, thus\n" + failingDetails, expectedLoads <= countLoads); } verifyDefault(); } /** * IMPORTANT: This test shows, that XWikiCacheStore is broken!!! */ @Test public void test_failing_multiThreaded_scenario1_XWikiCacheStore() throws Exception { int cores = Runtime.getRuntime().availableProcessors(); assertTrue("This tests needs real multi core processors, but found " + cores, cores > 1); // on an intel quadcore 4770 first race condition generally happens already after a few thousand int executeRuns = 30000; setupTestMocks(); replayDefault(); initStorePrepareMultiThreadMocks(); List<Future<LoadDocCheckResult>> testResults = testScenario1(theCacheStore, cores, executeRuns); boolean failed = false; try { assertSuccessFullRuns(testResults); } catch (AssertionError exp) { // expected failed = true; } if (!failed) { fail(); } if (verifyDocLoads) { assertTrue("no synchronisation on loading must lead to concurrent loads." + " Thus more than the expected loads must have happend.", expectedCountDocLoads.get() <= countDocLoads.get()); } verifyDefault(); } private void preloadCache(XWikiCacheStoreInterface store) throws Exception { if (verifyDocLoads) { countDocLoads.set(0); expectedCountDocLoads.set(1); expectedCountDocLoadsFixed.set(1); } LoadXWikiDocCommand testLoadCommand = new LoadXWikiDocCommand(store); LoadDocCheckResult result = testLoadCommand.call(); assertTrue(Arrays.deepToString(result.getMessages().toArray()), result.isSuccessfull()); } private void setupTestMocks() { Session sessionMock = createMockAndAddToDefault(Session.class); expect(sessionFactoryMock.openSession()).andReturn(sessionMock).anyTimes(); sessionMock.setFlushMode(eq(FlushMode.COMMIT)); expectLastCall().atLeastOnce(); sessionMock.setFlushMode(eq(FlushMode.MANUAL)); expectLastCall().atLeastOnce(); Transaction transactionMock = createMockAndAddToDefault(Transaction.class); expect(sessionMock.beginTransaction()).andReturn(transactionMock).anyTimes(); transactionMock.rollback(); expectLastCall().anyTimes(); expect(sessionMock.close()).andReturn(null).anyTimes(); XWikiDocument myDoc = new XWikiDocument(testDocRef); expectXWikiDocLoad(sessionMock, myDoc); expectLoadEmptyAttachmentList(sessionMock); expectBaseObjectLoad(sessionMock); } private List<Future<LoadDocCheckResult>> testScenario1(XWikiCacheStoreInterface store, int cores, int maxLoadTasks) throws Exception { fastFail.set(false); preloadCache(store); final int numTimesFromCache = cores * 3; final int oneRunRepeats = 200; int count = (maxLoadTasks / (oneRunRepeats * numTimesFromCache)) + 1; ScheduledExecutorService theExecutor = Executors.newScheduledThreadPool(cores); List<Future<LoadDocCheckResult>> futureList = new ArrayList<>(count * (numTimesFromCache + 1) * oneRunRepeats); try { do { count List<Callable<LoadDocCheckResult>> loadTasks = new ArrayList<>(oneRunRepeats * numTimesFromCache); for (int i = 0; i < oneRunRepeats; i++) { if (i > 0) { loadTasks.add(new RefreshCacheEntryCommand(store)); loadTasks.add(new LoadXWikiDocCommand(store)); } for (int j = 1; j <= numTimesFromCache; j++) { loadTasks.add(new LoadXWikiDocCommand(store)); } } futureList.addAll(theExecutor.invokeAll(loadTasks)); final Future<LoadDocCheckResult> lastFuture = futureList.get(futureList.size() - oneRunRepeats); while (!lastFuture.isDone() && !fastFail.get()) { Thread.sleep(50); } } while (!fastFail.get() && (count > 0)); } finally { theExecutor.shutdown(); while (!theExecutor.isTerminated()) { if (fastFail.get()) { theExecutor.shutdownNow(); } theExecutor.awaitTermination(500, TimeUnit.MILLISECONDS); } } return futureList; } private void assertSuccessFullRuns(List<Future<LoadDocCheckResult>> futureList) throws InterruptedException, ExecutionException { int successfulRuns = 0; int failedRuns = 0; List<String> failMessgs = new ArrayList<>(); for (Future<LoadDocCheckResult> testFuture : futureList) { LoadDocCheckResult result = testFuture.get(); if (result.isSuccessfull()) { successfulRuns += 1; } else { failedRuns += 1; List<String> messages = result.getMessages(); failMessgs.add("Run num: " + (successfulRuns + failedRuns) + "\n"); failMessgs.addAll(messages); } } assertEquals("Found " + failedRuns + " failing runs: " + Arrays.deepToString( failMessgs.toArray()), futureList.size(), successfulRuns); } private void expectBaseObjectLoad(Session sessionMock) { String loadBaseObjectHql = "from BaseObject as bobject where bobject.name = :name order by " + "bobject.number"; Query queryObj = new TestQuery<>(loadBaseObjectHql, new QueryList<BaseObject>() { @Override public List<BaseObject> list(String string, Map<String, Object> params) throws HibernateException { DocumentReference theDocRef = webUtilsService.resolveDocumentReference((String) params.get( "name")); List<BaseObject> attList = new ArrayList<>(); for (BaseObject templBaseObject : baseObjMap.get(theDocRef)) { BaseObject bObj = createBaseObject(templBaseObject.getNumber(), templBaseObject.getXClassReference()); bObj.setDocumentReference(theDocRef); attList.add(bObj); } return attList; } }); expect(sessionMock.createQuery(eq(loadBaseObjectHql))).andReturn(queryObj).anyTimes(); expectPropertiesLoad(sessionMock); } private void expectPropertiesLoad(Session sessionMock) { String loadPropHql = "select prop.name, prop.classType from BaseProperty as prop where " + "prop.id.id = :id"; Query queryProp = new TestQuery<>(loadPropHql, new QueryList<String[]>() { @Override public List<String[]> list(String string, Map<String, Object> params) throws HibernateException { return propertiesMap.get(params.get("id")); } }); expect(sessionMock.createQuery(eq(loadPropHql))).andReturn(queryProp).atLeastOnce(); sessionMock.load(isA(PropertyInterface.class), isA(Serializable.class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { BaseProperty property = (BaseProperty) getCurrentArguments()[0]; Integer objId = property.getObject().getId(); for (BaseObject templBaseObject : baseObjMap.get(testDocRef)) { if (objId.equals(templBaseObject.getId())) { for (Object theObj : templBaseObject.getFieldList()) { BaseProperty theField = (BaseProperty) theObj; if (theField.getName().equals(property.getName()) && theField.getClass().equals( property.getClass())) { property.setValue(theField.getValue()); } } } } return this; } }).atLeastOnce(); } private void expectLoadEmptyAttachmentList(Session sessionMock) { String loadAttachmentHql = "from XWikiAttachment as attach where attach.docId=:docid"; Query query = new TestQuery<>(loadAttachmentHql, new QueryList<XWikiAttachment>() { @Override public List<XWikiAttachment> list(String string, Map<String, Object> params) throws HibernateException { List<XWikiAttachment> attList = new ArrayList<>(); return attList; } }); expect(sessionMock.createQuery(eq(loadAttachmentHql))).andReturn(query).anyTimes(); } private void expectXWikiDocLoad(Session sessionMock, XWikiDocument myDoc) { sessionMock.load(isA(XWikiDocument.class), eq(new Long(myDoc.getId()))); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { XWikiDocument theDoc = (XWikiDocument) getCurrentArguments()[0]; if (testDocRef.equals(theDoc.getDocumentReference())) { if (verifyDocLoads) { countDocLoads.incrementAndGet(); } theDoc.setContent("test Content"); theDoc.setTitle("the test Title"); theDoc.setAuthor("XWiki.testAuthor"); theDoc.setCreationDate(new java.sql.Date(new Date().getTime() - 5000L)); theDoc.setContentUpdateDate(new java.sql.Date(new Date().getTime() - 2000L)); theDoc.setLanguage(""); theDoc.setDefaultLanguage("en"); } return this; } }).anyTimes(); } private void createBaseObjects() { DocumentReference testDocRefClone = new DocumentReference(testDocRef.clone()); BaseObject bObj1 = createBaseObject(0, navClassConfig.getMenuNameClassRef(wikiName)); bObj1.setDocumentReference(testDocRefClone); addStringField(bObj1, INavigationClassConfig.MENU_NAME_LANG_FIELD, "de"); addStringField(bObj1, INavigationClassConfig.MENU_NAME_FIELD, "Hause"); BaseObject bObj2 = createBaseObject(1, navClassConfig.getMenuNameClassRef(wikiName)); bObj2.setDocumentReference(testDocRefClone); addStringField(bObj2, INavigationClassConfig.MENU_NAME_LANG_FIELD, "en"); addStringField(bObj2, INavigationClassConfig.MENU_NAME_FIELD, "Home"); BaseObject bObj3 = createBaseObject(0, navClassConfig.getMenuItemClassRef(wikiRef)); bObj3.setDocumentReference(testDocRefClone); addIntField(bObj3, INavigationClassConfig.MENU_POSITION_FIELD, 1); BaseObject bObj4 = createBaseObject(0, pageTypeClassConfig.getPageTypeClassRef(wikiRef)); bObj4.setDocumentReference(testDocRefClone); addStringField(bObj4, IPageTypeClassConfig.PAGE_TYPE_FIELD, "Performance"); List<BaseObject> attList = new Vector<>(Arrays.asList(bObj1, bObj2, bObj3, bObj4)); baseObjMap = ImmutableMap.of(testDocRefClone, attList); } private void createPropertiesMap() { Map<Integer, List<String[]>> propertiesMap = new HashMap<>(); for (BaseObject templBaseObject : baseObjMap.get(testDocRef)) { List<String[]> propList = new ArrayList<>(); for (Object theObj : templBaseObject.getFieldList()) { PropertyInterface theField = (PropertyInterface) theObj; String[] row = new String[2]; row[0] = theField.getName(); row[1] = theField.getClass().getCanonicalName(); propList.add(row); } if (propertiesMap.containsKey(templBaseObject.getId())) { throw new IllegalStateException(); } propertiesMap.put(templBaseObject.getId(), ImmutableList.copyOf(propList)); } this.propertiesMap = ImmutableMap.copyOf(propertiesMap); } private void initStorePrepareMultiThreadMocks() throws XWikiException { defaultContext = (XWikiContext) getContext().clone(); XWikiStoreInterface store = Utils.getComponent(XWikiStoreInterface.class); theCacheStore = new XWikiCacheStore(store, defaultContext); theCacheStoreFixed = (DocumentCacheStore) Utils.getComponent(XWikiStoreInterface.class, DocumentCacheStore.COMPONENT_NAME); theCacheStoreFixed.initalize(); // ensure cache is initialized theCacheStoreFixed.getStore(); // ensure store is initialized defaultMocks = Collections.unmodifiableCollection(getDefaultMocks()); } private class LoadDocCheckResult { private final List<String> messages = new Vector<>(); public void addMessage(String message) { messages.add(message); fastFail.set(true); } public boolean isSuccessfull() { return (messages.size() == 0); } public List<String> getMessages() { return messages; } } private abstract class AbstractXWikiTestFuture extends AbstractXWikiRunnable implements Callable<LoadDocCheckResult> { private boolean hasNewContext; private final LoadDocCheckResult result = new LoadDocCheckResult(); private final XWikiCacheStoreInterface store; protected AbstractXWikiTestFuture(XWikiCacheStoreInterface store) { this.store = store; } protected XWikiCacheStoreInterface getStore() { return this.store; } private ExecutionContext getExecutionContext() { return Utils.getComponent(Execution.class).getContext(); } protected LoadDocCheckResult getResult() { return result; } @Override public LoadDocCheckResult call() throws Exception { try { try { hasNewContext = (getExecutionContext() == null); if (hasNewContext) { initExecutionContext(); getExecutionContext().setProperty(EXECUTIONCONTEXT_KEY_MOCKS, defaultMocks); getExecutionContext().setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, defaultContext.clone()); } try { runInternal(); } finally { if (hasNewContext) { // cleanup execution context cleanupExecutionContext(); } } } catch (ExecutionContextException e) { LOGGER.error("Failed to initialize execution context", e); } } catch (Throwable exp) { // anything could happen in the test and we want to catch all failures getResult().addMessage("Exception: " + exp.getMessage() + "\n" + ExceptionUtils.getStackTrace(exp)); } return getResult(); } } private class RefreshCacheEntryCommand extends AbstractXWikiTestFuture { public RefreshCacheEntryCommand(XWikiCacheStoreInterface store) { super(store); } @Override public void runInternal() { if (!successfullRemoveFromCache()) { if (verifyDocLoads) { failedToRemoveFromCacheCount.incrementAndGet(); } } } boolean successfullRemoveFromCache() { if (getStore() instanceof DocumentCacheStore) { return newStore(); } else { return oldStore(); } } private boolean newStore() { final InvalidateState invalidState = theCacheStoreFixed.removeDocFromCache(new XWikiDocument( testDocRef), true); if (verifyDocLoads) { switch (invalidState) { case LOADING_CANCELED: invalidatedLoadingCount.incrementAndGet(); break; case REMOVED: expectedCountDocLoadsFixed.incrementAndGet(); break; case LOADING_MULTI_CANCELED: invalidatedMultipleCount.incrementAndGet(); break; default: failedToInvalidatedLoadingCount.incrementAndGet(); break; } } return (invalidState.equals(InvalidateState.LOADING_CANCELED) || invalidState.equals( InvalidateState.REMOVED)); } private boolean oldStore() { String key = theCacheStore.getKey(wikiName, testFullName, ""); XWikiDocument oldCachedDoc = null; if (theCacheStore.getCache() != null) { oldCachedDoc = theCacheStore.getCache().get(key); theCacheStore.getCache().remove(key); if (verifyDocLoads) { expectedCountDocLoads.incrementAndGet(); } } if (theCacheStore.getPageExistCache() != null) { theCacheStore.getPageExistCache().remove(key); } return oldCachedDoc != null; } } private class LoadXWikiDocCommand extends AbstractXWikiTestFuture { private XWikiDocument loadedXWikiDoc; public LoadXWikiDocCommand(XWikiCacheStoreInterface store) { super(store); } @Override protected void runInternal() { loadTestDocument(); testLoadedDocument(); } private void testLoadedDocument() { if (loadedXWikiDoc != null) { if (loadedXWikiDoc.isNew()) { getResult().addMessage("unexpected: isNew is true"); } if (!loadedXWikiDoc.isMostRecent()) { getResult().addMessage("unexpected: isMostRecent is false"); } for (BaseObject theTestObj : baseObjMap.get(testDocRef)) { Map<DocumentReference, List<BaseObject>> loadedObjs = loadedXWikiDoc.getXObjects(); final List<BaseObject> xclassObjs = loadedObjs.get(theTestObj.getXClassReference()); if (!xclassObjs.contains(theTestObj)) { getResult().addMessage("Object missing " + theTestObj); } else { BaseObject theLoadedObj = xclassObjs.get(xclassObjs.indexOf(theTestObj)); if (theLoadedObj == theTestObj) { getResult().addMessage("Object is same " + theTestObj); } else { for (String theFieldName : theTestObj.getPropertyNames()) { BaseProperty theField = (BaseProperty) theLoadedObj.getField(theFieldName); BaseProperty theTestField = (BaseProperty) theTestObj.getField(theFieldName); if (theField == theTestField) { getResult().addMessage("Field is same " + theField); } else if (!theTestField.getValue().equals(theField.getValue())) { getResult().addMessage("Field value missmatch expected: " + theField + "\n but found: " + theField.getValue()); } } } } } } else { getResult().addMessage("Loaded document reference is null."); } } private void loadTestDocument() { try { XWikiDocument myDoc = new XWikiDocument(testDocRef); try { loadedXWikiDoc = getStore().loadXWikiDoc(myDoc, getContext()); } catch (XWikiException exp) { throw new IllegalStateException(exp); } } catch (Exception exp) { throw new RuntimeException(exp); } } } private final void addIntField(BaseObject bObj, String fieldName, int value) { bObj.setIntValue(fieldName, value); } private final void addStringField(BaseObject bObj, String fieldName, String value) { bObj.setStringValue(fieldName, value); } private final BaseObject createBaseObject(int num, DocumentReference classRef) { BaseObject bObj = new BaseObject(); bObj.setXClassReference(new DocumentReference(classRef.clone())); bObj.setNumber(num); return bObj; } private interface QueryList<T> { public List<T> list(String string, Map<String, Object> params) throws HibernateException; } private class TestQuery<T> extends AbstractQueryImpl { private Query theQueryMock; private QueryList<T> listStub; private Map<String, Object> params; public TestQuery(String queryStr, QueryList<T> listStub) { super(queryStr, FlushMode.AUTO, null, null); this.listStub = listStub; this.params = new HashMap<>(); theQueryMock = createMock(Query.class); replay(theQueryMock); } @SuppressWarnings("rawtypes") @Override public Iterator iterate() throws HibernateException { return theQueryMock.iterate(); } @Override public ScrollableResults scroll() throws HibernateException { return theQueryMock.scroll(); } @Override public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException { return theQueryMock.scroll(scrollMode); } @SuppressWarnings("unchecked") @Override public List<T> list() throws HibernateException { if (listStub != null) { return listStub.list(getQueryString(), params); } return theQueryMock.list(); } @Override public Query setText(String named, String val) { this.params.put(named, val); return this; } @Override public Query setInteger(String named, int val) { this.params.put(named, new Integer(val)); return this; } @Override public Query setLong(String named, long val) { this.params.put(named, new Long(val)); return this; } @Override public int executeUpdate() throws HibernateException { return theQueryMock.executeUpdate(); } @Override public Query setLockMode(String alias, LockMode lockMode) { return theQueryMock.setLockMode(alias, lockMode); } @SuppressWarnings("rawtypes") @Override protected Map getLockModes() { throw new UnsupportedOperationException("getLockModes not supported"); } } private class TestXWiki extends XWiki { @Override public BaseClass getXClass(DocumentReference documentReference, XWikiContext context) throws XWikiException { // Used to avoid recursive loading of documents if there are recursive usage of classes BaseClass bclass = context.getBaseClass(documentReference); if (bclass == null) { bclass = new BaseClass(); bclass.setDocumentReference(documentReference); context.addBaseClass(bclass); } return bclass; } } }
package net.vectorgaming.vcore.framework.commands; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.command.CommandMap; import org.bukkit.craftbukkit.v1_6_R3.CraftServer; /** * * @author Kenny */ public class CommandManager { private static CommandMap commandMap; private static final ArrayList<VCommand> commands = new ArrayList<>(); static { try { final Field f = CraftServer.class.getDeclaredField("commandMap"); f.setAccessible(true); commandMap = (CommandMap) f.get(Bukkit.getServer()); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(CommandManager.class.getName()).log(Level.SEVERE, null, ex); } } /** * Dynamically registers a command into Bukkit. The command is not required to be added in the * plugin.yml * @param command Command to be registered */ public static void registerCommand(VCommand command) { commandMap.register(command.getName(), command); commands.add(command); } /** * Checks to see if the given command has been registered * @param command Name of the command to check * @return TRUE if the command does exist */ public static boolean commandExists(String command) { for(VCommand cmd : commands) { if(cmd.getName().equalsIgnoreCase(command)) return true; } return false; } /** * Returns a list of commands that have been registered with the plugin * @return A list of commands */ public static ArrayList<VCommand> getCommands() { return commands; } }
package org.intellij.ibatis.provider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.xml.XmlAttributeValue; import org.intellij.ibatis.IbatisManager; import org.intellij.ibatis.dom.sqlMap.CacheModel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.Set; /** * cache model reference provider * * @author linux_china@hotmail.com */ public class CacheModelReferenceProvider extends BaseReferenceProvider { @NotNull public PsiReference[] getReferencesByElement(PsiElement psiElement) { XmlAttributeValue xmlAttributeValue = (XmlAttributeValue) psiElement; XmlAttributeValuePsiReference psiReference = new XmlAttributeValuePsiReference(xmlAttributeValue) { public boolean isSoft() { return false; } @Nullable public PsiElement resolve() { String cacheModelId = getReferenceId(getElement()); IbatisManager manager = IbatisManager.getInstance(); Map<String, CacheModel> allResultMap = manager.getAllCacheModel(getElement()); CacheModel cacheModel = allResultMap.get(cacheModelId); return cacheModel == null ? null : cacheModel.getXmlTag(); } public Object[] getVariants() { Set<String> cacheModelList = IbatisManager.getInstance().getAllCacheModel(getElement()).keySet(); return cacheModelList.toArray(); } }; return new PsiReference[]{psiReference}; } }
package com.lambdaworks.redis; import static com.google.code.tempusfugit.temporal.Duration.seconds; import static com.google.code.tempusfugit.temporal.Timeout.timeout; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import com.google.code.tempusfugit.temporal.Condition; import com.google.code.tempusfugit.temporal.WaitFor; import com.lambdaworks.redis.models.command.CommandDetail; import com.lambdaworks.redis.models.command.CommandDetailParser; import com.lambdaworks.redis.models.role.RedisInstance; import com.lambdaworks.redis.models.role.RoleParser; import com.lambdaworks.redis.protocol.CommandType; public class ServerCommandTest extends AbstractCommandTest { @Test public void bgrewriteaof() throws Exception { String msg = "Background append only file rewriting"; assertThat(redis.bgrewriteaof(), containsString(msg)); } @Test public void bgsave() throws Exception { while (redis.info().contains("aof_rewrite_in_progress:1")) { Thread.sleep(100); } String msg = "Background saving started"; assertThat(redis.bgsave()).isEqualTo(msg); } @Test public void clientGetSetname() throws Exception { assertThat(redis.clientGetname()).isNull(); assertThat(redis.clientSetname("test")).isEqualTo("OK"); assertThat(redis.clientGetname()).isEqualTo("test"); assertThat(redis.clientSetname("")).isEqualTo("OK"); assertThat(redis.clientGetname()).isNull(); } @Test public void clientPause() throws Exception { assertThat(redis.clientPause(1000)).isEqualTo("OK"); } @Test public void clientKill() throws Exception { Pattern p = Pattern.compile(".*addr=([^ ]+).*"); String clients = redis.clientList(); Matcher m = p.matcher(clients); assertThat(m.lookingAt()).isTrue(); assertThat(redis.clientKill(m.group(1))).isEqualTo("OK"); } @Test public void clientKillExtended() throws Exception { RedisConnection<String, String> connection2 = client.connect(); connection2.clientSetname("killme"); Pattern p = Pattern.compile("^.*addr=([^ ]+).*name=killme.*$", Pattern.MULTILINE | Pattern.DOTALL); String clients = redis.clientList(); Matcher m = p.matcher(clients); assertThat(m.matches()).isTrue(); String addr = m.group(1); assertThat(redis.clientKill(KillArgs.Builder.addr(addr).skipme())).isGreaterThan(0); assertThat(redis.clientKill(KillArgs.Builder.id(4234))).isEqualTo(0); assertThat(redis.clientKill(KillArgs.Builder.typeSlave().id(4234))).isEqualTo(0); assertThat(redis.clientKill(KillArgs.Builder.typeNormal().id(4234))).isEqualTo(0); assertThat(redis.clientKill(KillArgs.Builder.typePubsub().id(4234))).isEqualTo(0); connection2.close(); } @Test public void clientList() throws Exception { assertThat(redis.clientList().contains("addr=")).isTrue(); } @Test public void commandCount() throws Exception { assertThat(redis.commandCount()).isGreaterThan(100); } @Test public void command() throws Exception { List<Object> result = redis.command(); assertThat(result.size()).isGreaterThan(100); List<CommandDetail> commands = CommandDetailParser.parse(result); assertThat(commands).hasSameSizeAs(result); } @Test public void commandInfo() throws Exception { List<Object> result = redis.commandInfo(CommandType.GETRANGE, CommandType.SET); assertThat(result.size()).isEqualTo(2); List<CommandDetail> commands = CommandDetailParser.parse(result); assertThat(commands).hasSameSizeAs(result); result = redis.commandInfo("a missing command"); assertThat(result.size()).isEqualTo(0); } @Test public void configGet() throws Exception { assertThat(redis.configGet("maxmemory")).isEqualTo(list("maxmemory", "0")); } @Test public void configResetstat() throws Exception { redis.get(key); redis.get(key); assertThat(redis.configResetstat()).isEqualTo("OK"); assertThat(redis.info().contains("keyspace_misses:0")).isTrue(); } @Test public void configSet() throws Exception { String maxmemory = redis.configGet("maxmemory").get(1); assertThat(redis.configSet("maxmemory", "1024")).isEqualTo("OK"); assertThat(redis.configGet("maxmemory").get(1)).isEqualTo("1024"); redis.configSet("maxmemory", maxmemory); } @Test public void configRewrite() throws Exception { String result = redis.configRewrite(); assertThat(result).isEqualTo("OK"); } @Test public void dbsize() throws Exception { assertThat(redis.dbsize()).isEqualTo(0); redis.set(key, value); assertThat(redis.dbsize()).isEqualTo(1); } @Test public void debugObject() throws Exception { redis.set(key, value); redis.debugObject(key); } /** * this test causes a stop of the redis. This means, you cannot repeat the test without restarting your redis. * * @throws Exception */ @Test public void debugSegfault() throws Exception { final RedisAsyncConnection<String, String> connection = client.connectAsync(RedisURI.Builder.redis("localhost", 6482) .build()); connection.debugSegfault(); WaitFor.waitOrTimeout(new Condition() { @Override public boolean isSatisfied() { return !connection.isOpen(); } }, timeout(seconds(5))); assertThat(connection.isOpen()).isFalse(); } @Test public void flushall() throws Exception { redis.set(key, value); assertThat(redis.flushall()).isEqualTo("OK"); assertThat(redis.get(key)).isNull(); } @Test public void flushdb() throws Exception { redis.set(key, value); redis.select(1); redis.set(key, value + "X"); assertThat(redis.flushdb()).isEqualTo("OK"); assertThat(redis.get(key)).isNull(); redis.select(0); assertThat(redis.get(key)).isEqualTo(value); } @Test public void info() throws Exception { assertThat(redis.info().contains("redis_version")).isTrue(); assertThat(redis.info("server").contains("redis_version")).isTrue(); } @Test public void lastsave() throws Exception { Date start = new Date(System.currentTimeMillis() / 1000); assertThat(start.compareTo(redis.lastsave()) <= 0).isTrue(); } @Test public void save() throws Exception { while (redis.info().contains("aof_rewrite_in_progress:1")) { Thread.sleep(100); } assertThat(redis.save()).isEqualTo("OK"); } @Test public void slaveof() throws Exception { assertThat(redis.slaveof("localhost", 0)).isEqualTo("OK"); redis.slaveofNoOne(); } @Test public void role() throws Exception { RedisClient redisClient = new RedisClient("localhost", 6480); RedisAsyncConnection<String, String> connection = redisClient.connectAsync(); try { RedisFuture<List<Object>> role = connection.role(); List<Object> objects = role.get(); assertThat(objects.get(0)).isEqualTo("master"); assertThat(objects.get(1).getClass()).isEqualTo(Long.class); RedisInstance redisInstance = RoleParser.parse(objects); assertThat(redisInstance.getRole()).isEqualTo(RedisInstance.Role.MASTER); } finally { connection.close(); redisClient.shutdown(0, 0, TimeUnit.MILLISECONDS); } } /** * this test causes a stop of the redis. This means, you cannot repeat the test without restarting your redis. * * @throws Exception */ @Test public void shutdown() throws Exception { final RedisAsyncConnection<String, String> connection = client.connectAsync(RedisURI.Builder.redis("localhost", 6483) .build()); try { connection.shutdown(true); connection.shutdown(false); WaitFor.waitOrTimeout(new Condition() { @Override public boolean isSatisfied() { return !connection.isOpen(); } }, timeout(seconds(5))); assertThat(connection.isOpen()).isFalse(); } finally { connection.close(); } } @Test public void slaveofNoOne() throws Exception { assertThat(redis.slaveofNoOne()).isEqualTo("OK"); } @Test @SuppressWarnings("unchecked") public void slowlog() throws Exception { long start = System.currentTimeMillis() / 1000; assertThat(redis.configSet("slowlog-log-slower-than", "1")).isEqualTo("OK"); assertThat(redis.slowlogReset()).isEqualTo("OK"); redis.set(key, value); List<Object> log = redis.slowlogGet(); assertThat(log).hasSize(2); List<Object> entry = (List<Object>) log.get(0); assertThat(entry).hasSize(4); assertThat(entry.get(0) instanceof Long).isTrue(); assertThat((Long) entry.get(1) >= start).isTrue(); assertThat(entry.get(2) instanceof Long).isTrue(); assertThat(entry.get(3)).isEqualTo(list("SET", key, value)); entry = (List<Object>) log.get(1); assertThat(entry).hasSize(4); assertThat(entry.get(0) instanceof Long).isTrue(); assertThat((Long) entry.get(1) >= start).isTrue(); assertThat(entry.get(2) instanceof Long).isTrue(); assertThat(entry.get(3)).isEqualTo(list("SLOWLOG", "RESET")); assertThat(redis.slowlogGet(1)).hasSize(1); assertThat((long) redis.slowlogLen()).isEqualTo(4); redis.configSet("slowlog-log-slower-than", "0"); } @Test public void sync() throws Exception { assertThat(redis.sync().startsWith("REDIS")).isTrue(); } @Test public void migrate() throws Exception { redis.set(key, value); String result = redis.migrate("localhost", port + 1, key, 0, 10); assertThat(result).isEqualTo("OK"); } }
package imagej.platform; import imagej.ext.plugin.PluginModuleInfo; import imagej.service.IService; import java.util.List; /** * Interface for service that provides application-level functionality. * * @author Curtis Rueden */ public interface AppService extends IService { /** Displays an About ImageJ dialog. */ void about(); /** Displays ImageJ preferences. */ void showPrefs(); /** Quits ImageJ. */ void quit(); /** Gets the list of plugins handled by this service. */ List<PluginModuleInfo<?>> getHandledPlugins(); }
package com.noradltd.medusa.scrum; import static com.noradltd.medusa.scrum.CardBuilder.createCardsLike; import static com.noradltd.medusa.scrum.TeamBuilder.createTeamOf; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.noradltd.medusa.scrum.Card.Size; public abstract class SprintBuilder { private SprintBuilder() { } public static final Sprint emptySprint() { return new Sprint(); } public static final Sprint defaultSprint() { Sprint sprint = overcommittedSprint(); sprint.days = 10; return sprint; } public static final Sprint undercommittedSprint() { Sprint sprint = emptySprint(); sprint.days = 5; sprint.addCards(createCardsLike(Size.SMALL, 5)); sprint.team = createTeamOf(5); return sprint; } public static final Sprint overcommittedSprint() { Sprint sprint = emptySprint(); sprint.days = 5; sprint.addCards(createCardsLike(Size.SMALL, 5)); sprint.addCards(createCardsLike(Size.MEDIUM, 5)); sprint.addCards(createCardsLike(Size.LARGE, 5)); sprint.team = createTeamOf(5); return sprint; } public static final Sprint addDefectsTo(Sprint sprint, Integer defectCount) { if (!sprint.cards.isEmpty()) { Card[] array = sprint.cards.toArray(new Card[] {}); List<Card> list = Arrays.asList(array); Collections.shuffle(list); Iterator<Card> cardItr = list.iterator(); Card currentCard = cardItr.next(); for (int ct = 0; ct < defectCount; ct++) { currentCard.shouldCreateDefect = true; currentCard.defectImpactRelativeToOriginalSize = 1.0f; currentCard = cardItr.next(); } } return sprint; } }
package org.leyfer.thesis.TouchLogger.service; import android.app.IntentService; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.leyfer.thesis.TouchLogger.MainActivity; import org.leyfer.thesis.TouchLogger.TouchSaver; import org.leyfer.thesis.TouchLogger.helper.DeviceTouchConfig; import org.leyfer.thesis.TouchLogger.helper.MotionEventConstructor; import org.leyfer.thesis.TouchLogger.config.TouchConfig; import org.leyfer.thesis.TouchLogger.notification.WatchNotification; import org.leyfer.thesis.TouchLogger.notification.helper.NotificationAction; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; public class TouchReaderService extends IntentService { public static final String ACTION_START = "org.leyfer.thesis.ACTION_START"; public static final String ACTION_PAUSE = "org.leyfer.thesis.ACTION_PAUSE"; public static final String ACTION_RESUME = "org.leyfer.thesis.ACTION_RESUME"; public static final String ACTION_STOP = "org.leyfer.thesis.ACTION_STOP"; private final int BUFFER_LENGTH = 32; private WatchNotification mNotification; private boolean mActive = true; private NotificationManager mNotificationManager; private boolean isRunning = true; private JSONObject mGesture; private JSONArray mEvents; private long mStartGestureTime; public TouchReaderService() { super("TouchReaderService"); } @Override public void onCreate() { super.onCreate(); mNotification = new WatchNotification(getApplicationContext()); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mGesture = new JSONObject(); mEvents = new JSONArray(); } @Override protected void onHandleIntent(Intent intent) { readAndParseTouches(getApplicationContext()); } private void killGetevent() { try { Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); String command="pkill getevent"; os.writeBytes(command + "\n"); os.close(); } catch (IOException e) { Log.e("TouchLogger", e.getMessage()); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); String action = intent.getAction(); if (ACTION_PAUSE.equals(action)) { mActive = false; startForeground(WatchNotification.NOTIFICATION_ID, mNotification.getNotification(NotificationAction.ACTION_PAUSED)); } else if (ACTION_RESUME.equals(action)) { mActive = true; startForeground(WatchNotification.NOTIFICATION_ID, mNotification.getNotification(NotificationAction.ACTION_INPROGRESS)); } else if (ACTION_START.equals(action)) { mActive = true; startForeground(WatchNotification.NOTIFICATION_ID, mNotification.getNotification(NotificationAction.ACTION_INPROGRESS)); sendBroadcast( new Intent(MainActivity.ACTION_SERVICE_STATE) .putExtra(MainActivity.SERVICE_ISRUNNING_EXTRA, true) ); } else if (ACTION_STOP.equals(action)) { mActive = false; isRunning = false; killGetevent(); mNotificationManager.cancel(WatchNotification.NOTIFICATION_ID); sendBroadcast( new Intent(MainActivity.ACTION_SERVICE_STATE) .putExtra(MainActivity.SERVICE_ISRUNNING_EXTRA, false) ); } return START_NOT_STICKY; } private void readAndParseTouches(Context context) { MotionEventConstructor eventConstructor; TouchConfig config = DeviceTouchConfig.configMap.get( String.format("%s,%s", Build.BOARD, Build.MODEL).toUpperCase()); if (config == null) { throw new RuntimeException("bad device"); } eventConstructor = new MotionEventConstructor(config); try { Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); String command=String.format("getevent -t %s", config.INPUT_DEVICE_PATH); os.writeBytes(command + "\n"); os.close(); InputStream is = new BufferedInputStream(process.getInputStream()); StringBuilder result = new StringBuilder(); byte[] buffer = new byte[BUFFER_LENGTH]; while(isRunning && !Thread.currentThread().isInterrupted()) { int availableBytes = is.available(); if (availableBytes > 0) { int readed = is.read(buffer); if (readed > 0) { result.append(new String(buffer, 0, readed)); } } else { try { Thread.sleep(500); } catch (InterruptedException e) { isRunning = false; } } String logData = result.toString(); String[] strings = logData.split("\n"); boolean isStringcompleted = logData.endsWith("\n"); result = new StringBuilder(); if (!isStringcompleted) { result.append(strings[strings.length - 1]); } int i; int length; if (isStringcompleted) { length = strings.length; } else { length = strings.length - 1; } for (i = 0; i < length; i++) { parseRawTouchEvent(context, eventConstructor, strings[i]); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { Log.e("TouchLogger", e.getMessage()); } } private void parseRawTouchEvent(Context context, MotionEventConstructor constructor, String rawTouchEvent) throws JSONException { constructor.update(rawTouchEvent); if (constructor.isMotionEventReady()) { JSONObject event = constructor.getMotionEvent(); mEvents.put(event); String prefix = event.getString("prefix"); if (prefix.equals("DOWN")) { mStartGestureTime = event.getLong("timestamp"); } else if (prefix.equals("UP")) { mGesture.put("timestamp", System.currentTimeMillis()); mGesture.put("length", event.getLong("timestamp") - mStartGestureTime); mGesture.put("events", mEvents); if (mActive) { TouchSaver.getInstance(context).saveGesture(mGesture); } mEvents = new JSONArray(); mGesture = new JSONObject(); } } } }