answer
stringlengths
17
10.2M
package com.thaiopensource.relaxng; import java.util.Enumeration; import java.util.Hashtable; import java.io.IOException; import org.xml.sax.ContentHandler; import org.xml.sax.XMLReader; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.Locator; import org.xml.sax.InputSource; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.EntityResolver; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.LocatorImpl; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.ValidationContext; import org.relaxng.datatype.DatatypeLibraryFactory; import org.relaxng.datatype.DatatypeLibrary; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import com.thaiopensource.util.Uri; public class PatternReader implements ValidationContext { static final String relaxngURI = "http://relaxng.org/ns/structure/0.9"; static final String xmlURI = "http: static final String xsdURI = "http: XMLReader xr; XMLReaderCreator xrc; PatternBuilder patternBuilder; DatatypeLibraryFactory datatypeLibraryFactory; Pattern startPattern; Locator locator; PrefixMapping prefixMapping; XmlBaseHandler xmlBaseHandler = new XmlBaseHandler(); boolean hadError = false; Hashtable patternTable; Hashtable nameClassTable; final OpenIncludes openIncludes; Datatype ncNameDatatype; static class PrefixMapping { final String prefix; final String uri; final PrefixMapping next; PrefixMapping(String prefix, String uri, PrefixMapping next) { this.prefix = prefix; this.uri = uri; this.next = next; } } static class OpenIncludes { final String systemId; final OpenIncludes parent; OpenIncludes(String systemId, OpenIncludes parent) { this.systemId = systemId; this.parent = parent; } } abstract class State implements ContentHandler { State parent; String nsInherit; String ns; String datatypeLibrary; Grammar grammar; void set() { xr.setContentHandler(this); } abstract State create(); abstract State createChildState(String localName) throws SAXException; public void setDocumentLocator(Locator loc) { locator = loc; xmlBaseHandler.setLocator(loc); } void setParent(State parent) { this.parent = parent; if (parent.ns != null) this.nsInherit = parent.ns; else this.nsInherit = parent.nsInherit; this.datatypeLibrary = parent.datatypeLibrary; this.grammar = parent.grammar; } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { xmlBaseHandler.startElement(); if (isPatternNamespaceURI(namespaceURI)) { State state = createChildState(localName); if (state == null) { xr.setContentHandler(new Skipper(this)); return; } state.setParent(this); state.set(); state.attributes(atts); } else { if (!allowForeignElements()) error("foreign_element_char_content"); xr.setContentHandler(new Skipper(this)); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { xmlBaseHandler.endElement(); parent.set(); end(); } void setName(String name) throws SAXException { error("illegal_name_attribute"); } void setOtherAttribute(String name, String value) throws SAXException { error("illegal_attribute_ignored", name); } void endAttributes() throws SAXException { } boolean allowForeignElements() { return true; } void attributes(Attributes atts) throws SAXException { int len = atts.getLength(); for (int i = 0; i < len; i++) { String uri = atts.getURI(i); if (uri.length() == 0) { String name = atts.getLocalName(i); if (name.equals("name")) setName(atts.getValue(i).trim()); else if (name.equals("ns")) { ns = atts.getValue(i); checkUri(ns); if (!ns.equals("") && !Uri.isAbsolute(ns)) error("relative_ns"); } else if (name.equals("datatypeLibrary")) { datatypeLibrary = atts.getValue(i); checkUri(datatypeLibrary); if (!datatypeLibrary.equals("") && !Uri.isAbsolute(datatypeLibrary)) error("relative_datatype_library"); if (Uri.hasFragmentId(datatypeLibrary)) error("fragment_identifier_datatype_library"); } else setOtherAttribute(name, atts.getValue(i)); } else if (uri.equals(relaxngURI)) error("qualified_attribute", atts.getLocalName(i)); else if (uri.equals(xmlURI) && atts.getLocalName(i).equals("base")) xmlBaseHandler.xmlBaseAttribute(atts.getValue(i)); } endAttributes(); } abstract void end() throws SAXException; void endChild(Pattern pattern) { // XXX cannot happen; throw exception } void endChild(NameClass nc) { // XXX cannot happen; throw exception } public void startDocument() { } public void endDocument() throws SAXException { } public void processingInstruction(String target, String date) { } public void skippedEntity(String name) { } public void ignorableWhitespace(char[] ch, int start, int len) { } public void characters(char[] ch, int start, int len) throws SAXException { for (int i = 0; i < len; i++) { switch(ch[start + i]) { case ' ': case '\r': case '\n': case '\t': break; default: error("illegal_characters_ignored"); break; } } } public void startPrefixMapping(String prefix, String uri) { prefixMapping = new PrefixMapping(prefix, uri, prefixMapping); } public void endPrefixMapping(String prefix) { prefixMapping = prefixMapping.next; } } class Skipper extends DefaultHandler { int level = 1; State nextState; Skipper(State nextState) { this.nextState = nextState; } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { ++level; } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (--level == 0) nextState.set(); } } abstract class EmptyContentState extends State { State createChildState(String localName) throws SAXException { error("expected_empty", localName); return null; } abstract Pattern makePattern() throws SAXException; void end() throws SAXException { parent.endChild(makePattern()); } } abstract class PatternContainerState extends State { Pattern containedPattern; State createChildState(String localName) throws SAXException { State state = (State)patternTable.get(localName); if (state == null) { error("expected_pattern", localName); return null; } return state.create(); } Pattern combinePattern(Pattern p1, Pattern p2) { return patternBuilder.makeSequence(p1, p2); } Pattern wrapPattern(Pattern p) throws SAXException { return p; } void endChild(Pattern pattern) { if (containedPattern == null) containedPattern = pattern; else containedPattern = combinePattern(containedPattern, pattern); } void end() throws SAXException { if (containedPattern == null) { error("missing_children"); containedPattern = patternBuilder.makeError(); } sendPatternToParent(wrapPattern(containedPattern)); } void sendPatternToParent(Pattern p) { parent.endChild(p); } } class GroupState extends PatternContainerState { State create() { return new GroupState(); } } class ZeroOrMoreState extends PatternContainerState { State create() { return new ZeroOrMoreState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeZeroOrMore(p); } } class OneOrMoreState extends PatternContainerState { State create() { return new OneOrMoreState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeOneOrMore(p); } } class OptionalState extends PatternContainerState { State create() { return new OptionalState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeOptional(p); } } class ListState extends PatternContainerState { State create() { return new ListState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeList(p, copyLocator()); } } class ChoiceState extends PatternContainerState { State create() { return new ChoiceState(); } Pattern combinePattern(Pattern p1, Pattern p2) { return patternBuilder.makeChoice(p1, p2); } } class InterleaveState extends PatternContainerState { State create() { return new InterleaveState(); } Pattern combinePattern(Pattern p1, Pattern p2) { return patternBuilder.makeInterleave(p1, p2); } } class MixedState extends PatternContainerState { State create() { return new MixedState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeInterleave(patternBuilder.makeText(), p); } } static interface NameClassRef { void setNameClass(NameClass nc); } class ElementState extends PatternContainerState implements NameClassRef { NameClass nameClass; String name; void setName(String name) { this.name = name; } public void setNameClass(NameClass nc) { nameClass = nc; } void endAttributes() throws SAXException { if (name != null) nameClass = expandName(name, ns != null ? ns : nsInherit); else new NameClassChildState(this, this).set(); } State create() { return new ElementState(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeElement(nameClass, p, copyLocator()); } } class RootState extends PatternContainerState { RootState() { } RootState(Grammar grammar, String ns) { this.grammar = grammar; this.nsInherit = ns; this.datatypeLibrary = ""; } State create() { return new RootState(); } State createChildState(String localName) throws SAXException { if (grammar == null) return super.createChildState(localName); if (localName.equals("grammar")) return new MergeGrammarState(); error("expected_grammar", localName); return null; } public void endDocument() throws SAXException { if (!hadError) startPattern = containedPattern; } } class NotAllowedState extends EmptyContentState { State create() { return new NotAllowedState(); } Pattern makePattern() { return patternBuilder.makeNotAllowed(); } } class EmptyState extends EmptyContentState { State create() { return new EmptyState(); } Pattern makePattern() { return patternBuilder.makeEmptySequence(); } } class TextState extends EmptyContentState { State create() { return new TextState(); } Pattern makePattern() { return patternBuilder.makeText(); } } class ValueState extends EmptyContentState { StringBuffer buf = new StringBuffer(); String type; State create() { return new ValueState(); } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("type")) type = checkNCName(value.trim()); else super.setOtherAttribute(name, value); } public void characters(char[] ch, int start, int len) { buf.append(ch, start, len); } boolean allowForeignElements() { return false; } Pattern makePattern() throws SAXException { DatatypeBuilder dtb; if (type == null) dtb = getDatatypeBuilder("", "token"); else dtb = getDatatypeBuilder(datatypeLibrary, type); try { Datatype dt = dtb.createDatatype(); Object value = dt.createValue(buf.toString(), PatternReader.this); if (value != null) return patternBuilder.makeValue(dt, value); error("invalid_value", buf.toString()); return patternBuilder.makeData(dt); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("datatype_requires_param_detail", detail); else error("datatype_requires_param"); return patternBuilder.makeError(); } } } class DataState extends State { String type; DatatypeBuilder dtb; Pattern except = null; Locator loc = copyLocator(); State create() { return new DataState(); } State createChildState(String localName) throws SAXException { if (localName.equals("param")) { if (except != null) error("param_after_except"); return new ParamState(dtb); } if (localName.equals("except")) { if (except != null) error("multiple_except"); return new ChoiceState(); } error("expected_param_except", localName); return null; } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("type")) type = checkNCName(value.trim()); else super.setOtherAttribute(name, value); } void endAttributes() throws SAXException { if (type == null) { error("missing_type_attribute"); dtb = getDatatypeBuilder("", "string"); } else dtb = getDatatypeBuilder(datatypeLibrary, type); } void end() throws SAXException { Pattern p; try { Datatype dt = dtb.createDatatype(); if (except != null) p = patternBuilder.makeDataExcept(dt, except, loc); else p = patternBuilder.makeData(dt); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("invalid_params_detail", detail); else error("invalid_params"); p = patternBuilder.makeError(); } parent.endChild(p); } void endChild(Pattern pattern) { if (except == null) except = pattern; else except = patternBuilder.makeChoice(except, pattern); } } class ParamState extends State { private StringBuffer buf = new StringBuffer(); private DatatypeBuilder dtb; private String name; ParamState(DatatypeBuilder dtb) { this.dtb = dtb; } State create() { return new ParamState(null); } void setName(String name) throws SAXException { this.name = checkNCName(name); } void endAttributes() throws SAXException { if (name == null) error("missing_name_attribute"); } State createChildState(String localName) throws SAXException { error("expected_empty", localName); return null; } public void characters(char[] ch, int start, int len) { buf.append(ch, start, len); } boolean allowForeignElements() { return false; } void end() throws SAXException { if (name == null) return; try { dtb.addParameter(name, buf.toString(), PatternReader.this); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("invalid_param_detail", detail); else error("invalid_param"); } } } class AttributeState extends PatternContainerState implements NameClassRef { NameClass nameClass; String name; boolean global = false; State create() { return new AttributeState(); } void setName(String name) { this.name = name; } public void setNameClass(NameClass nc) { nameClass = nc; } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("global")) { value = value.trim(); if (value.equals("true")) global = true; else if (!value.equals("false")) error("global_attribute_bad_value", value); } else super.setOtherAttribute(name, value); } void endAttributes() throws SAXException { if (name != null) { String nsUse; if (ns != null) nsUse = ns; else if (global) nsUse = nsInherit; else nsUse = ""; nameClass = expandName(name, nsUse); } else new NameClassChildState(this, this).set(); } void end() throws SAXException { if (containedPattern == null) containedPattern = patternBuilder.makeText(); super.end(); } Pattern wrapPattern(Pattern p) { return patternBuilder.makeAttribute(nameClass, p, copyLocator()); } State createChildState(String localName) throws SAXException { State tem = super.createChildState(localName); if (tem != null && containedPattern != null) error("attribute_multi_pattern"); return tem; } } abstract class SinglePatternContainerState extends PatternContainerState { State createChildState(String localName) throws SAXException { if (containedPattern == null) return super.createChildState(localName); error("too_many_children"); return null; } } class DivState extends State { IncludeState include; DivState(IncludeState include) { this.include = include; } State create() { return new DivState(null); } State createChildState(String localName) throws SAXException { if (localName.equals("define")) return new DefineState(include); if (localName.equals("start")) return new StartState(include); if (include == null && localName.equals("include")) return new IncludeState(); if (localName.equals("div")) return new DivState(include); error("expected_define", localName); // XXX better errors return null; } void end() throws SAXException { } } static class Item { Item(PatternRefPattern prp, Item next) { this.prp = prp; this.next = next; } PatternRefPattern prp; Item next; byte replacementStatus; } class IncludeState extends DivState { String href; private Item items; IncludeState() { super(null); include = this; } void add(PatternRefPattern prp) { items = new Item(prp, items); } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("href")) { href = value; checkUri(href); } else super.setOtherAttribute(name, value); } void endAttributes() throws SAXException { if (href == null) error("missing_href_attribute"); } void end() throws SAXException { if (href == null) return; Item i; for (i = items; i != null; i = i.next) { i.replacementStatus = i.prp.getReplacementStatus(); i.prp.setReplacementStatus(PatternRefPattern.REPLACEMENT_REQUIRE); } try { InputSource in = makeInputSource(href); String systemId = in.getSystemId(); for (OpenIncludes inc = openIncludes; inc != null; inc = inc.parent) if (inc.systemId.equals(systemId)) { error("recursive_include", systemId); return; } if (readPattern(PatternReader.this, in, grammar, ns == null ? nsInherit : ns) == null) hadError = true; } catch (IOException e) { throw new SAXException(e); } for (i = items; i != null; i = i.next) { if (i.prp.getReplacementStatus() == PatternRefPattern.REPLACEMENT_REQUIRE) { if (i.prp.getName() == null) error("missing_start_replacement"); else error("missing_define_replacement", i.prp.getName()); } i.prp.setReplacementStatus(i.replacementStatus); } } } class MergeGrammarState extends DivState { MergeGrammarState() { super(null); } void end() throws SAXException { // need a non-null pattern to avoid error parent.endChild(patternBuilder.makeEmptySequence()); } } class GrammarState extends MergeGrammarState { void setParent(State parent) { super.setParent(parent); grammar = new Grammar(grammar); } State create() { return new GrammarState(); } void end() throws SAXException { for (Enumeration enum = grammar.patternNames(); enum.hasMoreElements();) { String name = (String)enum.nextElement(); PatternRefPattern tr = (PatternRefPattern)grammar.makePatternRef(name); if (tr.getPattern() == null) { error("reference_to_undefined", name, tr.getRefLocator()); tr.setPattern(patternBuilder.makeError()); } } Pattern start = grammar.startPatternRef().getPattern(); if (start == null) { error("missing_start_element"); start = patternBuilder.makeError(); } parent.endChild(start); } } class RefState extends EmptyContentState { String name; State create() { return new RefState(); } void endAttributes() throws SAXException { if (name == null) error("missing_name_attribute"); if (grammar == null) error("ref_outside_grammar"); } void setName(String name) throws SAXException { this.name = checkNCName(name); } Pattern makePattern() { return makePattern(grammar); } Pattern makePattern(Grammar g) { if (g != null && name != null) { PatternRefPattern p = g.makePatternRef(name); if (p.getRefLocator() == null && locator != null) p.setRefLocator(new LocatorImpl(locator)); return p; } return patternBuilder.makeError(); } } class ParentRefState extends RefState { State create() { return new ParentRefState(); } void endAttributes() throws SAXException { super.endAttributes(); if (grammar.getParent() == null) error("parent_ref_outside_grammar"); } Pattern makePattern() { return makePattern(grammar == null ? null : grammar.getParent()); } } class ExternalRefState extends EmptyContentState { String href; Pattern includedPattern; State create() { return new ExternalRefState(); } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("href")) { href = value; checkUri(href); } else super.setOtherAttribute(name, value); } void endAttributes() throws SAXException { if (href == null) error("missing_href_attribute"); else { try { InputSource in = makeInputSource(href); String systemId = in.getSystemId(); for (OpenIncludes inc = openIncludes; inc != null; inc = inc.parent) if (inc.systemId.equals(systemId)) { error("recursive_include", systemId); return; } includedPattern = readPattern(PatternReader.this, in, null, ns == null ? nsInherit : ns); } catch (IOException e) { throw new SAXException(e); } } } Pattern makePattern() { if (includedPattern == null) { hadError = true; return patternBuilder.makeError(); } return includedPattern; } } class DefineState extends PatternContainerState { String name; private IncludeState include; byte combine = PatternRefPattern.COMBINE_NONE; DefineState(IncludeState include) { this.include = include; } State create() { return new DefineState(null); } void setName(String name) throws SAXException { this.name = checkNCName(name); } void setOtherAttribute(String name, String value) throws SAXException { if (name.equals("combine")) { value = value.trim(); if (value.equals("choice")) combine = PatternRefPattern.COMBINE_CHOICE; else if (value.equals("interleave")) combine = PatternRefPattern.COMBINE_INTERLEAVE; else error("combine_attribute_bad_value", value); } else super.setOtherAttribute(name, value); } void endAttributes() throws SAXException { if (name == null) error("missing_name_attribute"); else checkCombine(grammar.makePatternRef(name)); } void checkCombine(PatternRefPattern prp) throws SAXException { if (prp.getReplacementStatus() != PatternRefPattern.REPLACEMENT_KEEP) return; switch (combine) { case PatternRefPattern.COMBINE_NONE: if (prp.isCombineImplicit()) { if (prp.getName() == null) error("duplicate_start"); else error("duplicate_define", prp.getName()); } else prp.setCombineImplicit(); break; case PatternRefPattern.COMBINE_CHOICE: case PatternRefPattern.COMBINE_INTERLEAVE: if (prp.getCombineType() != PatternRefPattern.COMBINE_NONE && prp.getCombineType() != combine) { if (prp.getName() == null) error("conflict_combine_start"); else error("conflict_combine_define", prp.getName()); } prp.setCombineType(combine); break; } } void setPattern(PatternRefPattern prp, Pattern p) { switch (prp.getReplacementStatus()) { case PatternRefPattern.REPLACEMENT_KEEP: if (include != null) include.add(prp); if (prp.getPattern() == null) prp.setPattern(p); else if (prp.getCombineType() == PatternRefPattern.COMBINE_INTERLEAVE) prp.setPattern(patternBuilder.makeInterleave(prp.getPattern(), p)); else prp.setPattern(patternBuilder.makeChoice(prp.getPattern(), p)); break; case PatternRefPattern.REPLACEMENT_REQUIRE: prp.setReplacementStatus(PatternRefPattern.REPLACEMENT_IGNORE); break; case PatternRefPattern.REPLACEMENT_IGNORE: break; } } void sendPatternToParent(Pattern p) { if (name != null) setPattern(grammar.makePatternRef(name), p); } } class StartState extends DefineState { StartState(IncludeState include) { super(include); } State create() { return new StartState(null); } void endAttributes() throws SAXException { if (name != null) checkCombine(grammar.makePatternRef(name)); checkCombine(grammar.startPatternRef()); } void setName(String name) throws SAXException { this.name = checkNCName(name); } void sendPatternToParent(Pattern p) { if (name != null) setPattern(grammar.makePatternRef(name), p); setPattern(grammar.startPatternRef(), p); } State createChildState(String localName) throws SAXException { State tem = super.createChildState(localName); if (tem != null && containedPattern != null) error("start_multi_pattern"); return tem; } } abstract class NameClassContainerState extends State { State createChildState(String localName) throws SAXException { State state = (State)nameClassTable.get(localName); if (state == null) { error("expected_name_class", localName); return null; } return state.create(); } } class NameClassChildState extends NameClassContainerState { State prevState; NameClassRef nameClassRef; State create() { return null; } NameClassChildState(State prevState, NameClassRef nameClassRef) { this.prevState = prevState; this.nameClassRef = nameClassRef; setParent(prevState.parent); } void endChild(NameClass nameClass) { nameClassRef.setNameClass(nameClass); prevState.set(); } void end() throws SAXException { nameClassRef.setNameClass(new ErrorNameClass()); error("missing_name_class"); prevState.set(); prevState.end(); } } abstract class NameClassBaseState extends State { abstract NameClass makeNameClass() throws SAXException; void end() throws SAXException { parent.endChild(makeNameClass()); } } class NameState extends NameClassBaseState { StringBuffer buf = new StringBuffer(); State createChildState(String localName) throws SAXException { error("expected_name", localName); return null; } State create() { return new NameState(); } public void characters(char[] ch, int start, int len) { buf.append(ch, start, len); } boolean allowForeignElements() { return false; } NameClass makeNameClass() throws SAXException { return expandName(buf.toString().trim(), ns != null ? ns : nsInherit); } } private static final int PATTERN_CONTEXT = 0; private static final int ANY_NAME_CONTEXT = 1; private static final int NS_NAME_CONTEXT = 2; class AnyNameState extends NameClassBaseState { NameClass except = null; State create() { return new AnyNameState(); } State createChildState(String localName) throws SAXException { if (localName.equals("except")) { if (except != null) error("multiple_except"); return new NameClassChoiceState(getContext()); } error("expected_except", localName); return null; } int getContext() { return ANY_NAME_CONTEXT; } NameClass makeNameClass() { if (except == null) return makeNameClassNoExcept(); else return makeNameClassExcept(except); } NameClass makeNameClassNoExcept() { return new AnyNameClass(); } NameClass makeNameClassExcept(NameClass except) { return new AnyNameExceptNameClass(except); } void endChild(NameClass nameClass) { if (except != null) except = new ChoiceNameClass(except, nameClass); else except = nameClass; } } class NsNameState extends AnyNameState { State create() { return new NsNameState(); } NameClass makeNameClassNoExcept() { return new NsNameClass(computeNs()); } NameClass makeNameClassExcept(NameClass except) { return new NsNameExceptNameClass(computeNs(), except); } private String computeNs() { return ns != null ? ns : nsInherit; } int getContext() { return NS_NAME_CONTEXT; } } class NameClassChoiceState extends NameClassContainerState { private NameClass nameClass; private int context; NameClassChoiceState() { this.context = PATTERN_CONTEXT; } NameClassChoiceState(int context) { this.context = context; } void setParent(State parent) { super.setParent(parent); if (parent instanceof NameClassChoiceState) this.context = ((NameClassChoiceState)parent).context; } State create() { return new NameClassChoiceState(); } State createChildState(String localName) throws SAXException { if (localName.equals("anyName")) { if (context >= ANY_NAME_CONTEXT) { error(context == ANY_NAME_CONTEXT ? "any_name_except_contains_any_name" : "ns_name_except_contains_any_name"); return null; } } else if (localName.equals("nsName")) { if (context == NS_NAME_CONTEXT) { error("ns_name_except_contains_ns_name"); return null; } } return super.createChildState(localName); } void endChild(NameClass nc) { if (nameClass == null) nameClass = nc; else nameClass = new ChoiceNameClass(nameClass, nc); } void end() throws SAXException { if (nameClass == null) { error("missing_name_class"); parent.endChild(new ErrorNameClass()); return; } parent.endChild(nameClass); } } private void initPatternTable() { patternTable = new Hashtable(); patternTable.put("zeroOrMore", new ZeroOrMoreState()); patternTable.put("oneOrMore", new OneOrMoreState()); patternTable.put("optional", new OptionalState()); patternTable.put("list", new ListState()); patternTable.put("choice", new ChoiceState()); patternTable.put("interleave", new InterleaveState()); patternTable.put("group", new GroupState()); patternTable.put("mixed", new MixedState()); patternTable.put("element", new ElementState()); patternTable.put("attribute", new AttributeState()); patternTable.put("empty", new EmptyState()); patternTable.put("text", new TextState()); patternTable.put("value", new ValueState()); patternTable.put("data", new DataState()); patternTable.put("notAllowed", new NotAllowedState()); patternTable.put("grammar", new GrammarState()); patternTable.put("ref", new RefState()); patternTable.put("parentRef", new ParentRefState()); patternTable.put("externalRef", new ExternalRefState()); } private void initNameClassTable() { nameClassTable = new Hashtable(); nameClassTable.put("name", new NameState()); nameClassTable.put("anyName", new AnyNameState()); nameClassTable.put("nsName", new NsNameState()); nameClassTable.put("choice", new NameClassChoiceState()); } Pattern getStartPattern() { return startPattern; } Pattern expandPattern(Pattern pattern) throws SAXException { if (pattern != null) { try { pattern.checkRecursion(0); } catch (SAXParseException e) { error(e); return null; } pattern = pattern.expand(patternBuilder); try { pattern.checkRestrictions(Pattern.START_CONTEXT, null); return pattern; } catch (RestrictionViolationException e) { error(e.getMessageId(), e.getLocator()); } } return null; } void error(String key) throws SAXException { error(key, locator); } void error(String key, String arg) throws SAXException { error(key, arg, locator); } void error(String key, String arg1, String arg2) throws SAXException { error(key, arg1, arg2, locator); } void error(String key, Locator loc) throws SAXException { error(new SAXParseException(Localizer.message(key), loc)); } void error(String key, String arg, Locator loc) throws SAXException { error(new SAXParseException(Localizer.message(key, arg), loc)); } void error(String key, String arg1, String arg2, Locator loc) throws SAXException { error(new SAXParseException(Localizer.message(key, arg1, arg2), loc)); } void error(SAXParseException e) throws SAXException { hadError = true; ErrorHandler eh = xr.getErrorHandler(); if (eh != null) eh.error(e); } void warning(String key) throws SAXException { warning(key, locator); } void warning(String key, Locator loc) throws SAXException { warning(new SAXParseException(Localizer.message(key), loc)); } void warning(SAXParseException e) throws SAXException { ErrorHandler eh = xr.getErrorHandler(); if (eh != null) eh.error(e); } public PatternReader(XMLReaderCreator xrc, XMLReader xr, PatternBuilder patternBuilder, DatatypeLibraryFactory factory) { this.xrc = xrc; this.patternBuilder = patternBuilder; this.xr = xr; this.datatypeLibraryFactory = new BuiltinDatatypeLibraryFactory(factory); this.ncNameDatatype = getNCNameDatatype(); openIncludes = null; init(null, ""); } PatternReader(PatternReader parent, String systemId, XMLReader xr, Grammar grammar, String ns) { this.xrc = parent.xrc; this.patternBuilder = parent.patternBuilder; this.datatypeLibraryFactory = parent.datatypeLibraryFactory; this.ncNameDatatype = parent.ncNameDatatype; this.xr = xr; this.openIncludes = new OpenIncludes(systemId, parent.openIncludes); init(grammar, ns); } private void init(Grammar grammar, String ns) { initPatternTable(); initNameClassTable(); prefixMapping = new PrefixMapping("xml", xmlURI, null); new RootState(grammar, ns).set(); } SimpleNameClass expandName(String name, String ns) throws SAXException { int ic = name.indexOf(':'); if (ic == -1) return new SimpleNameClass(ns, checkNCName(name)); String prefix = checkNCName(name.substring(0, ic)); String localName = checkNCName(name.substring(ic + 1)); for (PrefixMapping tem = prefixMapping; tem != null; tem = tem.next) if (tem.prefix.equals(prefix)) return new SimpleNameClass(tem.uri, localName); error("undefined_prefix", prefix); return new SimpleNameClass("", localName); } String checkNCName(String str) throws SAXException { if (!ncNameDatatype.isValid(str, null)) error("invalid_ncname", str); return str; } InputSource makeInputSource(String systemId) throws IOException, SAXException { systemId = Uri.resolve(xmlBaseHandler.getBaseUri(), systemId); EntityResolver er = xr.getEntityResolver(); if (er != null) { InputSource inputSource = er.resolveEntity(null, systemId); if (inputSource != null) return inputSource; } return new InputSource(systemId); } XMLReader createXMLReader() throws SAXException { XMLReader ixr = xrc.createXMLReader(); EntityResolver er = xr.getEntityResolver(); if (er != null) ixr.setEntityResolver(er); ErrorHandler eh = xr.getErrorHandler(); if (eh != null) ixr.setErrorHandler(eh); return ixr; } public static Pattern readPattern(XMLReaderCreator xrc, XMLReader xr, PatternBuilder patternBuilder, DatatypeLibraryFactory datatypeLibraryFactory, InputSource in) throws SAXException, IOException { PatternReader pr = new PatternReader(xrc, xr, patternBuilder, datatypeLibraryFactory); xr.parse(in); return pr.expandPattern(pr.getStartPattern()); } static Pattern readPattern(PatternReader parent, InputSource in, Grammar grammar, String ns) throws SAXException, IOException { XMLReader xr = parent.createXMLReader(); PatternReader pr = new PatternReader(parent, in.getSystemId(), xr, grammar, ns); xr.parse(in); return pr.getStartPattern(); } public String resolveNamespacePrefix(String prefix) { for (PrefixMapping p = prefixMapping; p != null; p = p.next) if (p.prefix.equals(prefix)) return p.uri; return null; } public String getBaseUri() { return xmlBaseHandler.getBaseUri(); } public boolean isUnparsedEntity(String name) { return false; } public boolean isNotation(String name) { return false; } boolean isPatternNamespaceURI(String s) { return s.equals(relaxngURI); } DatatypeBuilder getDatatypeBuilder(String datatypeLibrary, String type) throws SAXException { DatatypeLibrary dl = datatypeLibraryFactory.createDatatypeLibrary(datatypeLibrary); if (dl != null) { try { return dl.createDatatypeBuilder(type); } catch (DatatypeException e) { } } error("unrecognized_datatype", datatypeLibrary, type); try { return datatypeLibraryFactory.createDatatypeLibrary("") .createDatatypeBuilder("string"); } catch (DatatypeException e) { throw new RuntimeException("could not create builtin \"string\" datatype"); } } private Datatype getNCNameDatatype() { DatatypeLibrary dl = datatypeLibraryFactory.createDatatypeLibrary(xsdURI); if (dl != null) { try { return dl.createDatatypeBuilder("NCName").createDatatype(); } catch (DatatypeException e) { } } return new StringDatatype(); } Locator copyLocator() { if (locator == null) return null; return new LocatorImpl(locator); } void checkUri(String s) throws SAXException { if (!Uri.isValid(s)) error("invalid_uri", s); } }
package com.rwl.euclidian.algorithm; /** * * @author RainWhileLoop */ public class Euclidian { /** * Calculated the GCD of 2 numbers by using Euclidian Algorithm * * @param num1 must not be 0 * @param num2 must not be 0 * @return GCD - greatest common divisor */ public static int findGCD(int num1, int num2) { if (num1 == 0) { return num2; } if (num2 == 0) { return num1; } int dividend = Math.max(num1, num2); int divisor = Math.min(num1, num2); int fraction = dividend % divisor; if (fraction != 0) { return findGCD(divisor, fraction); } return divisor; } private static void showProcess(int max, int min) { System.out.println(max + " = " + min + "(" + max / min + ") + " + max % min); } }
package com.vaadin.data.util; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.Property; import com.vaadin.service.FileTypeResolver; import com.vaadin.terminal.Resource; /** * A hierarchical container wrapper for a filesystem. * * @author IT Mill Ltd. * @version * @VERSION@ * @since 3.0 */ @SuppressWarnings("serial") public class FilesystemContainer implements Container.Hierarchical { /** * String identifier of a file's "name" property. */ public static String PROPERTY_NAME = "Name"; /** * String identifier of a file's "size" property. */ public static String PROPERTY_SIZE = "Size"; /** * String identifier of a file's "icon" property. */ public static String PROPERTY_ICON = "Icon"; /** * String identifier of a file's "last modified" property. */ public static String PROPERTY_LASTMODIFIED = "Last Modified"; /** * List of the string identifiers for the available properties. */ public static Collection FILE_PROPERTIES; private final static Method FILEITEM_LASTMODIFIED; private final static Method FILEITEM_NAME; private final static Method FILEITEM_ICON; private final static Method FILEITEM_SIZE; static { FILE_PROPERTIES = new ArrayList(); FILE_PROPERTIES.add(PROPERTY_NAME); FILE_PROPERTIES.add(PROPERTY_ICON); FILE_PROPERTIES.add(PROPERTY_SIZE); FILE_PROPERTIES.add(PROPERTY_LASTMODIFIED); FILE_PROPERTIES = Collections.unmodifiableCollection(FILE_PROPERTIES); try { FILEITEM_LASTMODIFIED = FileItem.class.getMethod("lastModified", new Class[] {}); FILEITEM_NAME = FileItem.class.getMethod("getName", new Class[] {}); FILEITEM_ICON = FileItem.class.getMethod("getIcon", new Class[] {}); FILEITEM_SIZE = FileItem.class.getMethod("getSize", new Class[] {}); } catch (final NoSuchMethodException e) { throw new RuntimeException( "Internal error finding methods in FilesystemContainer"); } } private File[] roots = new File[] {}; private FilenameFilter filter = null; private boolean recursive = true; /** * Constructs a new <code>FileSystemContainer</code> with the specified file * as the root of the filesystem. The files are included recursively. * * @param root * the root file for the new file-system container. Null values * are ignored. */ public FilesystemContainer(File root) { if (root != null) { roots = new File[] { root }; } } /** * Constructs a new <code>FileSystemContainer</code> with the specified file * as the root of the filesystem. The files are included recursively. * * @param root * the root file for the new file-system container. * @param recursive * should the container recursively contain subdirectories. */ public FilesystemContainer(File root, boolean recursive) { this(root); setRecursive(recursive); } /** * Constructs a new <code>FileSystemContainer</code> with the specified file * as the root of the filesystem. * * @param root * the root file for the new file-system container. * @param extension * the Filename extension (w/o separator) to limit the files in * container. * @param recursive * should the container recursively contain subdirectories. */ public FilesystemContainer(File root, String extension, boolean recursive) { this(root); this.setFilter(extension); setRecursive(recursive); } /** * Constructs a new <code>FileSystemContainer</code> with the specified root * and recursivity status. * * @param root * the root file for the new file-system container. * @param filter * the Filename filter to limit the files in container. * @param recursive * should the container recursively contain subdirectories. */ public FilesystemContainer(File root, FilenameFilter filter, boolean recursive) { this(root); this.setFilter(filter); setRecursive(recursive); } /** * Adds new root file directory. Adds a file to be included as root file * directory in the <code>FilesystemContainer</code>. * * @param root * the File to be added as root directory. Null values are * ignored. */ public void addRoot(File root) { if (root != null) { final File[] newRoots = new File[roots.length + 1]; for (int i = 0; i < roots.length; i++) { newRoots[i] = roots[i]; } newRoots[roots.length] = root; roots = newRoots; } } /** * Tests if the specified Item in the container may have children. Since a * <code>FileSystemContainer</code> contains files and directories, this * method returns <code>true</code> for directory Items only. * * @param itemId * the id of the item. * @return <code>true</code> if the specified Item is a directory, * <code>false</code> otherwise. */ public boolean areChildrenAllowed(Object itemId) { return itemId instanceof File && ((File) itemId).canRead() && ((File) itemId).isDirectory(); } /* * Gets the ID's of all Items who are children of the specified Item. Don't * add a JavaDoc comment here, we use the default documentation from * implemented interface. */ public Collection getChildren(Object itemId) { if (!(itemId instanceof File)) { return Collections.unmodifiableCollection(new LinkedList()); } File[] f; if (filter != null) { f = ((File) itemId).listFiles(filter); } else { f = ((File) itemId).listFiles(); } if (f == null) { return Collections.unmodifiableCollection(new LinkedList()); } final List l = Arrays.asList(f); Collections.sort(l); return Collections.unmodifiableCollection(l); } /* * Gets the parent item of the specified Item. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Object getParent(Object itemId) { if (!(itemId instanceof File)) { return null; } return ((File) itemId).getParentFile(); } /* * Tests if the specified Item has any children. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public boolean hasChildren(Object itemId) { if (!(itemId instanceof File)) { return false; } String[] l; if (filter != null) { l = ((File) itemId).list(filter); } else { l = ((File) itemId).list(); } return (l != null) && (l.length > 0); } /* * Tests if the specified Item is the root of the filesystem. Don't add a * JavaDoc comment here, we use the default documentation from implemented * interface. */ public boolean isRoot(Object itemId) { if (!(itemId instanceof File)) { return false; } for (int i = 0; i < roots.length; i++) { if (roots[i].equals(itemId)) { return true; } } return false; } /* * Gets the ID's of all root Items in the container. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ public Collection rootItemIds() { File[] f; // in single root case we use children if (roots.length == 1) { if (filter != null) { f = roots[0].listFiles(filter); } else { f = roots[0].listFiles(); } } else { f = roots; } if (f == null) { return Collections.unmodifiableCollection(new LinkedList()); } final List l = Arrays.asList(f); Collections.sort(l); return Collections.unmodifiableCollection(l); } /** * Returns <code>false</code> when conversion from files to directories is * not supported. * * @param itemId * the ID of the item. * @param areChildrenAllowed * the boolean value specifying if the Item can have children or * not. * @return <code>true</code> if the operaton is successful otherwise * <code>false</code>. * @throws UnsupportedOperationException * if the setChildrenAllowed is not supported. */ public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Conversion file to/from directory is not supported"); } /** * Returns <code>false</code> when moving files around in the filesystem is * not supported. * * @param itemId * the ID of the item. * @param newParentId * the ID of the Item that's to be the new parent of the Item * identified with itemId. * @return <code>true</code> if the operation is successful otherwise * <code>false</code>. * @throws UnsupportedOperationException * if the setParent is not supported. */ public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException { throw new UnsupportedOperationException("File moving is not supported"); } /* * Tests if the filesystem contains the specified Item. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ public boolean containsId(Object itemId) { if (!(itemId instanceof File)) { return false; } boolean val = false; // Try to match all roots for (int i = 0; i < roots.length; i++) { try { val |= ((File) itemId).getCanonicalPath().startsWith( roots[i].getCanonicalPath()); } catch (final IOException e) { // Exception ignored } } if (val && filter != null) { val &= filter.accept(((File) itemId).getParentFile(), ((File) itemId).getName()); } return val; } /* * Gets the specified Item from the filesystem. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Item getItem(Object itemId) { if (!(itemId instanceof File)) { return null; } return new FileItem((File) itemId); } /** * Internal recursive method to add the files under the specified directory * to the collection. * * @param col * the collection where the found items are added * @param f * the root file where to start adding files */ private void addItemIds(Collection col, File f) { File[] l; if (filter != null) { l = f.listFiles(filter); } else { l = f.listFiles(); } final List ll = Arrays.asList(l); Collections.sort(ll); for (final Iterator i = ll.iterator(); i.hasNext();) { final File lf = (File) i.next(); col.add(lf); if (lf.isDirectory()) { addItemIds(col, lf); } } } /* * Gets the IDs of Items in the filesystem. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Collection getItemIds() { if (recursive) { final Collection col = new ArrayList(); for (int i = 0; i < roots.length; i++) { addItemIds(col, roots[i]); } return Collections.unmodifiableCollection(col); } else { File[] f; if (roots.length == 1) { if (filter != null) { f = roots[0].listFiles(filter); } else { f = roots[0].listFiles(); } } else { f = roots; } if (f == null) { return Collections.unmodifiableCollection(new LinkedList()); } final List l = Arrays.asList(f); Collections.sort(l); return Collections.unmodifiableCollection(l); } } /** * Gets the specified property of the specified file Item. The available * file properties are "Name", "Size" and "Last Modified". If propertyId is * not one of those, <code>null</code> is returned. * * @param itemId * the ID of the file whose property is requested. * @param propertyId * the property's ID. * @return the requested property's value, or <code>null</code> */ public Property getContainerProperty(Object itemId, Object propertyId) { if (!(itemId instanceof File)) { return null; } if (propertyId.equals(PROPERTY_NAME)) { return new MethodProperty(getType(propertyId), new FileItem( (File) itemId), FILEITEM_NAME, null); } if (propertyId.equals(PROPERTY_ICON)) { return new MethodProperty(getType(propertyId), new FileItem( (File) itemId), FILEITEM_ICON, null); } if (propertyId.equals(PROPERTY_SIZE)) { return new MethodProperty(getType(propertyId), new FileItem( (File) itemId), FILEITEM_SIZE, null); } if (propertyId.equals(PROPERTY_LASTMODIFIED)) { return new MethodProperty(getType(propertyId), new FileItem( (File) itemId), FILEITEM_LASTMODIFIED, null); } return null; } /** * Gets the collection of available file properties. * * @return Unmodifiable collection containing all available file properties. */ public Collection getContainerPropertyIds() { return FILE_PROPERTIES; } /** * Gets the specified property's data type. "Name" is a <code>String</code>, * "Size" is a <code>Long</code>, "Last Modified" is a <code>Date</code>. If * propertyId is not one of those, <code>null</code> is returned. * * @param propertyId * the ID of the property whose type is requested. * @return data type of the requested property, or <code>null</code> */ public Class getType(Object propertyId) { if (propertyId.equals(PROPERTY_NAME)) { return String.class; } if (propertyId.equals(PROPERTY_ICON)) { return Resource.class; } if (propertyId.equals(PROPERTY_SIZE)) { return Long.class; } if (propertyId.equals(PROPERTY_LASTMODIFIED)) { return Date.class; } return null; } /** * Internal method to recursively calculate the number of files under a root * directory. * * @param f * the root to start counting from. */ private int getFileCounts(File f) { File[] l; if (filter != null) { l = f.listFiles(filter); } else { l = f.listFiles(); } if (l == null) { return 0; } int ret = l.length; for (int i = 0; i < l.length; i++) { if (l[i].isDirectory()) { ret += getFileCounts(l[i]); } } return ret; } /** * Gets the number of Items in the container. In effect, this is the * combined amount of files and directories. * * @return Number of Items in the container. */ public int size() { if (recursive) { int counts = 0; for (int i = 0; i < roots.length; i++) { counts += getFileCounts(roots[i]); } return counts; } else { File[] f; if (roots.length == 1) { if (filter != null) { f = roots[0].listFiles(filter); } else { f = roots[0].listFiles(); } } else { f = roots; } if (f == null) { return 0; } return f.length; } } /** * A Item wrapper for files in a filesystem. * * @author IT Mill Ltd. * @version * @VERSION@ * @since 3.0 */ public class FileItem implements Item { /** * The wrapped file. */ private final File file; /** * Constructs a FileItem from a existing file. */ private FileItem(File file) { this.file = file; } /* * Gets the specified property of this file. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Property getItemProperty(Object id) { return getContainerProperty(file, id); } /* * Gets the IDs of all properties available for this item Don't add a * JavaDoc comment here, we use the default documentation from * implemented interface. */ public Collection getItemPropertyIds() { return getContainerPropertyIds(); } /** * Calculates a integer hash-code for the Property that's unique inside * the Item containing the Property. Two different Properties inside the * same Item contained in the same list always have different * hash-codes, though Properties in different Items may have identical * hash-codes. * * @return A locally unique hash-code as integer */ @Override public int hashCode() { return file.hashCode() ^ FilesystemContainer.this.hashCode(); } /** * Tests if the given object is the same as the this object. Two * Properties got from an Item with the same ID are equal. * * @param obj * an object to compare with this object. * @return <code>true</code> if the given object is the same as this * object, <code>false</code> if not */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FileItem)) { return false; } final FileItem fi = (FileItem) obj; return fi.getHost() == getHost() && fi.file.equals(file); } /** * Gets the host of this file. */ private FilesystemContainer getHost() { return FilesystemContainer.this; } /** * Gets the last modified date of this file. * * @return Date */ public Date lastModified() { return new Date(file.lastModified()); } /** * Gets the name of this file. * * @return file name of this file. */ public String getName() { return file.getName(); } /** * Gets the icon of this file. * * @return the icon of this file. */ public Resource getIcon() { return FileTypeResolver.getIcon(file); } /** * Gets the size of this file. * * @return size */ public long getSize() { if (file.isDirectory()) { return 0; } return file.length(); } /** * @see java.lang.Object#toString() */ @Override public String toString() { if ("".equals(file.getName())) { return file.getAbsolutePath(); } return file.getName(); } /** * Filesystem container does not support adding new properties. * * @see com.vaadin.data.Item#addItemProperty(Object, Property) */ public boolean addItemProperty(Object id, Property property) throws UnsupportedOperationException { throw new UnsupportedOperationException("Filesystem container " + "does not support adding new properties"); } /** * Filesystem container does not support removing properties. * * @see com.vaadin.data.Item#removeItemProperty(Object) */ public boolean removeItemProperty(Object id) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Filesystem container does not support property removal"); } } /** * Generic file extension filter for displaying only files having certain * extension. * * @author IT Mill Ltd. * @version * @VERSION@ * @since 3.0 */ public class FileExtensionFilter implements FilenameFilter, Serializable { private final String filter; /** * Constructs a new FileExtensionFilter using given extension. * * @param fileExtension * the File extension without the separator (dot). */ public FileExtensionFilter(String fileExtension) { filter = "." + fileExtension; } /** * Allows only files with the extension and directories. * * @see java.io.FilenameFilter#accept(File, String) */ public boolean accept(File dir, String name) { if (name.endsWith(filter)) { return true; } return new File(dir, name).isDirectory(); } } /** * Returns the file filter used to limit the files in this container. * * @return Used filter instance or null if no filter is assigned. */ public FilenameFilter getFilter() { return filter; } /** * Sets the file filter used to limit the files in this container. * * @param filter * The filter to set. <code>null</code> disables filtering. */ public void setFilter(FilenameFilter filter) { this.filter = filter; } /** * Sets the file filter used to limit the files in this container. * * @param extension * the Filename extension (w/o separator) to limit the files in * container. */ public void setFilter(String extension) { filter = new FileExtensionFilter(extension); } /** * Is this container recursive filesystem. * * @return <code>true</code> if container is recursive, <code>false</code> * otherwise. */ public boolean isRecursive() { return recursive; } /** * Sets the container recursive property. Set this to false to limit the * files directly under the root file. * <p> * Note : This is meaningful only if the root really is a directory. * </p> * * @param recursive * the New value for recursive property. */ public void setRecursive(boolean recursive) { this.recursive = recursive; } /* * (non-Javadoc) * * @see com.vaadin.data.Container#addContainerProperty(java.lang.Object, * java.lang.Class, java.lang.Object) */ public boolean addContainerProperty(Object propertyId, Class<?> type, Object defaultValue) throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#addItem() */ public Object addItem() throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#addItem(java.lang.Object) */ public Item addItem(Object itemId) throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeAllItems() */ public boolean removeAllItems() throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeItem(java.lang.Object) */ public boolean removeItem(Object itemId) throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } /* * (non-Javadoc) * * @see com.vaadin.data.Container#removeContainerProperty(java.lang.Object ) */ public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { throw new UnsupportedOperationException( "File system container does not support this operation"); } }
package com.secret.fastalign.main; import jaligner.Alignment; import jaligner.SmithWatermanGotoh; import jaligner.matrix.MatrixLoader; import jaligner.matrix.MatrixLoaderException; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import com.secret.fastalign.general.FastaData; import com.secret.fastalign.general.Sequence; import com.secret.fastalign.utils.IntervalTree; import com.secret.fastalign.utils.Utils; public class EstimateROC { private static final double MIN_IDENTITY = 0.60; private static final int DEFAULT_NUM_TRIALS = 10000; private static final int DEFAULT_MIN_OVL = 500; private static boolean DEBUG = false; private static class Pair { public int first; public int second; public Pair(int startInRef, int endInRef) { this.first = startInRef; this.second = endInRef; } @SuppressWarnings("unused") public int size() { return (Math.max(this.first, this.second) - Math.min(this.first, this.second) + 1); } } private static class Overlap { public int afirst; public int bfirst; public int asecond; public int bsecond; public boolean isFwd; public String id1; public String id2; public Overlap() { // do nothing } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Overlap Aid="); stringBuilder.append(this.id1); stringBuilder.append(" ("); stringBuilder.append(this.afirst); stringBuilder.append(", "); stringBuilder.append(this.asecond); stringBuilder.append("), Bid="); stringBuilder.append(this.id2); stringBuilder.append(" ("); stringBuilder.append(this.bfirst); stringBuilder.append("), "); stringBuilder.append(this.bsecond); return stringBuilder.toString(); } } private static Random generator = null; public static int seed = 0; private HashMap<String, IntervalTree<Integer>> clusters = new HashMap<String, IntervalTree<Integer>>(); private HashMap<String, String> seqToChr = new HashMap<String, String>(10000000); private HashMap<String, Integer> seqToScore = new HashMap<String, Integer>(10000000); private HashMap<String, Pair> seqToPosition = new HashMap<String, Pair>(10000000); private HashMap<Integer, String> seqToName = new HashMap<Integer, String>(10000000); private HashMap<String, Integer> seqNameToIndex = new HashMap<String, Integer>(10000000); private HashSet<String> ovlNames = new HashSet<String>(10000000*10); private HashMap<String, Overlap> ovlInfo = new HashMap<String, Overlap>(10000000*10); private HashMap<Integer, String> ovlToName = new HashMap<Integer, String>(10000000*10); private int minOvlLen = DEFAULT_MIN_OVL; private int numTrials = DEFAULT_NUM_TRIALS; private long tp = 0; private long fn = 0; private long tn = 0; private long fp = 0; private double ppv = 0; private Sequence[] dataSeq = null; public static void printUsage() { System.err .println("This program uses random sampling to estimate PPV/Sensitivity/Specificity"); System.err.println("The program requires 2 arguments:"); System.err .println("\t1. A blasr M4 file mapping sequences to a reference (or reference subset)"); System.err .println("\t2. All-vs-all mappings of same sequences in CA ovl format"); System.err.println("\t3. Minimum overlap length (default: " + DEFAULT_MIN_OVL); System.err.println("\t4. Number of random trials, 0 means full compute (default : " + DEFAULT_NUM_TRIALS); System.err.println("\t5. Sequences in fasta format."); } public static void main(String[] args) throws Exception { if (args.length < 2) { printUsage(); System.exit(1); } EstimateROC g = null; if (args.length > 3) { g = new EstimateROC(Integer.parseInt(args[2]), Integer.parseInt(args[3])); } else if (args.length > 2) { g = new EstimateROC(Integer.parseInt(args[2])); } else { g = new EstimateROC(); } if (args.length > 5) { DEBUG = Boolean.parseBoolean(args[5]); } System.err.println("Running, reference: " + args[0] + " matches: " + args[1]); System.err.println("Number trials: " + (g.numTrials == 0 ? "all" : g.numTrials)); System.err.println("Minimum ovl: " + g.minOvlLen); // load and cluster reference System.err.print("Loading reference..."); long startTime = System.nanoTime(); long totalTime = startTime; g.processReference(args[0]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); if (args.length > 4) { // load fasta System.err.print("Loading fasta..."); startTime = System.nanoTime(); g.loadFasta(args[4]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); } // load matches System.err.print("Loading matches..."); startTime = System.nanoTime(); g.processOverlaps(args[1]); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); if (g.numTrials == 0) { System.err.print("Computing full statistics O(" + g.seqToName.size() + "^2) operations!..."); startTime = System.nanoTime(); g.fullEstimate(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); } else { System.err.print("Computing sensitivity..."); startTime = System.nanoTime(); g.estimateSensitivity(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // now estimate FP/TN by picking random match and checking reference // mapping System.err.print("Computing specificity..."); startTime = System.nanoTime(); g.estimateSpecificity(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); // last but not least PPV, pick random subset of our matches and see what percentage are true System.err.print("Computing PPV..."); startTime = System.nanoTime(); g.estimatePPV(); System.err.println("done " + (System.nanoTime() - startTime) * 1.0e-9 + "s."); } System.err.println("Total time: " + (System.nanoTime() - totalTime) * 1.0e-9 + "s."); System.out.println("Estimated sensitivity:\t" + Utils.DECIMAL_FORMAT.format((double) g.tp / (double)(g.tp + g.fn))); System.out.println("Estimated specificity:\t" + Utils.DECIMAL_FORMAT.format((double) g.tn / (double)(g.fp + g.tn))); System.out.println("Estimated PPV:\t " + Utils.DECIMAL_FORMAT.format(g.ppv)); } public EstimateROC() { this(DEFAULT_MIN_OVL, DEFAULT_NUM_TRIALS); } public EstimateROC(int minOvlLen) { this(minOvlLen, DEFAULT_NUM_TRIALS); } @SuppressWarnings("unused") public EstimateROC(int minOvlLen, int numTrials) { this.minOvlLen = minOvlLen; this.numTrials = numTrials; if (false) { GregorianCalendar t = new GregorianCalendar(); int t1 = t.get(Calendar.SECOND); int t2 = t.get(Calendar.MINUTE); int t3 = t.get(Calendar.HOUR_OF_DAY); int t4 = t.get(Calendar.DAY_OF_MONTH); int t5 = t.get(Calendar.MONTH); int t6 = t.get(Calendar.YEAR); seed = t6 + 65 * (t5 + 12 * (t4 + 31 * (t3 + 24 * (t2 + 60 * t1)))); } generator = new Random(seed); } private String getOvlName(String id, String id2) { return (id.compareTo(id2) <= 0 ? id + "_" + id2 : id2 + "_" + id); } private String pickRandomSequence() { int val = generator.nextInt(this.seqToName.size()); return this.seqToName.get(val); } private String pickRandomMatch() { int val = generator.nextInt(this.ovlToName.size()); return this.ovlToName.get(val); } private int getOverlapSize(String id, String id2) { String chr = this.seqToChr.get(id); String chr2 = this.seqToChr.get(id2); Pair p1 = this.seqToPosition.get(id); Pair p2 = this.seqToPosition.get(id2); if (!chr.equalsIgnoreCase(chr2)) { System.err.println("Error: comparing wrong chromosomes betweeen sequences " + id + " and sequence " + id2); System.exit(1); } return Utils.getRangeOverlap(p1.first, p1.second, p2.first, p2.second); } private HashSet<String> getSequenceMatches(String id, int min) { String chr = this.seqToChr.get(id); Pair p1 = this.seqToPosition.get(id); List<Integer> intersect = this.clusters.get(chr).get(p1.first, p1.second); HashSet<String> result = new HashSet<String>(); Iterator<Integer> it = intersect.iterator(); while (it.hasNext()) { String id2 = this.seqToName.get(it.next()); Pair p2 = this.seqToPosition.get(id2); String chr2 = this.seqToChr.get(id2); if (!chr.equalsIgnoreCase(chr2)) { System.err.println("Error: comparing wrong chromosomes betweeen sequences " + id + " and sequence in its cluster " + id2); System.exit(1); } int overlap = Utils.getRangeOverlap(p1.first, p1.second, p2.first, p2.second); if (overlap >= min && !id.equalsIgnoreCase(id2)) { result.add(id2); } } return result; } @SuppressWarnings("unused") private Overlap getOverlapInfo(String line) { Overlap overlap = new Overlap(); String[] splitLine = line.trim().split("\\s+"); try { if (splitLine.length == 7 || splitLine.length == 6) { overlap.id1 = splitLine[0]; overlap.id2 = splitLine[1]; double score = Double.parseDouble(splitLine[5]) * 5; int aoffset = Integer.parseInt(splitLine[3]); int boffset = Integer.parseInt(splitLine[4]); boolean isFwd = ("N".equals(splitLine[2])); if (this.dataSeq != null) { int alen = this.dataSeq[Integer.parseInt(overlap.id1)-1].length(); int blen = this.dataSeq[Integer.parseInt(overlap.id2)-1].length(); overlap.afirst = Math.max(0, aoffset); overlap.asecond = Math.min(alen, alen + boffset); overlap.bfirst = -1*Math.min(0, aoffset); overlap.bsecond = Math.min(blen, blen - boffset); } } else if (splitLine.length == 13) { overlap.afirst = Integer.parseInt(splitLine[5]); overlap.asecond = Integer.parseInt(splitLine[6]); overlap.bfirst = Integer.parseInt(splitLine[9]); overlap.bsecond = Integer.parseInt(splitLine[10]); overlap.isFwd = (Integer.parseInt(splitLine[8]) == 0); if (!overlap.isFwd) { overlap.bsecond = Integer.parseInt(splitLine[11]) - Integer.parseInt(splitLine[9]); overlap.bfirst = Integer.parseInt(splitLine[11]) - Integer.parseInt(splitLine[10]); } overlap.id1 = splitLine[0]; if (overlap.id1.indexOf("/") != -1) { overlap.id1 = overlap.id1.substring(0, splitLine[0].indexOf("/")); } if (overlap.id1.indexOf(",") != -1) { overlap.id1 = overlap.id1.split(",")[1]; } overlap.id2 = splitLine[1]; if (overlap.id2.indexOf(",") != -1) { overlap.id2 = overlap.id2.split(",")[1]; } } } catch (NumberFormatException e) { System.err.println("Warning: could not parse input line: " + line + " " + e.getMessage()); } return overlap; } private void loadFasta(String file) throws IOException { FastaData data = new FastaData(file, 0); data.enqueueFullFile(); this.dataSeq = data.toArray(); } private void processOverlaps(String file) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String line = null; int counter = 0; while ((line = bf.readLine()) != null) { Overlap ovl = getOverlapInfo(line); String id = ovl.id1; String id2 = ovl.id2; if (id == null || id2 == null) { continue; } if (id.equalsIgnoreCase(id2)) { continue; } if (this.seqToChr.get(id) == null || this.seqToChr.get(id2) == null) { continue; } String ovlName = getOvlName(id, id2); if (this.ovlNames.contains(ovlName)) { continue; } this.ovlNames.add(ovlName); this.ovlToName.put(counter, ovlName); this.ovlInfo.put(ovlName, ovl); counter++; if (counter % 100000 == 0) { System.err.println("Loaded " + counter); } } System.err.print("Processed " + this.ovlNames.size() + " overlaps"); if (this.ovlNames.isEmpty()) { System.err .println("Error: No sequence matches to reference loaded!"); System.exit(1); } bf.close(); } /** * We are parsing file of the format 18903/0_100 ref000001|lambda_NEB3011 * -462 96.9697 0 0 99 100 0 2 101 48502 254 21589/0_100 * ref000001|lambda_NEB3011 -500 100 0 0 100 100 1 4 104 48502 254 * 15630/0_100 ref000001|lambda_NEB3011 -478 98 0 0 100 100 0 5 105 48502 * 254 **/ @SuppressWarnings("unused") private void processReference(String file) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(file))); String line = null; int counter = 0; while ((line = bf.readLine()) != null) { String[] splitLine = line.trim().split("\\s+"); String id = splitLine[0]; if (id.indexOf("/") != -1) { id = id.substring(0, splitLine[0].indexOf("/")); } if (id.indexOf(",") != -1) { id = id.split(",")[1]; } int start = Integer.parseInt(splitLine[5]); int end = Integer.parseInt(splitLine[6]); int length = Integer.parseInt(splitLine[7]); int startInRef = Integer.parseInt(splitLine[9]); int endInRef = Integer.parseInt(splitLine[10]); int score = Integer.parseInt(splitLine[2]); String chr = splitLine[1]; if (!this.clusters.containsKey(chr)) { this.clusters.put(chr, new IntervalTree<Integer>()); } if (this.seqToPosition.containsKey(id)) { if (score < this.seqToScore.get(id)) { // replace this.seqToPosition.put(id, new Pair(startInRef, endInRef)); this.seqToChr.put(id, chr); this.seqToScore.put(id, score); } } else { this.seqToPosition.put(id, new Pair(startInRef, endInRef)); this.seqToChr.put(id, chr); this.seqToName.put(counter, id); this.seqNameToIndex.put(id, counter); this.seqToScore.put(id, score); counter++; } } bf.close(); for (String id : this.seqToPosition.keySet()) { String chr = this.seqToChr.get(id); if (!this.clusters.containsKey(chr)) { this.clusters.put(chr, new IntervalTree<Integer>()); } Pair p = this.seqToPosition.get(id); this.clusters.get(chr).addInterval(p.first, p.second, this.seqNameToIndex.get(id)); } System.err.print("Processed " + this.clusters.size() + " chromosomes, " + this.seqToPosition.size() + " sequences matching ref"); if (this.seqToPosition.isEmpty()) { System.err .println("Error: No sequence matches to reference loaded!"); System.exit(1); } } private boolean overlapExists(String id, String id2) { return this.ovlNames.contains(getOvlName(id, id2)); } private void checkMatches(String id, HashSet<String> matches) { for (String m : matches) { if (overlapExists(id, m)) { this.tp++; } else { this.fn++; if (DEBUG) { System.err.println("Overlap between sequences: " + id + ", " + m + " is missing."); } } } } private boolean computeDP(String id, String id2) { if (this.dataSeq == null) { return false; } Logger logger = Logger.getLogger(SmithWatermanGotoh.class.getName()); logger.setLevel(Level.OFF); logger = Logger.getLogger(MatrixLoader.class.getName()); logger.setLevel(Level.OFF); Overlap ovl = this.ovlInfo.get(getOvlName(id, id2)); jaligner.Sequence s1 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id1)-1].toString().substring(ovl.afirst, ovl.asecond)); jaligner.Sequence s2 = null; if (ovl.isFwd) { s2 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id2)-1].toString().substring(ovl.bfirst, ovl.bsecond)); } else { s2 = new jaligner.Sequence(this.dataSeq[Integer.parseInt(ovl.id2)-1].getReverseCompliment().toString().substring(ovl.bfirst, ovl.bsecond)); } Alignment alignment; try { alignment = SmithWatermanGotoh.align(s1, s2, MatrixLoader.load("IDENTITY"), 2f, 1f); } catch (MatrixLoaderException e) { return false; } return ((double)alignment.getSimilarity()/s1.length() > MIN_IDENTITY); } private void estimateSensitivity() { // we estimate TP/FN by randomly picking a sequence, getting its // cluster, and checking our matches for (int i = 0; i < this.numTrials; i++) { // pick cluster String id = pickRandomSequence(); HashSet<String> matches = getSequenceMatches(id, this.minOvlLen); if (DEBUG) { System.err.println("Estimated sensitivity trial #" + i + " " + id + " matches " + matches); } checkMatches(id, matches); } } private void estimateSpecificity() { // we estimate FP/TN by randomly picking two sequences for (int i = 0; i < this.numTrials; i++) { // pick cluster String id = pickRandomSequence(); String other = pickRandomSequence(); while (id.equalsIgnoreCase(other)) { other = pickRandomSequence(); } HashSet<String> matches = getSequenceMatches(id, 0); if (overlapExists(id, other)) { if (!matches.contains(other)) { this.fp++; } } else { if (!matches.contains(other)) { this.tn++; } } } } private void estimatePPV() { int numTP = 0; for (int i = 0; i < this.numTrials; i++) { int ovlLen = 0; String[] ovl = null; String ovlName = null; while (ovlLen < this.minOvlLen) { // pick an overlap ovlName = pickRandomMatch(); Overlap o = this.ovlInfo.get(ovlName); ovlLen = Utils.getRangeOverlap(o.afirst, o.asecond, o.bfirst, o.bsecond); } if (ovlName == null) { System.err.println("Could not find any computed overlaps > " + this.minOvlLen); System.exit(1); } else { ovl = ovlName.split("_"); String id = ovl[0]; String id2 = ovl[1]; HashSet<String> matches = getSequenceMatches(id, 0); if (matches.contains(id2)) { numTP++; } else { if (computeDP(id, id2)) { numTP++; } else { if (DEBUG) { System.err.println("Overlap between sequences: " + id + ", " + id2 + " is not correct."); } } } } } // now our formula for PPV. Estimate percent of our matches which are true this.ppv = (double)numTP / (double)this.numTrials; } @SuppressWarnings("cast") private void fullEstimate() { for (int i = 0; i < this.seqToName.size(); i++) { String id = this.seqToName.get(i); for (int j = i+1; j < this.seqToName.size(); j++) { String id2 = this.seqToName.get(j); if (id == null || id2 == null) { continue; } HashSet<String> matches = getSequenceMatches(id, 0); if (!overlapExists(id, id2)) { if (!matches.contains(id2)) { this.tn++; } else if (getOverlapSize(id, id2) > this.minOvlLen) { this.fn++; } } else { if (matches.contains(id2)) { this.tp++; } else { if (computeDP(id, id2)) { this.tp++; } else { this.fp++; } } } } } this.ppv = (double) this.tp / ((double)this.tp+(double)this.fp); } }
package com.skelril.aurora.util; import com.skelril.aurora.util.item.ItemUtil; import org.bukkit.inventory.ItemStack; import java.util.*; public class ItemCondenser { private Map<ItemStack, ItemStack> supported = new HashMap<>(); private List<Step> conversionSteps = new ArrayList<>(); public void addSupport(ItemStack from, ItemStack to) { supported.put(from, to); compile(); } public boolean supports(ItemStack itemStack) { for (ItemStack is : supported.keySet()) { if (itemStack.isSimilar(is)) { return true; } } return true; } /** * * @param itemStacks - the old item stacks * @return the new item stacks, or null if the operation could not be completed/did nothing */ public ItemStack[] operate(ItemStack[] itemStacks) { itemStacks = ItemUtil.clone(itemStacks); // Make sure we're working in our domain here List<Remainder> remainders = new ArrayList<>(); int modified = 0; for (Step step : conversionSteps) { int total = 0; List<Integer> positions = new ArrayList<>(); ItemStack target = step.getOldItem(); for (int i = 0; i < itemStacks.length; ++i) { ItemStack cur = itemStacks[i]; if (target.isSimilar(cur)) { total += cur.getAmount(); positions.add(i); } } // Add in any remainders from prior steps Iterator<Remainder> it = remainders.iterator(); while (it.hasNext()) { Remainder remainder = it.next(); if (step.getOldItem().isSimilar(remainder.getItem())) { total += remainder.getAmount(); it.remove(); } } int divisor = step.getOldItem().getAmount(); int newAmt = (total / divisor) * step.getNewItem().getAmount(); if (newAmt < 1) continue; int oldAmt = total % divisor; for (Integer pos : positions) { itemStacks[pos] = null; } final ItemStack newStack = step.getNewItem(); final ItemStack oldStack = step.getOldItem(); remainders.add(new Remainder(oldStack, oldAmt)); remainders.add(new Remainder(newStack, newAmt)); ++modified; } for (Remainder remainder : remainders) { ItemStack rStack = remainder.getItem(); for (int i = 0; i < itemStacks.length; ++i) { final ItemStack stack = itemStacks[i]; int startingAmt = stack == null ? 0 : stack.getAmount(); int rAmt = remainder.getAmount(); int quantity; if (rAmt > 0 && (startingAmt == 0 || rStack.isSimilar(stack))) { quantity = Math.min(rAmt + startingAmt, rStack.getMaxStackSize()); rAmt -= quantity - startingAmt; itemStacks[i] = rStack.clone(); itemStacks[i].setAmount(quantity); remainder.setAmount(rAmt); } else if (rAmt == 0) { break; } } // We couldn't place all items if (remainder.getAmount() > 0) return null; } return modified == 0 ? null : itemStacks; } private void compile() { conversionSteps.clear(); for (Map.Entry<ItemStack, ItemStack> entry : supported.entrySet()) { addStep: { Step step = new Step(entry.getKey(), entry.getValue()); for (int i = 0; i < conversionSteps.size(); ++i) { // If the step's needed item, is what this makes, put this in front if (conversionSteps.get(i).getOldItem().equals(step.getNewItem())) { conversionSteps.add(i, step); break addStep; } } conversionSteps.add(step); } } } private static class Step { private ItemStack oldItem; private ItemStack newItem; private Step(ItemStack oldItem, ItemStack newItem) { this.oldItem = oldItem; this.newItem = newItem; } public ItemStack getOldItem() { return oldItem.clone(); } public ItemStack getNewItem() { return newItem.clone(); } } private static class Remainder { private final ItemStack item; private int amount; public Remainder(ItemStack item, int amount) { this.item = item.clone(); this.amount = amount; } public ItemStack getItem() { return item.clone(); } public int getAmount() { return amount; } public void setAmount(int amt) { this.amount = amt; } } }
package com.xnx3.j2ee.generateCache; import java.io.IOException; import com.xnx3.file.FileUtil; import com.xnx3.j2ee.Global; public class BaseGenerate { private String content; private String objName; /** * js * @param objName jsjsjs */ void createCacheObject(String objName){ this.objName=objName; content="var "+objName+" = new Array(); "; } /** * js * @param key * @param value */ void cacheAdd(Object key,Object value){ content += objName+"['"+key+"']='"+value+"'; "; } void generateCacheFile(){ addCommonJsFunction(); try { FileUtil.write(Global.projectPath+Global.CACHE_FILE+getClass().getSimpleName()+"_"+objName+".js", content,FileUtil.UTF8); } catch (IOException e) { e.printStackTrace(); } // FileUtil.write(Global.projectPath+Global.CACHE_FILE+getClass().getSimpleName()+"_"+objName+".js", content); this.content=null; } void addCommonJsFunction(){ this.content+= "/*option*/ function writeSelectAllOptionFor"+this.objName+"(selectId){ var content = \"\"; if(selectId==''){ content = content + '<option value=\"\" selected=\"selected\"></option>'; }else{ content = content + '<option value=\"\"></option>'; } for(var p in "+this.objName+"){ if(p == selectId){ content = content+'<option value=\"'+p+'\" selected=\"selected\">'+"+this.objName+"[p]+'</option>'; }else{ content = content+'<option value=\"'+p+'\">'+"+this.objName+"[p]+'</option>'; } } document.write(content); }"; } void appendContent(String content){ this.content = this.content+" "+content; } }
package com.wangc.test_plan.service; import com.wangc.comm.Param; import com.wangc.test_plan.bean.LogResultBean; import com.wangc.test_plan.bean.RunPlanBean; import com.wangc.test_plan.mapper.RPMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.*; import java.util.List; import java.util.Timer; import java.util.TimerTask; @Service public class RPService { @Autowired RPMapper rpMapper; public void insert(RunPlanBean rpb){ rpMapper.insertSelective(rpb); } public List<RunPlanBean> list(String tId){ RunPlanBean rpb = new RunPlanBean(); rpb.setTpId(tId); return rpMapper.select(rpb); } public static void main(String[] args){ RPService rps = new RPService(); String p = "D:\\workspace_HelloWorld\\testing_platform\\jmeter\\log\\2017\\07\\1500886505219_24165505219.log"; long l = 0L; LogResultBean s = rps.runlogList(p,l); Long aa = s.getModifiedTime(); System.out.println( s.getContent() ); try{ Thread.sleep(10000); }catch (Exception e){ e.printStackTrace(); } System.out.println( rps.runlogList(p,aa).getContent() ); } /* * @logPath * @oldLastModified modified * */ public LogResultBean runlogList(String logPath, long lastModified){ String result = ""; long modifiedTime = 0L; try { File file = new File(Param.USER_DIR+Param.LOG_PATH+logPath); modifiedTime = file.lastModified(); if (modifiedTime != lastModified) { System.out.println(""); result = readFile(file); } } catch (Exception e) { e.printStackTrace(); } return new LogResultBean(logPath,modifiedTime,result); //result } private String readFile(File file) { String content = ""; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); StringBuffer buffer = new StringBuffer(); String temp; while ((temp = reader.readLine()) != null) { if(temp.contains("o.a.j.r.Summariser")){ //todo buffer.append(temp.replace("INFO o.a.j.r.Summariser","")).append(" } } reader.close(); content = buffer.toString(); } catch (FileNotFoundException e) { System.out.println(""); } catch (IOException e) { System.err.println(""); } return content; } }
package edu.gatech.oad.antlab.pkg1; import edu.cs2335.antlab.pkg3.*; import edu.gatech.oad.antlab.person.*; import edu.gatech.oad.antlab.pkg2.*; /** * CS2335 Ant Lab * * Prints out a simple message gathered from all of the other classes * in the package structure */ public class AntLabMain { /**antlab11.java message class*/ private AntLab11 ant11; /**antlab12.java message class*/ private AntLab12 ant12; /**antlab21.java message class*/ private AntLab21 ant21; /**antlab22.java message class*/ private AntLab22 ant22; /**antlab31 java message class which is contained in a jar resource file*/ private AntLab31 ant31; /** * the constructor that intializes all the helper classes */ public AntLabMain () { ant11 = new AntLab11(); ant12 = new AntLab12(); ant21 = new AntLab21(); ant22 = new AntLab22(); ant31 = new AntLab31(); } /** * gathers a string from all the other classes and prints the message * out to the console * */ public void printOutMessage() { String toPrint = ant11.getMessage() + ant12.getMessage() + ant21.getMessage() + ant22.getMessage() + ant31.getMessage(); //Person1 replace P1 with your name //and gburdell1 with your gt id Person1 p1 = new Person1("Vinutna Veeragandham"); toPrint += p1.toString("vveeragandham3"); //Person2 replace P2 with your name //and gburdell with your gt id Person2 p2 = new Person2("Stefan Young"); toPrint += p2.toString("syoung67"); //Person3 replace P3 with your name //and gburdell3 with your gt id Person3 p3 = new Person3("P3"); toPrint += p3.toString("gburdell3"); //Person4 replace P4 with your name //and gburdell4 with your gt id Person4 p4 = new Person4("Sean Titus"); toPrint += p4.toString("stitus7"); //Person5 replace P4 with your name //and gburdell5 with your gt id Person5 p5 = new Person5("Nancy Tao"); toPrint += p5.toString("ntao6"); System.out.println(toPrint); } /** * entry point for the program */ public static void main(String[] args) { new AntLabMain().printOutMessage(); } }
package edu.wright.hendrix11.c3; import org.apache.commons.lang3.StringUtils; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import javax.faces.render.Renderer; import java.io.IOException; /** * @author Joe Hendrix */ @FacesRenderer(rendererType = ChartComponent.DEFAULT_RENDERER, componentFamily = ChartComponent.COMPONENT_FAMILY) public class ChartRenderer extends Renderer { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ChartComponent chart = (ChartComponent) component; ChartModel model = chart.getChartModel(); ResponseWriter writer = context.getResponseWriter(); writer.startElement("div", null); writer.writeAttribute("id", chart.getId(), "id"); if ( chart.getStyle() != null ) { writer.writeAttribute("style", chart.getStyle(), "style"); } writer.endElement("div"); encodeScript(chart, model, writer); } private void encodeScript(ChartComponent chart, ChartModel model, ResponseWriter writer) { writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.write("var chart = c3.generate({"); writer.write("bindto:' writer.write(chart.getId()); writer.write("',"); encodeData(chart, model, writer); encodeAxis(chart, model, writer); encodeGrid(chart, writer); writer.write("});"); writer.endElement("script"); } private void encodeLegend(ChartComponent chart, ResponseWriter writer) { if(chart.getShowLegend() != null || chart.getLegendPosition() != null) { writer.write(",legend:{"); if(chart.getShowLegend() != null) { writer.write("show:"); writer.write(chart.getShowLegend()); } if(chart.getShowLegend() != null && chart.getLegendPosition() != null) { writer.write(","); } if(chart.getLegendPosition() != null) { writer.write("position:'"); writer.write(chart.getLegendPosition()); writer.write("'"); } writer.write(); writer.write("}"); } } private void encodeGrid(ChartComponent chart, ResponseWriter writer) { if(chart.getGridX() != null || chart.getGridY() != null) { writer.write(",grid:{"); if(chart.getGridX() != null) { writer.write("x:{show:"); writer.write(chart.getGridX()); writer.write("}"); } if(chart.getGridX() != null && chart.getGridY() != null) { writer.write(","); } if(chart.getGridY() != null) { writer.write("y:{show:"); writer.write(chart.getGridY()); writer.write("}"); } writer.write("}"); } } private void encodeAxis(ChartComponent chart, ChartModel model, ResponseWriter writer) { if(model.hasArrayData()) { writer.write(",axis:{x:{type:'category'}}"); } } private void encodeData(ChartComponent chart, ChartModel model, ResponseWriter writer) { writer.write("data:{"); if(model.hasArrayData()) { encodeArrayData(chart, model, writer); } else { writer.write("columns:[['data',"); writer.write(StringUtils.join(model.getData().values(),','); writer.write("]]"); } if(chart.getType() != null) { writer.write(",type:'"); writer.write(chart.getType()); writer.write("'"); } writer.write("}"); } private void encodeArrayData(ChartComponent chart, ChartModel model, ResponseWriter writer) { List<String> barLabels = model.getBarLabels(); if(barLabels == null || barLabels.isEmpty()) { barLabels = new ArrayList<>(); for(int i = 0; i < model.getArrayData().get(0).length; i++) { barLabels.add("data" + i); } } List<StringBuilder> data = new ArrayList<>(); for(String label : model.getAxisLabels()) { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append("'"); sb.append(label); sb.append("'"); sb.append(StringUtils.join(model.getArrayData(label),",")); sb.append("]"); data.add(sb); } writer.write("x:'x',rows:[['x','"); writer.write(StringUtils.join(barLabels,"','")); writer.write("'],"); writer.write(StringUtils.join(data,"','")); writer.write("]"); } }
package fi.solita.utils.functional; import static fi.solita.utils.functional.Collections.newList; import static fi.solita.utils.functional.Collections.newMap; import static fi.solita.utils.functional.Collections.newSet; import static fi.solita.utils.functional.Option.None; import static fi.solita.utils.functional.Option.Some; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import fi.solita.utils.functional.Iterables.ConcatenatingIterable; import fi.solita.utils.functional.Iterables.FilteringIterable; import fi.solita.utils.functional.Iterables.RangeIterable; import fi.solita.utils.functional.Iterables.RepeatingIterable; import fi.solita.utils.functional.Iterables.TransformingIterable; import fi.solita.utils.functional.Iterables.ZippingIterable; public abstract class Functional { /** * Returns a new iterable <code>a - b</code>, i.e. one that contains all elements of <code>a</code> that * don't exist in <code>b</code>. */ public static <T> Iterable<T> subtract(Iterable<T> a, final Collection<T> b) { return filter(a, new Predicate<T>() { @Override public boolean accept(T object) { return !b.contains(object); } }); } public static <T> Iterable<T> subtract(T[] a, final Collection<T> b) { return subtract(newList(a), b); } public static <T> Iterable<T> subtract(Iterable<T> a, final T[] b) { return subtract(a, newSet(b)); } public static <T> Iterable<T> subtract(T[] a, final T[] b) { return subtract(newList(a), newSet(b)); } public static <K, V> Option<V> find(Map<? extends K, V> map, K key) { return Option.of(map.get(key)); } public static <T> Option<T> find(T[] elements, Apply<? super T, Boolean> filter) { return find(Arrays.asList(elements), filter); } public static <T> Option<T> find(Iterable<T> elements, Apply<? super T, Boolean> filter) { return headOption(filter(elements, filter)); } public static <T> Iterable<T> filter(T[] elements, Apply<? super T, Boolean> filter) { return filter(Arrays.asList(elements), filter); } public static <T> Iterable<T> filter(Iterable<T> elements, Apply<? super T, Boolean> filter) { return new FilteringIterable<T>(elements, filter); } public static <T, E> Map<T, E> filter(Map<T, E> map, Apply<Map.Entry<? super T, ? super E>, Boolean> filter) { return Collections.newMap(filter(map.entrySet(), filter)); } public static <S, T> Iterable<T> map(S[] elements, Apply<? super S, ? extends T> transformer) { return map(Arrays.asList(elements), transformer); } public static <S, T> Iterable<T> map(Iterable<S> elements, Apply<? super S, ? extends T> transformer) { return new TransformingIterable<S,T>(elements, transformer); } public static <K1, V1, K2, V2> Map<K2, V2> map(Map<K1, V1> source, Apply<Map.Entry<K1, V1>, Map.Entry<K2, V2>> transformer) { return Collections.newMap(map(source.entrySet(), transformer)); } public static <S, T> Iterable<T> flatMap(S[] elements, Apply<? super S, ? extends Iterable<T>> transformer) { return flatMap(Arrays.asList(elements), transformer); } public static <S, T> Iterable<T> flatMap(Iterable<S> elements, Apply<? super S, ? extends Iterable<T>> transformer) { return flatten(map(elements, transformer)); } public static <T> Iterable<T> flatten(T[][] elements) { return flatten(map(elements, new Transformer<T[], Iterable<T>>() { @Override public Iterable<T> transform(T[] source) { return Arrays.asList(source); } })); } public static <T> Iterable<T> flatten(Iterable<? extends T>[] elements) { return flatten(map(elements, Function1.<Iterable<? extends T>>id())); } public static <T> Iterable<T> flatten(Iterable<? extends Iterable<? extends T>> elements) { return new ConcatenatingIterable<T>(elements); } public static <T> void foreach(T[] elements, Apply<? super T, Void> procedure) { foreach(Arrays.asList(elements), procedure); } public static <T> void foreach(Iterable<T> elements, Apply<? super T, Void> procedure) { for (T t: elements) { procedure.apply(t); } } /** * Non-lazy */ public static <T> Iterable<List<T>> grouped(T[] elements, int size) { return grouped(Arrays.asList(elements), size); } /** * Non-lazy */ public static <T> Iterable<List<T>> grouped(Iterable<T> elements, int size) { if (size <= 0) { throw new IllegalArgumentException("size must be positive"); } List<List<T>> target = Collections.newList(); Iterator<T> it = elements.iterator(); while (it.hasNext()) { List<T> group = Collections.newListOfSize(size); for (@SuppressWarnings("unused") int i: range(1, size)) { if (it.hasNext()) { group.add(it.next()); } } if (!group.isEmpty()) { target.add(group); } } return target; } /** * Non-lazy */ public static <G, T> Map<G, List<T>> groupBy(T[] elements, Apply<? super T,G> f) { return groupBy(Arrays.asList(elements), f); } /** * Non-lazy */ public static <G, T> Map<G, List<T>> groupBy(Iterable<T> elements, Apply<? super T,G> f) { Map<G, List<T>> target = newMap(); for (T t: elements) { G g = f.apply(t); Option<List<T>> groupOption = find(target, g); List<T> group; if (groupOption.isDefined()) { group = groupOption.get(); } else { group = Collections.newList(); target.put(g, group); } group.add(t); } return target; } public static <T> T head(T[] elements) { return head(Arrays.asList(elements)); } public static <T> T head(Iterable<T> elements) { return elements.iterator().next(); } public static <T> Option<T> headOption(T[] elements) { return headOption(Arrays.asList(elements)); } public static <T> Option<T> headOption(Iterable<T> elements) { Iterator<T> it = elements.iterator(); if (it.hasNext()) { return Some(it.next()); } else { return None(); } } public static <T> Iterable<T> tail(T[] elements) { return tail(Arrays.asList(elements)); } public static <T> Iterable<T> tail(Iterable<T> elements) { return drop(elements, 1); } public static <T> T last(T[] elements) { return last(Arrays.asList(elements)); } public static <T> T last(Iterable<T> elements) { Iterator<T> it = elements.iterator(); T ret = it.next(); while (it.hasNext()) { ret = it.next(); } return ret; } public static <T> Option<T> lastOption(T[] elements) { return lastOption(Arrays.asList(elements)); } public static <T> Option<T> lastOption(Iterable<T> elements) { Iterator<T> it = elements.iterator(); if (it.hasNext()) { T ret = it.next(); while (it.hasNext()) { ret = it.next(); } return Some(ret); } else { return None(); } } public static <T> Iterable<T> init(T[] elements) { return init(Arrays.asList(elements)); } public static <T> Iterable<T> init(Iterable<T> elements) { return take(elements, size(elements)-1); } public static <T> Iterable<T> take(T[] elements, int amount) { return take(Arrays.asList(elements), amount); } public static <T> Iterable<T> take(final Iterable<T> elements, final int amount) { return new Iterables.TakingIterable<T>(elements, amount); } public static <T> Iterable<T> drop(T[] elements, int amount) { return drop(Arrays.asList(elements), amount); } public static <T> Iterable<T> drop(final Iterable<T> elements, final int amount) { if (amount < 0) { throw new IllegalArgumentException("amount must be gte 0"); } return new Iterable<T>() { @Override public Iterator<T> iterator() { Iterator<T> it = elements.iterator(); int left = amount; while (left > 0 && it.hasNext()) { it.next(); left } return it; } }; } public static <T> Iterable<T> takeWhile(T[] elements, Apply<? super T, Boolean> predicate) { return takeWhile(Arrays.asList(elements), predicate); } public static <T> Iterable<T> takeWhile(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private Option<T> next; private Iterator<T> source = elements.iterator(); { readNext(); } @Override public boolean hasNext() { return next.isDefined(); } private void readNext() { if (!source.hasNext()) { next = None(); } else { T n = source.next(); if (predicate.apply(n)) { next = Some(n); } else { next = None(); } } } @Override public T next() { if (!next.isDefined()) { throw new NoSuchElementException(); } T ret = next.get(); readNext(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } public static <T> Iterable<T> dropWhile(T[] elements, Apply<? super T, Boolean> predicate) { return dropWhile(Arrays.asList(elements), predicate); } public static <T> Iterable<T> dropWhile(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private boolean dropping = true; private Iterator<T> source = elements.iterator(); private Option<T> next; { readNext(); } @Override public boolean hasNext() { return next.isDefined(); } private void readNext() { next = source.hasNext() ? Some(source.next()) : Option.<T>None(); while (dropping && next.isDefined() && predicate.apply(next.get())) { next = source.hasNext() ? Some(source.next()) : Option.<T>None(); } dropping = false; } @Override public T next() { if (!next.isDefined()) { throw new NoSuchElementException(); } T ret = next.get(); readNext(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } public static <T> Pair<Iterable<T>, Iterable<T>> span(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { // TODO: a more efficient implementation return Pair.of(takeWhile(elements, predicate), dropWhile(elements, predicate)); } public static boolean isEmpty(Iterable<?> elements) { return !elements.iterator().hasNext(); } public static int size(Iterable<?> elements) { return Iterables.resolveSize(elements).getOrElse(Collections.newList(elements).size()); } public static <T> boolean contains(T[] elements, T element) { return contains(Arrays.asList(elements), element); } public static <T,E> boolean contains(Iterable<T> elements, T element) { return exists(elements, Predicates.equalTo(element)); } public static <T> boolean exists(T[] elements, Apply<T, Boolean> filter) { return exists(Arrays.asList(elements), filter); } public static <T> boolean exists(Iterable<T> elements, Apply<? super T, Boolean> filter) { return !isEmpty(filter(elements, filter)); } public static <T> boolean forAll(T[] elements, Apply<? super T, Boolean> filter) { return forAll(Arrays.asList(elements), filter); } public static <T> boolean forAll(Iterable<T> elements, Apply<? super T, Boolean> filter) { return isEmpty(filter(elements, Predicates.not(filter))); } @SuppressWarnings("unchecked") public static <T> Iterable<T> cons(T element, Iterable<? extends T> elements) { return concat(Arrays.asList(element), elements); } public static <T> Iterable<T> concat(T[] elements1, Iterable<? extends T> elements2) { return concat(Arrays.asList(elements1), elements2); } public static <T> Iterable<T> concat(Iterable<? extends T> elements1, T[] elements2) { return concat(elements1, Arrays.asList(elements2)); } public static <T> Iterable<T> concat(T[] elements1, T[] elements2) { return concat(Arrays.asList(elements1), Arrays.asList(elements2)); } public static <T> Iterable<T> concat(Iterable<? extends T> elements1, Iterable<? extends T> elements2) { return new ConcatenatingIterable<T>(Collections.newList(elements1, elements2)); } public static <T> Iterable<T> concat(final Iterable<? extends T> elements1, final Iterable<? extends T> elements2, final Iterable<? extends T> elements3) { return concat(elements1, concat(elements2, elements3)); } public static <T> Iterable<T> concat(final Iterable<? extends T> elements1, final Iterable<? extends T> elements2, final Iterable<? extends T> elements3, final Iterable<? extends T> elements4) { return concat(elements1, concat(elements2, elements3, elements4)); } public static <T> Iterable<T> concat(final Iterable<? extends T> elements1, final Iterable<? extends T> elements2, final Iterable<? extends T> elements3, final Iterable<? extends T> elements4, final Iterable<? extends T> elements5, final Iterable<? extends T>... rest) { return concat(elements1, concat(elements2, concat(elements3, elements4, elements5, flatten(rest)))); } public static <T extends Comparable<T>> Iterable<T> sort(final T[] elements) { return sort(Arrays.asList(elements)); } public static <T extends Comparable<T>> Iterable<T> sort(final Iterable<T> elements) { if (isEmpty(elements)) { return newSet(); } return sort(elements, Ordering.Natural()); } public static <T> Iterable<T> sort(T[] elements, Comparator<? super T> comparator) { return sort(Arrays.asList(elements), comparator); } public static <T> Iterable<T> sort(final Iterable<T> elements, final Comparator<? super T> comparator) { return new Iterables.SortingIterable<T>(elements, comparator); } public static <T extends SemiGroup<T>> T reduce(T e1) { return e1; } public static <T extends SemiGroup<T>> T reduce(T e1, T e2) { return reduce(newList(e1, e2)).get(); } public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3) { return reduce(newList(e1, e2, e3)).get(); } public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3, T e4) { return reduce(newList(e1, e2, e3, e4)).get(); } public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3, T e4, T... elements) { return reduce(concat(newList(e1, e2, e3, e4), elements)).get(); } public static <T extends SemiGroup<T>> Option<T> reduce(T[] elements) { return reduce(Arrays.asList(elements)); } public static <T extends SemiGroup<T>> Option<T> reduce(Iterable<? extends T> elements) { if (isEmpty(elements)) { return None(); } return fold(elements, head(elements)); } public static <T> T reduce(T[] elements, Monoid<T> m) { return reduce(Arrays.asList(elements), m); } public static <T> T reduce(Iterable<? extends T> elements, Monoid<T> m) { return fold(cons(m.zero(), elements), m).get(); } /** * @return <i>None</i> if <i>elements</i> is empty */ public static <T> Option<T> fold(T[] elements, Apply<Tuple2<T,T>, T> f) { return fold(Arrays.asList(elements), f); } /** * @return <i>None</i> if <i>elements</i> is empty */ public static <T> Option<T> fold(Iterable<? extends T> elements, Apply<Tuple2<T,T>, T> f) { if (isEmpty(elements)) { return None(); } T ret = head(elements); for (T t : drop(elements, 1)) { ret = f.apply(Tuple.of(ret, t)); } return Some(ret); } public static long sum(int e1) { return sum(Arrays.asList(e1)); } public static long sum(int e1, int e2) { return sum(Arrays.asList(e1, e2)); } public static long sum(int e1, int e2, int e3) { return sum(Arrays.asList(e1, e2, e3)); } public static long sum(int e1, int e2, int e3, Integer... rest) { return sum(concat(Arrays.asList(e1, e2, e3), rest)); } public static long sum(Iterable<Integer> elements) { return reduce(map(elements, Transformers.int2long), Monoid.longSum); } public static long product(int e1) { return product(Arrays.asList(e1)); } public static long product(int e1, int e2) { return product(Arrays.asList(e1, e2)); } public static long product(int e1, int e2, int e3) { return product(Arrays.asList(e1, e2, e3)); } public static long product(int e1, int e2, int e3, Integer... rest) { return product(concat(Arrays.asList(e1, e2, e3), rest)); } public static long product(Iterable<Integer> elements) { return reduce(map(elements, Transformers.int2long), Monoid.longProduct); } @SuppressWarnings("unchecked") public static <T extends Comparable<T>> T min(T e1, T... elements) { return min(concat(Arrays.asList(e1), elements)).get(); } public static <T extends Comparable<T>> Option<T> min(Iterable<T> elements) { return headOption(sort(elements)); } @SuppressWarnings("unchecked") public static <T extends Comparable<T>> T max(T e1, T... elements) { return max(concat(Arrays.asList(e1), elements)).get(); } public static <T extends Comparable<T>> Option<T> max(Iterable<T> elements) { return headOption(sort(elements, Ordering.Natural().reverse())); } public static <A,B> Iterable<Tuple2<A, B>> zip(A[] a, B[] b) { return zip(Arrays.asList(a), Arrays.asList(b)); } public static <A,B> Iterable<Tuple2<A, B>> zip(A[] a, Iterable<B> b) { return zip(Arrays.asList(a), b); } public static <A,B> Iterable<Tuple2<A, B>> zip(Iterable<A> a, B[] b) { return zip(a, Arrays.asList(b)); } public static <A,B> Iterable<Tuple2<A, B>> zip(Iterable<A> a, Iterable<B> b) { return new ZippingIterable<A,B>(a, b); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, B[] b, C[] c) { return zip(Arrays.asList(a), Arrays.asList(b), Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, Iterable<B> b, Iterable<C> c) { return zip(Arrays.asList(a), b, c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, B[] b, Iterable<C> c) { return zip(a, Arrays.asList(b), c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, Iterable<B> b, C[] c) { return zip(a, b, Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, B[] b, Iterable<C> c) { return zip(Arrays.asList(a), Arrays.asList(b), c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, B[] b, C[] c) { return zip(a, Arrays.asList(b), Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, Iterable<B> b, C[] c) { return zip(Arrays.asList(a), b, Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, Iterable<B> b, Iterable<C> c) { return map(zip(zip(a, b), c), new Transformer<Tuple2<Tuple2<A, B>, C>, Tuple3<A, B, C>>() { @Override public Tuple3<A, B, C> transform(Tuple2<Tuple2<A, B>, C> source) { return source._1.append(source._2); } }); } public static <A> Iterable<Tuple2<Integer, A>> zipWithIndex(Iterable<A> a) { return new ZippingIterable<Integer,A>(new RangeIterable(0), a); } public static <A> Iterable<Tuple2<Integer, A>> zipWithIndex(A[] a) { return new ZippingIterable<Integer,A>(new RangeIterable(0), Arrays.asList(a)); } public static Iterable<Integer> range(int from) { return new RangeIterable(from); } public static Iterable<Integer> range(int from, int toInclusive) { return new RangeIterable(from, toInclusive); } public static <T> Iterable<T> repeat(T value) { return new RepeatingIterable<T>(value); } public static <T> Iterable<T> repeat(T value, int amount) { return new RepeatingIterable<T>(value, amount); } public static String mkString(Iterable<Character> elements) { return mkString("", map(elements, Transformers.toString)); } public static String mkString(String delim, String[] elements) { return mkString(delim, Arrays.asList(elements)); } public static String mkString(String delim, Iterable<String> elements) { StringBuilder sb = new StringBuilder(); for (String s: elements) { if (sb.length() > 0) { sb.append(delim); } sb.append(s); } return sb.toString(); } public static <T> Iterable<T> reverse(Iterable<T> elements) { return new Iterables.ReversingIterable<T>(elements); } public static <T,R> Iterable<R> sequence(Iterable<? extends Apply<? super T,? extends R>> elements, final T t) { return map(elements, new Transformer<Apply<? super T,? extends R>, R>() { @Override public R transform(Apply<? super T,? extends R> source) { return source.apply(t); } }); } private static final String LINE_SEP = System.getProperty("line.separator"); public static final String unlines(Iterable<String> elements) { return mkString(LINE_SEP, elements); } @SuppressWarnings("unchecked") public static <T> Set<T> union(Set<T> e1, Set<T> e2) { return reduce(newList(e1, e2), (Monoid<Set<T>>)(Object)Monoid.setUnion); } @SuppressWarnings("unchecked") public static <T> Set<T> union(Set<T> e1, Set<T> e2, Set<T>... e) { return reduce(concat(newList(e1, e2), e), (Monoid<Set<T>>)(Object)Monoid.setUnion); } @SuppressWarnings("unchecked") public static <T> Set<T> intersection(Set<T> e1, Set<T> e2) { return reduce(newList(e1, e2), (Monoid<Set<T>>)(Object)Monoid.setIntersection); } @SuppressWarnings("unchecked") public static <T> Set<T> intersection(Set<T> e1, Set<T> e2, Set<T>... e) { return reduce(concat(newList(e1, e2), e), (Monoid<Set<T>>)(Object)Monoid.setIntersection); } }
package foodtruck.geolocation; import java.util.logging.Level; import java.util.logging.Logger; import com.google.inject.Inject; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import foodtruck.model.Location; import foodtruck.util.ServiceException; /** * A Geolocator instance that uses Yahoo's PlaceFinder service. * @author aviolette@gmail.com * @since 10/16/11 */ public class YahooGeolocator implements GeoLocator { private static final Logger log = Logger.getLogger(YahooGeolocator.class.getName()); private final YahooResource yahooResource; @Inject public YahooGeolocator(YahooResource yahooResource) { this.yahooResource = yahooResource; } @Override public Location locate(String location, GeolocationGranularity granularity) { try { JSONObject obj = yahooResource.findLocation(location); log.log(Level.INFO, "Geolocation result for {0}: \n{1}", new Object[] {location, obj.toString()}); JSONObject resultSet = obj.getJSONObject("ResultSet"); if (resultSet.getInt("Found") == 0) { return null; } if (resultSet.getInt("Quality") < 40) { log.log(Level.INFO, "Result Set was too broad"); return null; } JSONArray results = resultSet.getJSONArray("Results"); JSONObject result = results.getJSONObject(0); if (result.getInt("quality") < 40) { log.log(Level.INFO, "Result was too broad"); return null; } return new Location(Double.parseDouble(result.getString("latitude")), Double.parseDouble(result.getString("longitude")), location); } catch (JSONException e) { log.log(Level.WARNING, e.getMessage(), e); } catch (ServiceException e) { log.log(Level.WARNING, e.getMessage(), e); } return null; } }
package galaxyspace.core.hooks; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import asmodeuscore.api.dimension.IAdvancedSpace; import galaxyspace.core.events.SetBlockEvent; import galaxyspace.core.hooklib.asm.Hook; import galaxyspace.core.hooklib.asm.ReturnCondition; import galaxyspace.systems.SolarSystem.planets.overworld.items.ItemBasicGS.BasicItems; import micdoodle8.mods.galacticraft.api.GalacticraftRegistry; import micdoodle8.mods.galacticraft.api.item.IItemThermal; import micdoodle8.mods.galacticraft.api.world.EnumAtmosphericGas; import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider; import micdoodle8.mods.galacticraft.core.GCItems; import micdoodle8.mods.galacticraft.core.GalacticraftCore; import micdoodle8.mods.galacticraft.core.entities.EntityAlienVillager; import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerHandler; import micdoodle8.mods.galacticraft.core.entities.player.GCPlayerStats; import micdoodle8.mods.galacticraft.core.items.ItemBasic; import micdoodle8.mods.galacticraft.core.items.ItemCanisterGeneric; import micdoodle8.mods.galacticraft.core.network.PacketSimple; import micdoodle8.mods.galacticraft.core.network.PacketSimple.EnumSimplePacket; import micdoodle8.mods.galacticraft.core.util.CompatibilityManager; import micdoodle8.mods.galacticraft.core.util.DamageSourceGC; import micdoodle8.mods.galacticraft.core.util.GCCoreUtil; import micdoodle8.mods.galacticraft.core.util.OxygenUtil; import micdoodle8.mods.galacticraft.planets.mars.entities.EntityCreeperBoss; import micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityGasLiquefier; import micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityMethaneSynthesizer; import micdoodle8.mods.galacticraft.planets.venus.dimension.WorldProviderVenus; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.MobEffects; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.relauncher.ReflectionHelper; public class GSHooksManager { @Hook(returnCondition = ReturnCondition.ON_TRUE, booleanReturnConstant = false) public static boolean setBlockState(World world, BlockPos pos, IBlockState newState, int flags) { return MinecraftForge.EVENT_BUS.post(new SetBlockEvent(world, pos, newState, flags)); } @Hook(returnCondition = ReturnCondition.ALWAYS) public static int getAirProducts(TileEntityMethaneSynthesizer te) { WorldProvider WP = te.getWorld().provider; if (WP instanceof IGalacticraftWorldProvider) { ArrayList<EnumAtmosphericGas> atmos = ((IGalacticraftWorldProvider) WP).getCelestialBody().atmosphere.composition; if (atmos.size() > 0) { if (atmos.get(0) == EnumAtmosphericGas.CO2) { return 1; } } if (atmos.size() > 1) { if (atmos.get(1) == EnumAtmosphericGas.CO2) { return 1; } } if (atmos.size() > 2) { if (atmos.get(2) == EnumAtmosphericGas.CO2) { return 1; } } return 0; } return 0; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static int getAirProducts(TileEntityGasLiquefier te) { WorldProvider WP = te.getWorld().provider; if (WP instanceof IGalacticraftWorldProvider) { int result = 0; ArrayList<EnumAtmosphericGas> atmos = ((IGalacticraftWorldProvider) WP) .getCelestialBody().atmosphere.composition; if (atmos.size() > 0) { result = te.getIdFromName(atmos.get(0).name().toLowerCase()) + 1; } if (atmos.size() > 1) { result += 16 * (te.getIdFromName(atmos.get(1).name().toLowerCase()) + 1); } if (atmos.size() > 2) { result += 256 * (te.getIdFromName(atmos.get(2).name().toLowerCase()) + 1); } return result; } return 35; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static void checkThermalStatus(GCPlayerHandler handler, EntityPlayerMP player, GCPlayerStats playerStats) { if (player.world.provider instanceof IGalacticraftWorldProvider && !player.capabilities.isCreativeMode && !CompatibilityManager.isAndroid(player)) { final ItemStack thermalPaddingHelm = playerStats.getExtendedInventory().getStackInSlot(6); final ItemStack thermalPaddingChestplate = playerStats.getExtendedInventory().getStackInSlot(7); final ItemStack thermalPaddingLeggings = playerStats.getExtendedInventory().getStackInSlot(8); final ItemStack thermalPaddingBoots = playerStats.getExtendedInventory().getStackInSlot(9); float lowestThermalStrength = 0.0F; if (!thermalPaddingHelm.isEmpty() && !thermalPaddingChestplate.isEmpty() && !thermalPaddingLeggings.isEmpty() && !thermalPaddingBoots.isEmpty()) { if (thermalPaddingHelm.getItem() instanceof IItemThermal) { lowestThermalStrength += ((IItemThermal) thermalPaddingHelm.getItem()).getThermalStrength(); } if (thermalPaddingChestplate.getItem() instanceof IItemThermal) { lowestThermalStrength += ((IItemThermal) thermalPaddingChestplate.getItem()).getThermalStrength(); } if (thermalPaddingLeggings.getItem() instanceof IItemThermal) { lowestThermalStrength += ((IItemThermal) thermalPaddingLeggings.getItem()).getThermalStrength(); } if (thermalPaddingBoots.getItem() instanceof IItemThermal) { lowestThermalStrength += ((IItemThermal) thermalPaddingBoots.getItem()).getThermalStrength(); } lowestThermalStrength /= 4.0F; lowestThermalStrength = Math.abs(lowestThermalStrength); //It shouldn't be negative, but just in case! } IGalacticraftWorldProvider provider = (IGalacticraftWorldProvider) player.world.provider; float thermalLevelMod = provider.getThermalLevelModifier(); if(player.world.provider instanceof IAdvancedSpace) { provider = (IAdvancedSpace) player.world.provider; thermalLevelMod = ((IAdvancedSpace)provider).getThermalLevelModifier(player); } //System.out.println(thermalLevelMod); float absThermalLevelMod = Math.abs(thermalLevelMod); if (absThermalLevelMod > 0D) { int thermalLevelCooldownBase = Math.abs(MathHelper.floor(200 / thermalLevelMod)); int normaliseCooldown = MathHelper.floor(150 / lowestThermalStrength); int thermalLevelTickCooldown = thermalLevelCooldownBase; if (thermalLevelTickCooldown < 1) { thermalLevelTickCooldown = 1; //Prevent divide by zero errors } if (!thermalPaddingHelm.isEmpty() && !thermalPaddingChestplate.isEmpty() && !thermalPaddingLeggings.isEmpty() && !thermalPaddingBoots.isEmpty()) { //If the thermal strength exceeds the dimension's thermal level mod, it can't improve the normalise //This factor of 1.5F is chosen so that a combination of Tier 1 and Tier 2 thermal isn't enough to normalise on Venus (three Tier 2, one Tier 1 stays roughly constant) float relativeFactor = Math.max(1.0F, absThermalLevelMod / lowestThermalStrength) / 1.5F; normaliseCooldown = MathHelper.floor(normaliseCooldown / absThermalLevelMod * relativeFactor); if (normaliseCooldown < 1) { normaliseCooldown = 1; //Prevent divide by zero errors } // Player is wearing all required thermal padding items if ((player.ticksExisted - 1) % normaliseCooldown == 0) { handler.normaliseThermalLevel(player, playerStats, 1); } thermalLevelMod /= Math.max(1.0F, lowestThermalStrength / 2.0F); absThermalLevelMod = Math.abs(thermalLevelMod); } if (OxygenUtil.isAABBInBreathableAirBlock(player, true)) { playerStats.setThermalLevelNormalising(true); handler.normaliseThermalLevel(player, playerStats, 1); // If player is in ambient thermal area, slowly reset to normal return; } // For each piece of thermal equipment being used, slow down the the harmful thermal change slightly if (!thermalPaddingHelm.isEmpty()) { thermalLevelTickCooldown += thermalLevelCooldownBase; } if (!thermalPaddingChestplate.isEmpty()) { thermalLevelTickCooldown += thermalLevelCooldownBase; } if (!thermalPaddingLeggings.isEmpty()) { thermalLevelTickCooldown += thermalLevelCooldownBase; } if (!thermalPaddingBoots.isEmpty()) { thermalLevelTickCooldown += thermalLevelCooldownBase; } // Instead of increasing/decreasing the thermal level by a large amount every ~200 ticks, increase/decrease // by a small amount each time (still the same average increase/decrease) int thermalLevelTickCooldownSingle = MathHelper.floor(thermalLevelTickCooldown / absThermalLevelMod); if (thermalLevelTickCooldownSingle < 1) { thermalLevelTickCooldownSingle = 1; //Prevent divide by zero errors } if ((player.ticksExisted - 1) % thermalLevelTickCooldownSingle == 0) { int last = playerStats.getThermalLevel(); playerStats.setThermalLevel((int) Math.min(Math.max(last + (thermalLevelMod < 0 ? -1 : 1), -22), 22)); if (playerStats.getThermalLevel() != last) { //handler.sendThermalLevelPacket(player, playerStats); GalacticraftCore.packetPipeline.sendTo(new PacketSimple(EnumSimplePacket.C_UPDATE_THERMAL_LEVEL, GCCoreUtil.getDimensionID(player.world), new Object[] { playerStats.getThermalLevel(), playerStats.isThermalLevelNormalising() }), player); } } // If the normalisation is outpacing the freeze/overheat playerStats.setThermalLevelNormalising(thermalLevelTickCooldownSingle > normaliseCooldown && !thermalPaddingHelm.isEmpty() && !thermalPaddingChestplate.isEmpty() && !thermalPaddingLeggings.isEmpty() && !thermalPaddingBoots.isEmpty()); if (!playerStats.isThermalLevelNormalising()) { if ((player.ticksExisted - 1) % thermalLevelTickCooldown == 0) { if (Math.abs(playerStats.getThermalLevel()) >= 22) { player.attackEntityFrom(DamageSourceGC.thermal, 1.5F); } } if (playerStats.getThermalLevel() < -15) { player.addPotionEffect(new PotionEffect(MobEffects.SLOWNESS, 5, 2, true, true)); } if (playerStats.getThermalLevel() > 15) { player.addPotionEffect(new PotionEffect(MobEffects.NAUSEA, 5, 2, true, true)); } } } else //Normalise thermal level if on Space Station or non-modifier planet { playerStats.setThermalLevelNormalising(true); handler.normaliseThermalLevel(player, playerStats, 2); } } else //Normalise thermal level if on Overworld or any non-GC dimension { playerStats.setThermalLevelNormalising(true); handler.normaliseThermalLevel(player, playerStats, 3); } } @Hook(returnCondition = ReturnCondition.ALWAYS) public static double getSolarEnergyMultiplier(WorldProviderVenus wp) { return 0; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static ItemStack getGuaranteedLoot(EntityCreeperBoss creeper, Random rand) { List<ItemStack> stackList = new LinkedList<>(); stackList.addAll(GalacticraftRegistry.getDungeonLoot(2)); return stackList.get(rand.nextInt(stackList.size())).copy(); } /* private static List<BlockPos> connectedPads = new ArrayList<BlockPos>(); private static Ticket chunkLoadTicket; @Hook(injectOnLine=88) public static void update(TileEntityLaunchController te) { if (!te.getWorld().isRemote) { te.controlEnabled = te.launchSchedulingEnabled && te.hasEnoughEnergyToRun && !te.getDisabled(0); boolean frequencyCheckNeeded = ReflectionHelper.getPrivateValue(TileEntityLaunchController.class, te, "frequencyCheckNeeded"); if (frequencyCheckNeeded) { te.checkDestFrequencyValid(); frequencyCheckNeeded = false; } ReflectionHelper.setPrivateValue(TileEntityLaunchController.class, te, frequencyCheckNeeded, "frequencyCheckNeeded"); if (te.requiresClientUpdate) { // PacketDispatcher.sendPacketToAllPlayers(this.getPacket()); // TODO te.requiresClientUpdate = false; } if (te.ticks % 40 == 0) { te.setFrequency(te.frequency); te.setDestinationFrequency(te.destFrequency); //System.out.println(te.attachedDock); } //Ticket chunkLoadTicket = ReflectionHelper.getPrivateValue(TileEntityLaunchController.class, te, "chunkLoadTicket"); //List<BlockPos> connectedPads = ReflectionHelper.getPrivateValue(TileEntityLaunchController.class, te, "connectedPads"); if (te.ticks % 20 == 0) { if (chunkLoadTicket != null) { for (int i = 0; i < connectedPads.size(); i++) { BlockPos coords = connectedPads.get(i); Block block = te.getWorld().getBlockState(coords).getBlock(); TileEntity tile = te.getWorld().getTileEntity(coords); if (!(tile instanceof IFuelDock)) { connectedPads.remove(i); //ReflectionHelper.setPrivateValue(TileEntityLaunchController.class, te, connectedPads, "connectedPads"); ForgeChunkManager.unforceChunk(chunkLoadTicket, new ChunkPos(coords.getX() >> 4, coords.getZ() >> 4)); } } } } } else { if (te.frequency == -1 && te.destFrequency == -1) { GalacticraftCore.packetPipeline.sendToServer(new PacketSimpleMars(EnumSimplePacketMars.S_UPDATE_ADVANCED_GUI, GCCoreUtil.getDimensionID(te.getWorld()), new Object[] { 5, te.getPos(), 0 })); } } return; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static void onTicketLoaded(TileEntityLaunchController te, Ticket ticket, boolean placed) { if (!te.getWorld().isRemote && ConfigManagerMars.launchControllerChunkLoad) { if (ticket == null) { return; } if (chunkLoadTicket == null) { chunkLoadTicket = ticket; } NBTTagCompound nbt = chunkLoadTicket.getModData(); nbt.setInteger("ChunkLoaderTileX", te.getPos().getX()); nbt.setInteger("ChunkLoaderTileY", te.getPos().getY()); nbt.setInteger("ChunkLoaderTileZ", te.getPos().getZ()); //List<BlockPos> connectedPads = ReflectionHelper.getPrivateValue(TileEntityLaunchController.class, te, "connectedPads"); for (int x = -3; x <= 3; x++) { for (int z = -3; z <= 3; z++) { TileEntity tile = te.getWorld().getTileEntity(te.getPos().add(x, 0, z)); Block blockID = te.getWorld().getBlockState(te.getPos().add(x, 0, z)).getBlock(); if (tile instanceof IFuelDock) { if (te.getPos().getX() + x >> 4 != te.getPos().getX() >> 4 || te.getPos().getZ() + z >> 4 != te.getPos().getZ() >> 4) { connectedPads.add(new BlockPos(te.getPos().getX() + x, te.getPos().getY(), te.getPos().getZ() + z)); //ReflectionHelper.setPrivateValue(TileEntityLaunchController.class, te, connectedPads, "connectedPads"); if (placed) { ChunkLoadingCallback.forceChunk(chunkLoadTicket, te.getWorld(), te.getPos().getX() + x, te.getPos().getY(), te.getPos().getZ() + z, te.getOwnerName()); } else { ChunkLoadingCallback.addToList(te.getWorld(), te.getPos().getX(), te.getPos().getY(), te.getPos().getZ(), te.getOwnerName()); } } } } } ChunkLoadingCallback.forceChunk(chunkLoadTicket, te.getWorld(), te.getPos().getX(), te.getPos().getY(), te.getPos().getZ(), te.getOwnerName()); } } @Hook(returnCondition = ReturnCondition.ALWAYS) public static boolean canAttachToLandingPad(TileEntityLaunchController te, IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); //GalaxySpace.instance.debug(tile); return tile instanceof IFuelDock; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static void updateRocketOnDockSettings(TileEntityLaunchController te) { if (te.attachedDock instanceof IFuelDock) { IFuelDock pad = ((IFuelDock) te.attachedDock); IDockable rocket = pad.getDockedEntity(); if (rocket instanceof EntityAutoRocket) { ((EntityAutoRocket) rocket).updateControllerSettings(pad); } } } @Hook(returnCondition = ReturnCondition.ALWAYS) public static boolean setTarget(EntityAutoRocket rocket, boolean doSet, int destFreq) { Class<?> controllerClass = ReflectionHelper.getPrivateValue(EntityAutoRocket.class, rocket, "controllerClass"); WorldServer[] servers = GCCoreUtil.getWorldServerList(rocket.world); if (!GalacticraftCore.isPlanetsLoaded || controllerClass == null) { return false; } for (int i = 0; i < servers.length; i++) { WorldServer world = servers[i]; try { for (TileEntity tile : new ArrayList<TileEntity>(world.loadedTileEntityList)) { if (!controllerClass.isInstance(tile)) continue; tile = world.getTileEntity(tile.getPos()); if (!controllerClass.isInstance(tile)) continue; int controllerFrequency = controllerClass.getField("frequency").getInt(tile); if (destFreq == controllerFrequency) { boolean targetSet = false; blockLoop: for (int x = -3; x <= 4; x++) { for (int z = -3; z <= 4; z++) { BlockPos pos = new BlockPos(tile.getPos().add(x, 0, z)); Block block = world.getBlockState(pos).getBlock(); TileEntity tileen = world.getTileEntity(pos); //if (block instanceof BlockLandingPadFull) if (tileen instanceof IFuelDock) { System.out.println(block); if (doSet) { rocket.targetVec = pos; } targetSet = true; break blockLoop; } } } if (doSet) { rocket.targetDimension = tile.getWorld().provider.getDimension(); } if (!targetSet) { if (doSet) { rocket.targetVec = null; } return false; } else { return true; } } } } catch (Exception e) { e.printStackTrace(); } } return false; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static boolean setFrequency(EntityAutoRocket rocket) { Class<?> controllerClass = ReflectionHelper.getPrivateValue(EntityAutoRocket.class, rocket, "controllerClass"); BlockVec3 activeLaunchController = ReflectionHelper.getPrivateValue(EntityAutoRocket.class, rocket, "activeLaunchController"); if (!GalacticraftCore.isPlanetsLoaded || controllerClass == null) { return false; } if (activeLaunchController != null) { TileEntity launchController = activeLaunchController.getTileEntity(rocket.world); if (controllerClass.isInstance(launchController)) { try { Boolean b = (Boolean) controllerClass.getMethod("validFrequency").invoke(launchController); if (b != null && b) { int controllerFrequency = controllerClass.getField("destFrequency").getInt(launchController); boolean foundPad = setTarget(rocket, false, controllerFrequency); if (foundPad) { rocket.destinationFrequency = controllerFrequency; GCLog.debug("Rocket under launch control: going to target frequency " + controllerFrequency); return true; } } } catch (Exception e) { e.printStackTrace(); } } } rocket.destinationFrequency = -1; return false; } */ private static final EntityAlienVillager.ITradeList[] DEFAULT_TRADE_LIST_MAP = new EntityAlienVillager.ITradeList[] { new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.schematic, 1, 1), new EntityAlienVillager.PriceInfo(40, 55), BasicItems.SCHEMATIC_BOX.getItemStack()), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.oxMask, 1, 0), new EntityAlienVillager.PriceInfo(1, 2)), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.oxTankLight, 1, 235), new EntityAlienVillager.PriceInfo(3, 4)), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.oxygenGear, 1, 0), new EntityAlienVillager.PriceInfo(3, 4)), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.fuelCanister, 1, 317), new EntityAlienVillager.PriceInfo(3, 4)), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.parachute, 1, 0), new EntityAlienVillager.PriceInfo(1, 2)), new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.battery, 1, 58), new EntityAlienVillager.PriceInfo(2, 4)), new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.oilCanister, 1, ItemCanisterGeneric.EMPTY), new EntityAlienVillager.PriceInfo(1, 1), new ItemStack(GCItems.foodItem, 1, 1)), //carrots = also yields a tin! new EntityAlienVillager.ListItemForEmeralds(new ItemStack(GCItems.basicItem, 1, ItemBasic.WAFER_BASIC), new EntityAlienVillager.PriceInfo(3, 4)), new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.schematic, 1, 0), new EntityAlienVillager.PriceInfo(3, 5), new ItemStack(GCItems.schematic, 1, 1)), //Exchange buggy and rocket schematics new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.schematic, 1, 1), new EntityAlienVillager.PriceInfo(3, 5), new ItemStack(GCItems.schematic, 1, 0)), //Exchange buggy and rocket schematics new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.basicItem, 2, 3), new EntityAlienVillager.PriceInfo(1, 1), new ItemStack(GCItems.basicItem, 1, 6)), //Compressed Tin - needed to craft a Fuel Loader new EntityAlienVillager.ItemAndEmeraldToItem(new ItemStack(GCItems.basicItem, 2, 4), new EntityAlienVillager.PriceInfo(1, 1), new ItemStack(GCItems.basicItem, 1, 7)), //Compressed Copper - needed to craft a Fuel Loader new EntityAlienVillager.EmeraldForItems(new ItemStack(Blocks.SAPLING, 1, 3), new EntityAlienVillager.PriceInfo(11, 39)) //The one thing Alien Villagers don't have and can't get is jungle trees... }; @Hook(returnCondition = ReturnCondition.ALWAYS) public static void populateBuyingList(EntityAlienVillager e) { MerchantRecipeList buyingList = ReflectionHelper.getPrivateValue(EntityAlienVillager.class, e, "buyingList"); if (buyingList == null) { buyingList = new MerchantRecipeList(); } for (EntityAlienVillager.ITradeList tradeList : DEFAULT_TRADE_LIST_MAP) { tradeList.modifyMerchantRecipeList(buyingList, e.getEntityWorld().rand); } ReflectionHelper.setPrivateValue(EntityAlienVillager.class, e, buyingList, "buyingList"); } }
package galaxyspace.core.hooks; import java.util.ArrayList; import galaxyspace.core.events.SetBlockEvent; import galaxyspace.core.hooklib.asm.Hook; import galaxyspace.core.hooklib.asm.ReturnCondition; import micdoodle8.mods.galacticraft.api.prefab.world.gen.WorldProviderSpace; import micdoodle8.mods.galacticraft.api.world.EnumAtmosphericGas; import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider; import micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityGasLiquefier; import micdoodle8.mods.galacticraft.planets.mars.tile.TileEntityMethaneSynthesizer; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import net.minecraftforge.common.MinecraftForge; public class GSHooksManager { @Hook(returnCondition = ReturnCondition.ON_TRUE, booleanReturnConstant = false) public static boolean setBlockState(World world, BlockPos pos, IBlockState newState, int flags) { return MinecraftForge.EVENT_BUS.post(new SetBlockEvent(world, pos, newState, flags)); } @Hook(returnCondition = ReturnCondition.ALWAYS) public static int getAirProducts(TileEntityMethaneSynthesizer te) { WorldProvider WP = te.getWorld().provider; if (WP instanceof IGalacticraftWorldProvider) { ArrayList<EnumAtmosphericGas> atmos = ((IGalacticraftWorldProvider) WP).getCelestialBody().atmosphere.composition; if (atmos.size() > 0) { if (atmos.get(0) == EnumAtmosphericGas.CO2) { return 1; } } if (atmos.size() > 1) { if (atmos.get(1) == EnumAtmosphericGas.CO2) { return 1; } } if (atmos.size() > 2) { if (atmos.get(2) == EnumAtmosphericGas.CO2) { return 1; } } return 0; } return 0; } @Hook(returnCondition = ReturnCondition.ALWAYS) public static int getAirProducts(TileEntityGasLiquefier te) { WorldProvider WP = te.getWorld().provider; if (WP instanceof IGalacticraftWorldProvider) { int result = 0; ArrayList<EnumAtmosphericGas> atmos = ((IGalacticraftWorldProvider) WP) .getCelestialBody().atmosphere.composition; if (atmos.size() > 0) { result = te.getIdFromName(atmos.get(0).name().toLowerCase()) + 1; } if (atmos.size() > 1) { result += 16 * (te.getIdFromName(atmos.get(1).name().toLowerCase()) + 1); } if (atmos.size() > 2) { result += 256 * (te.getIdFromName(atmos.get(2).name().toLowerCase()) + 1); } return result; } return 35; } /* @Hook(returnCondition = ReturnCondition.ALWAYS) public static void updateLightmap(float partialTicks) { if(lightmapUpdateNeeded) { } }*/ }
package hudson.plugins.promoted_builds; import hudson.EnvVars; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Cause.UserCause; import hudson.model.Result; import hudson.util.Iterators; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import java.util.List; import java.util.concurrent.Future; import java.util.logging.Logger; import jenkins.model.Jenkins; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; /** * Promotion status of a build wrt a specific {@link PromotionProcess}. * * @author Kohsuke Kawaguchi * @see PromotedBuildAction#statuses */ @ExportedBean public final class Status { /** * Matches with {@link PromotionProcess#name}. */ public final String name; private final PromotionBadge[] badges; /** * When did the build qualify for a promotion? */ public final Calendar timestamp = new GregorianCalendar(); /** * If the build is successfully promoted, the build number of {@link Promotion} * that represents that record. * * -1 to indicate that the promotion was not successful yet. */ private int promotion = -1; /** * Bulid numbers of {@link Promotion}s that are attempted. * If {@link Promotion} fails, this field can have multiple values. * Sorted in the ascending order. */ private List<Integer> promotionAttempts = new ArrayList<Integer>(); /*package*/ transient PromotedBuildAction parent; public Status(PromotionProcess process, Collection<? extends PromotionBadge> badges) { this.name = process.getName(); this.badges = badges.toArray(new PromotionBadge[badges.size()]); } @Exported public String getName() { return name; } /** * Gets the parent {@link Status} that owns this object. */ public PromotedBuildAction getParent() { return parent; } /** * Gets the {@link PromotionProcess} that this object deals with. */ @Exported public PromotionProcess getProcess() { assert parent != null : name; AbstractProject<?,?> project = parent.getProject(); assert project != null : parent; JobPropertyImpl jp = project.getProperty(JobPropertyImpl.class); if(jp==null) return null; return jp.getItem(name); } /** * Gets the icon that should represent this promotion (that is potentially attempted but failed.) */ public String getIcon(String size) { String baseName; PromotionProcess p = getProcess(); if (p == null) { // promotion process undefined (perhaps deleted?). fallback to the default icon baseName = "star-gold"; } else { Promotion l = getLast(); if (l!=null && l.getResult()!= Result.SUCCESS) return Jenkins.RESOURCE_PATH+"/images/"+size+"/error.png"; baseName = p.getIcon(); } return Jenkins.RESOURCE_PATH+"/plugin/promoted-builds/icons/"+size+"/"+ baseName +".png"; } /** * Gets the build that was qualified for a promotion. */ public AbstractBuild<?,?> getTarget() { return getParent().owner; } /** * Called by {@link Promotion} to allow status to contribute environment variables. * * @param build * The calling build. Never null. * @param env * Environment variables should be added to this map. */ public void buildEnvVars(AbstractBuild<?,?> build, EnvVars env) { for (PromotionBadge badge : badges) { badge.buildEnvVars(build, env); } } /** * Gets the string that says how long since this promotion had happened. * * @return * string like "3 minutes" "1 day" etc. */ public String getTimestampString() { long duration = new GregorianCalendar().getTimeInMillis()-timestamp.getTimeInMillis(); return Util.getTimeSpanString(duration); } /** * Gets the string that says how long did it toook for this build to be promoted. */ public String getDelayString(AbstractBuild<?,?> owner) { long duration = timestamp.getTimeInMillis() - owner.getTimestamp().getTimeInMillis() - owner.getDuration(); return Util.getTimeSpanString(duration); } public boolean isFor(PromotionProcess process) { return process.getName().equals(this.name); } /** * Returns the {@link Promotion} object that represents the successful promotion. * * @return * null if the promotion has never been successful, or if it was but * the record is already lost. */ public Promotion getSuccessfulPromotion(JobPropertyImpl jp) { if(promotion>=0) { PromotionProcess p = jp.getItem(name); if(p!=null) return p.getBuildByNumber(promotion); } return null; } /** * Returns true if the promotion was successfully completed. */ public boolean isPromotionSuccessful() { return promotion>=0; } /** * Returns true if at least one {@link Promotion} activity is attempted. * False if none is executed yet (this includes the case where it's in the queue.) */ public boolean isPromotionAttempted() { return !promotionAttempts.isEmpty(); } /** * Returns true if the promotion for this is pending in the queue, * waiting to be executed. */ public boolean isInQueue() { PromotionProcess p = getProcess(); return p!=null && p.isInQueue(getTarget()); } /** * Gets the badges indicating how did a build qualify for a promotion. */ @Exported public List<PromotionBadge> getBadges() { return Arrays.asList(badges); } /** * Called when a new promotion attempts for this build starts. */ /*package*/ void addPromotionAttempt(Promotion p) { promotionAttempts.add(p.getNumber()); } /** * Called when a promotion succeeds. */ /*package*/ void onSuccessfulPromotion(Promotion p) { promotion = p.getNumber(); } // web bound methods /** * Gets the last successful {@link Promotion}. */ public Promotion getLastSuccessful() { PromotionProcess p = getProcess(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if(b!=null && b.getResult()== Result.SUCCESS) return b; } return null; } /** * Gets the last successful {@link Promotion}. */ public Promotion getLastFailed() { PromotionProcess p = getProcess(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if(b!=null && b.getResult()!=Result.SUCCESS) return b; } return null; } public Promotion getLast() { PromotionProcess p = getProcess(); for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if(b!=null) return b; } return null; } /** * Gets all the promotion builds. */ @Exported public List<Promotion> getPromotionBuilds() { List<Promotion> builds = new ArrayList<Promotion>(); PromotionProcess p = getProcess(); if (p!=null) { for( Integer n : Iterators.reverse(promotionAttempts) ) { Promotion b = p.getBuildByNumber(n); if (b != null) { builds.add(b); } } } return builds; } /** * Gets the promotion build by build number. * * @param number build number * @return promotion build */ public Promotion getPromotionBuild(int number) { PromotionProcess p = getProcess(); return p.getBuildByNumber(number); } /** * Schedules a new build. */ public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(!getTarget().hasPermission(Promotion.PROMOTE)) return; Future<Promotion> f = getProcess().scheduleBuild2(getTarget(), new UserCause()); if (f==null) LOGGER.warning("Failing to schedule the promotion of "+getTarget()); // TODO: we need better visual feed back so that the user knows that the build happened. rsp.forwardToPreviousPage(req); } private static final Logger LOGGER = Logger.getLogger(Status.class.getName()); }
package info.loenwind.travelhut.config; import java.nio.charset.Charset; import javax.annotation.Nonnull; import info.loenwind.travelhut.TravelHutMod; import io.netty.buffer.ByteBuf; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; public enum Config { // section, defaultValue, description, requiresWorldRestart, requiresGameRestart enableTravelHuts(Section.SERVER, true, "Enable the generation of travel huts.", false, false), generationDistance(Section.SERVER, 20, "The distance between huts (in chunks).", false, false), travellingChecksInBetween(Section.SERVER, false, "When travelling, check chunks where no huts are generated, too. Enable this after changing the generation distance.", false, false), generateBedrock(Section.SERVER, true, "Should travel hut floors generate as bedrock? If false, they will be obsidian. (Note: Bedrock huts and obsidian huts are not compatible with each other.)", false, false), chanceFloatingIsland(Section.SERVER, 0.05, "Chance that ocean huts will float instead of being submerged (0.0-1.0.)", false, false), chanceTowers(Section.SERVER, 0.025, "Chance that huts will generate as a tower instead of being on the floor (0.0-1.0).", false, false); // Nothing to see beyond this point. End of configuration values. @Nonnull private final Section section; @Nonnull private final Object defaultValue; @Nonnull private final String description; @Nonnull private Object currentValue; private final boolean requiresWorldRestart; private final boolean requiresGameRestart; private Config(@Nonnull Section section, @Nonnull Object defaultValue, @Nonnull String description, boolean requiresWorldRestart, boolean requiresGameRestart) { this.section = section; this.description = description; this.currentValue = this.defaultValue = defaultValue; this.requiresWorldRestart = requiresWorldRestart; this.requiresGameRestart = requiresGameRestart; } private Config(@Nonnull Section section, @Nonnull Integer defaultValue, @Nonnull String description, boolean requiresWorldRestart, boolean requiresGameRestart) { this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart); } private Config(@Nonnull Section section, @Nonnull Double defaultValue, @Nonnull String description, boolean requiresWorldRestart, boolean requiresGameRestart) { this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart); } private Config(@Nonnull Section section, @Nonnull Boolean defaultValue, @Nonnull String description, boolean requiresWorldRestart, boolean requiresGameRestart) { this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart); } private Config(@Nonnull Section section, @Nonnull String defaultValue, @Nonnull String description, boolean requiresWorldRestart, boolean requiresGameRestart) { this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart); } private Config(@Nonnull Section section, @Nonnull Integer defaultValue, @Nonnull String description) { this(section, (Object) defaultValue, description, false, false); } private Config(@Nonnull Section section, @Nonnull Double defaultValue, @Nonnull String description) { this(section, (Object) defaultValue, description, false, false); } private Config(@Nonnull Section section, @Nonnull Boolean defaultValue, @Nonnull String description) { this(section, (Object) defaultValue, description, false, false); } private Config(@Nonnull Section section, @Nonnull String defaultValue, @Nonnull String description) { this(section, (Object) defaultValue, description, false, false); } void load(Configuration config) { Object value = null; if (defaultValue instanceof Integer) { value = setPropertyData(config.get(section.name, name(), (Integer) defaultValue, description)).getInt((Integer) defaultValue); } else if (defaultValue instanceof Double) { value = setPropertyData(config.get(section.name, name(), (Double) defaultValue, description)).getDouble((Double) defaultValue); } else if (defaultValue instanceof Boolean) { value = setPropertyData(config.get(section.name, name(), (Boolean) defaultValue, description)).getBoolean((Boolean) defaultValue); } else if (defaultValue instanceof String) { value = setPropertyData(config.get(section.name, name(), (String) defaultValue, description)).getString(); } setField(value); } private Property setPropertyData(final Property property) { property.setRequiresWorldRestart(requiresWorldRestart); property.setRequiresMcRestart(requiresGameRestart); property.setLanguageKey(TravelHutMod.MODID + ".config." + name()); return property; } private void setField(Object value) { if (value != null) { currentValue = value; } } void store(ByteBuf buf) { if (defaultValue instanceof Integer) { buf.writeInt(getInt()); } else if (defaultValue instanceof Double) { buf.writeDouble(getDouble()); } else if (defaultValue instanceof Boolean) { buf.writeBoolean(getBoolean()); } else if (defaultValue instanceof String) { String value = getString(); byte[] bytes = value.getBytes(Charset.forName("UTF-8")); buf.writeInt(bytes.length); buf.writeBytes(bytes); } } void read(ByteBuf buf) { Object value = null; if (defaultValue instanceof Integer) { value = buf.readInt(); } else if (defaultValue instanceof Double) { value = buf.readDouble(); } else if (defaultValue instanceof Boolean) { value = buf.readBoolean(); } else if (defaultValue instanceof String) { int len = buf.readInt(); byte[] bytes = new byte[len]; buf.readBytes(bytes, 0, len); value = new String(bytes, Charset.forName("UTF-8")); } setField(value); } protected void resetToDefault() { setField(defaultValue); } public Section getSection() { return section; } private class DataTypeErrorInConfigException extends RuntimeException { private static final long serialVersionUID = -7077690323202964355L; } public int getDefaultInt() { if (defaultValue instanceof Integer) { return (Integer) defaultValue; } else if (defaultValue instanceof Double) { return ((Double) defaultValue).intValue(); } else if (defaultValue instanceof Boolean) { return (Boolean) defaultValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public double getDefaultDouble() { if (defaultValue instanceof Integer) { return (Integer) defaultValue; } else if (defaultValue instanceof Double) { return (Double) defaultValue; } else if (defaultValue instanceof Boolean) { return (Boolean) defaultValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public float getDefaultFloat() { if (defaultValue instanceof Integer) { return (Integer) defaultValue; } else if (defaultValue instanceof Double) { return ((Double) defaultValue).floatValue(); } else if (defaultValue instanceof Boolean) { return (Boolean) defaultValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public boolean getDefaultBoolean() { if (defaultValue instanceof Integer) { throw new DataTypeErrorInConfigException(); } else if (defaultValue instanceof Double) { throw new DataTypeErrorInConfigException(); } else if (defaultValue instanceof Boolean) { return (Boolean) defaultValue; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } @SuppressWarnings("null") @Nonnull public String getDefaultString() { if (defaultValue instanceof Integer) { return ((Integer) defaultValue).toString(); } else if (defaultValue instanceof Double) { return ((Double) defaultValue).toString(); } else if (defaultValue instanceof Boolean) { return ((Boolean) defaultValue).toString(); } else if (defaultValue instanceof String) { return (String) defaultValue; } else { throw new DataTypeErrorInConfigException(); } } public int getInt() { if (defaultValue instanceof Integer) { return (Integer) currentValue; } else if (defaultValue instanceof Double) { return ((Double) currentValue).intValue(); } else if (defaultValue instanceof Boolean) { return (Boolean) currentValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public double getDouble() { if (defaultValue instanceof Integer) { return (Integer) currentValue; } else if (defaultValue instanceof Double) { return (Double) currentValue; } else if (defaultValue instanceof Boolean) { return (Boolean) currentValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public float getFloat() { if (defaultValue instanceof Integer) { return (Integer) currentValue; } else if (defaultValue instanceof Double) { return ((Double) currentValue).floatValue(); } else if (defaultValue instanceof Boolean) { return (Boolean) currentValue ? 1 : 0; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } public boolean getBoolean() { if (defaultValue instanceof Integer) { throw new DataTypeErrorInConfigException(); } else if (defaultValue instanceof Double) { throw new DataTypeErrorInConfigException(); } else if (defaultValue instanceof Boolean) { return (Boolean) currentValue; } else if (defaultValue instanceof String) { throw new DataTypeErrorInConfigException(); } else { throw new DataTypeErrorInConfigException(); } } @SuppressWarnings("null") @Nonnull public String getString() { if (defaultValue instanceof Integer) { return ((Integer) currentValue).toString(); } else if (defaultValue instanceof Double) { return ((Double) currentValue).toString(); } else if (defaultValue instanceof Boolean) { return ((Boolean) currentValue).toString(); } else if (defaultValue instanceof String) { return (String) currentValue; } else { throw new DataTypeErrorInConfigException(); } } }
package innovimax.mixthem.arguments; /** * <p>This is a detailed enumeration of additional rule parameters.</p> * @author Innovimax * @version 1.0 */ public enum RuleParam { RANDOM_SEED("seed", ParamType.INTEGER), JOIN_COL1("col1", ParamType.INTEGER), JOIN_COL2("col2", ParamType.INTEGER), JOIN_COLS("cols", ParamType.INTEGER_ARRAY), ZIP_SEP("sep", ParamType.STRING); private final String name; private final ParamType type; private RuleParam(final String name, final ParamType type) { this.name = name; this.type = type; } /** * Returns the alias name of this parameter. * @return The alias name of this parameter */ public String getName() { return this.name; } /** * Returns the comment for this parameter. * @return The comment for this parameter */ public String getComment() { switch(this.type) { case INTEGER: return "is an integer value"; case INTEGER_ARRAY: return "is a list of integer separated by a comma"; default: return "is a string value"; } } /** * Returns the {@link ParamValue} representation of the parameter value. * @param value The value of the parameter on command line * @return The {@link ParamValue} representation of the parameter value */ ParamValue createValue(final String value) throws NumberFormatException { ParamValue pv = null; switch (this.type) { case INTEGER: pv = ParamValue.createInt(Integer.parseInt(value)); break; case INTEGER_ARRAY: String[] stringArray = value.split(","); int[] intArray = new int[stringArray.length]; for (int i=0; i < stringArray.length; i++) { intArray[i] = Integer.parseInt(stringArray[i]); } pv = ParamValue.createIntArray(intArray); break; default: pv = ParamValue.createString(value); } return pv; } }
package io.dang.tomcat.session; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.querybuilder.*; import io.dang.tomcat.CassandraClient; import io.dang.tomcat.io.ByteBufferInputStream; import io.dang.tomcat.io.ByteBufferOutputStream; import org.apache.catalina.Context; import org.apache.catalina.Loader; import org.apache.catalina.Session; import org.apache.catalina.session.StandardSession; import org.apache.catalina.session.StoreBase; import java.io.*; import java.util.List; import java.util.UUID; import org.apache.catalina.util.CustomObjectInputStream; public class CassandraStore extends StoreBase { private String sessionTableName = "sessions"; protected String sessionIdCol = "id"; protected String sessionDataCol = "session_data"; protected String sessionValidCol = "is_valid"; protected String sessionMaxInactiveCol = "max_inactive"; protected String sessionLastAccessedCol = "last_accessed"; protected String clusterName; protected String keyspace; protected String tableName; protected String nodes; CassandraClient client = new CassandraClient("dummy", "dummy"); @Override public int getSize() throws IOException { Select select = QueryBuilder.select().countAll().from(sessionTableName); ResultSet rs = client.getSession().execute(select); Row row = rs.one(); return row.getInt(0); } @Override public String[] keys() throws IOException { Select select = QueryBuilder.select(sessionIdCol).from(sessionTableName); ResultSet rs = client.getSession().execute(select); List<Row> rows = rs.all(); String[] retArray = new String[rows.size()]; int i = 0; for (Row row : rows) { UUID uuid = row.getUUID(0); retArray[i++] = uuid.toString(); } return retArray; } @Override public StandardSession load(String id) throws ClassNotFoundException, IOException { StandardSession session = (StandardSession) getManager().createEmptySession(); Select select = QueryBuilder.select(sessionIdCol, sessionDataCol) .from(sessionTableName) .where(QueryBuilder.eq(sessionIdCol, UUID.fromString(id))) .limit(1); ResultSet rs = client.getSession().execute(select); Row row = rs.one(); if (row == null) { return null; } Context context = manager.getContext(); ByteBufferInputStream bis = new ByteBufferInputStream(row.getBytes(1)); Loader loader = null; ClassLoader classLoader = null; ObjectInputStream ois; if (context != null) { loader = context.getLoader(); } if (loader != null) { classLoader = loader.getClassLoader(); } if (classLoader != null) { ois = new CustomObjectInputStream(bis, classLoader); } else { ois = new ObjectInputStream(bis); } session.setId(id); session.readObjectData(ois); try { ois.close(); } catch (IOException ignore) {} return session; } @Override public void remove(String id) throws IOException { UUID uuid = UUID.fromString(id); Delete delete = QueryBuilder.delete() .from(sessionTableName) .where(QueryBuilder.eq(sessionIdCol, uuid)) .ifExists(); client.getSession().execute(delete); } @Override public void clear() throws IOException { Truncate truncate = QueryBuilder.truncate(sessionTableName); client.getSession().execute(truncate); } @Override public void processExpires() { // NOOP // Note: Sessions in Cassandra will expire by themselves with TTL. // We only need to get rid of the sessions in memory } @Override public void save(Session session) throws IOException { StandardSession cSession = (StandardSession) session; ByteBufferOutputStream bbos = new ByteBufferOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(bbos); try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { cSession.writeObjectData(oos); } Insert insert = QueryBuilder.insertInto(sessionTableName) .using(QueryBuilder.ttl(session.getMaxInactiveInterval())) .value(sessionIdCol, UUID.fromString(session.getId())) .value(sessionDataCol, bbos.getByteBuffer()) .value(sessionValidCol, cSession.isValid()) .value(sessionMaxInactiveCol, session.getMaxInactiveInterval()) // probably don't need this column .value(sessionLastAccessedCol, session.getLastAccessedTime()); client.getSession().execute(insert); } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getKeyspace() { return keyspace; } public void setKeyspace(String keyspace) { this.keyspace = keyspace; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getNodes() { return nodes; } public void setNodes(String nodes) { this.nodes = nodes; } }
package joshie.enchiridion.gui.book; import joshie.enchiridion.EConfig; import joshie.enchiridion.Enchiridion; import joshie.enchiridion.api.EnchiridionAPI; import joshie.enchiridion.api.book.IFeatureProvider; import joshie.enchiridion.lib.EInfo; import net.minecraft.util.ResourceLocation; import java.util.ArrayList; public class GuiLayers extends AbstractGuiOverlay { public static final GuiLayers INSTANCE = new GuiLayers(); private static final ResourceLocation LOCK_DFLT = new ResourceLocation(EInfo.MODID, "textures/books/lock_dftl.png"); private static final ResourceLocation LOCK_HOVER = new ResourceLocation(EInfo.MODID, "textures/books/lock_hover.png"); private static final ResourceLocation VISIBLE_DFLT = new ResourceLocation(EInfo.MODID, "textures/books/layer_dftl.png"); private static final ResourceLocation VISIBLE_HOVER = new ResourceLocation(EInfo.MODID, "textures/books/layer_hover.png"); private IFeatureProvider dragged = null; private int held = 0; private int yStart = 0; private int layerPosition = 0; private GuiLayers() { } public boolean isDragging() { return held != 0; } private boolean isOverLayer(int layerY, int mouseX, int mouseY) { if (mouseX > EConfig.layersXPos + 20 && mouseX <= EConfig.layersXPos + 83) { return mouseY >= EConfig.toolbarYPos - 3 + layerY && mouseY <= EConfig.toolbarYPos + 8 + layerY; } return false; } @Override public void draw(int mouseX, int mouseY) { EnchiridionAPI.draw.drawImage(SIDEBAR, EConfig.layersXPos - 3, EConfig.toolbarYPos - 7, EConfig.layersXPos + 87, EConfig.timelineYPos + 13); EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos, EConfig.toolbarYPos + 7, EConfig.layersXPos + 85, EConfig.timelineYPos + 11, 0xFF312921, 0xFF191511); EnchiridionAPI.draw.drawSplitScaledString("[b]" + Enchiridion.translate("layers") + "[/b]", EConfig.layersXPos + 20, EConfig.toolbarYPos - 2, 250, 0xFFFFFFFF, 1F); int layerY = 0; int hoverY = 0; ArrayList<IFeatureProvider> features = EnchiridionAPI.book.getPage().getFeatures(); for (int i = layerPosition; i < Math.min(features.size(), layerPosition + 24); i++) { layerY += 12; IFeatureProvider feature = features.get(i); /* LOCK ICON */ //Setup the defaults for the lock icon ResourceLocation resource = LOCK_DFLT; int color1 = 0xFFE4D6AE; int color2 = 0x5579725A; if (feature.isFromTemplate()) { color1 = 0xFFDEAE3B; color2 = 0xFF785820; } //Switch over to the hover if it applies if (mouseX >= EConfig.layersXPos + 4 && mouseX <= EConfig.layersXPos + 9 && mouseY >= EConfig.toolbarYPos - 1 + layerY && mouseY <= EConfig.toolbarYPos + layerY + 5) { resource = LOCK_HOVER; if (feature.isFromTemplate()) { color1 = 0xFFA5812C; color2 = 0xFF543D16; } else { color1 = 0xFFB0A483; color2 = 0xFF48453C; } } //Draw the lock icons EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos + 2, EConfig.toolbarYPos - 3 + layerY, EConfig.layersXPos + 11, EConfig.toolbarYPos + 7 + layerY, color1, color2); if (feature.isLocked()) { EnchiridionAPI.draw.drawImage(resource, EConfig.layersXPos + 4, EConfig.toolbarYPos - 1 + layerY, EConfig.layersXPos + 9, EConfig.toolbarYPos + layerY + 5); } /* END LOCK ICON */ /* VISIBILITY ICON */ //Reset resource = VISIBLE_DFLT; if (feature.isFromTemplate()) { color1 = 0xFFDEAE3B; color2 = 0xFF785820; } else { color1 = 0xFFE4D6AE; color2 = 0x5579725A; } if (mouseX > EConfig.layersXPos + 9 && mouseX < EConfig.layersXPos + 20 && mouseY >= EConfig.toolbarYPos - 1 + layerY && mouseY <= EConfig.toolbarYPos + layerY + 5) { resource = VISIBLE_HOVER; if (feature.isFromTemplate()) { color1 = 0xFFA5812C; color2 = 0xFF543D16; } else { color1 = 0xFFB0A483; color2 = 0xFF48453C; } } EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos + 11, EConfig.toolbarYPos - 3 + layerY, EConfig.layersXPos + 20, EConfig.toolbarYPos + 7 + layerY, color1, color2); if (feature.isVisible()) { EnchiridionAPI.draw.drawImage(resource, EConfig.layersXPos + 12, EConfig.toolbarYPos - 1 + layerY, EConfig.layersXPos + 19, EConfig.toolbarYPos + layerY + 5); } /* END VISIBILITY ICON */ /* Layer itself */ EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos + 20, EConfig.toolbarYPos - 3 + layerY, EConfig.layersXPos + 83, EConfig.toolbarYPos + 7 + layerY, color1, color2); if (isOverLayer(layerY, mouseX, mouseY) || EnchiridionAPI.book.isGroupSelected(feature)) { hoverY = layerY; if (feature.isFromTemplate()) { color1 = 0xFFA5812C; color2 = 0xFF543D16; } else { color1 = 0xFFB0A483; color2 = 0xFF48453C; } EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos + 20, EConfig.toolbarYPos - 3 + layerY, EConfig.layersXPos + 83, EConfig.toolbarYPos + 7 + layerY, color1, color2); } /* End Layer */ String name = feature.getFeature().getName(); String truncated = (name.substring(0, Math.min(name.length(), 20))).replace("\n", " "); EnchiridionAPI.draw.drawSplitScaledString(truncated, EConfig.layersXPos + 25, EConfig.toolbarYPos + layerY, 250, 0xFF000000, 0.5F); } //Dragging! if (dragged != null && hoverY != 0) { if (held < 20) { held++; } else { String name = dragged.getFeature().getName(); String truncated = name.substring(0, Math.min(name.length(), 20)); EnchiridionAPI.draw.drawBorderedRectangle(EConfig.layersXPos + 20, EConfig.toolbarYPos - 3 + hoverY, EConfig.layersXPos + 83, EConfig.toolbarYPos + 7 + hoverY, 0xFFEEEEEE, 0xFF48453C); EnchiridionAPI.draw.drawSplitScaledString(truncated, EConfig.layersXPos + 25, EConfig.toolbarYPos + hoverY, 250, 0xFF000000, 0.5F); } } } @Override public boolean mouseClicked(int mouseX, int mouseY) { int layerY = 0; ArrayList<IFeatureProvider> features = EnchiridionAPI.book.getPage().getFeatures(); for (int i = layerPosition; i < Math.min(features.size(), layerPosition + 20); i++) { IFeatureProvider provider = features.get(i); layerY += 12; if (!provider.isLocked() && isOverLayer(layerY, mouseX, mouseY)) { yStart = mouseY; dragged = features.get(i); GuiBook.INSTANCE.selectLayer(dragged); return true; } } dragged = null; return false; } private void insertLayerAt(int mouseY, int layerNumber) { int change = 0; int difference = mouseY - yStart; if (difference > 0) change = 0; else if (difference < 0) change = -1; if (dragged.getLayerIndex() != layerNumber) { dragged.setLayerIndex(layerNumber + change); //Resort EnchiridionAPI.book.getPage().sort(); } } @Override public void mouseReleased(int mouseX, int mouseY) { boolean placing = held >= 20; int layerY = 0; ArrayList<IFeatureProvider> features = EnchiridionAPI.book.getPage().getFeatures(); for (int i = layerPosition; i < Math.min(features.size(), layerPosition + 24); i++) { layerY += 12; if (isOverLayer(layerY, mouseX, mouseY)) { if (placing) { insertLayerAt(mouseY, features.get(i).getLayerIndex()); } else { IFeatureProvider selected = EnchiridionAPI.book.getSelected(); if (selected != null) selected.deselect(); EnchiridionAPI.book.setSelected(features.get(i)); selected = EnchiridionAPI.book.getSelected(); selected.select(mouseX, mouseY); selected.select(mouseX, mouseY); selected.mouseReleased(mouseX, mouseY, 0); } } /* LOCK */ if (mouseX >= EConfig.layersXPos + 4 && mouseX <= EConfig.layersXPos + 9 && mouseY >= EConfig.toolbarYPos - 1 + layerY && mouseY <= EConfig.toolbarYPos + layerY + 5) { IFeatureProvider feature = features.get(i); feature.setLocked(!feature.isLocked()); } /* END LOCK */ /* VISIBLE */ if (mouseX > EConfig.layersXPos + 9 && mouseX < EConfig.layersXPos + 20 && mouseY >= EConfig.toolbarYPos - 1 + layerY && mouseY <= EConfig.toolbarYPos + layerY + 5) { IFeatureProvider feature = features.get(i); feature.setVisible(!feature.isVisible()); } /* END VISIBLE */ } //Reset dragged = null; yStart = 0; held = 0; } @Override public void scroll(boolean down, int mouseX, int mouseY) { if (mouseX >= EConfig.layersXPos) { if (down) { this.layerPosition++; } else { this.layerPosition this.layerPosition = Math.max(layerPosition, 0); } } } }
package lightster.aws.lambda.fop; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.S3Object; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.MimeConstants; public class PDFGenerator implements RequestHandler<LambdaRequest, LambdaResponse> { public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: PDFGenerator data.xml style.xslt output.pdf"); System.exit(1); } try { generatePdfUsingS3(args[0], args[1], args[2]); // generatePdf(args[0], args[1], args[2]); } catch (Exception exception) { exception.printStackTrace(System.err); System.exit(-1); } } /** * @param String dataPath * @param String xsltPath * @param String outputPath */ public static void generatePdf(String dataPath, String xsltPath, String outputPath) throws Exception { File dataFile = new File(dataPath); File xsltFile = new File(xsltPath); File outputFile = new File(outputPath); generatePdf(dataFile, xsltFile, outputFile); } /** * @param File dataFile * @param File xsltFile * @param File outputFile */ public static void generatePdf(File dataFile, File xsltFile, File outputFile) throws Exception { FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream outputBuffer = new BufferedOutputStream( new FileOutputStream(outputFile) ); try { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outputBuffer); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltFile)); Source source = new StreamSource(dataFile); Result result = new SAXResult(fop.getDefaultHandler()); transformer.transform(source, result); } finally { outputBuffer.close(); } } public static void generatePdfUsingS3(String dataPath, String xsltPath, String outputPath) throws Exception { AmazonS3URI dataUri = new AmazonS3URI(dataPath); AmazonS3URI xsltUri = new AmazonS3URI(xsltPath); AmazonS3URI outputUri = new AmazonS3URI(outputPath); File dataFile = new File("/tmp/data.xml"); File xsltFile = new File("/tmp/style.xslt"); File outputFile = new File("/tmp/output.pdf"); AmazonS3 s3; try { s3 = new AmazonS3Client(new ProfileCredentialsProvider().getCredentials()); } catch (Exception exception) { s3 = new AmazonS3Client(); } s3.getObject( new GetObjectRequest(dataUri.getBucket(), dataUri.getKey()), dataFile ); s3.getObject( new GetObjectRequest(xsltUri.getBucket(), xsltUri.getKey()), xsltFile ); generatePdf(dataFile, xsltFile, outputFile); s3.putObject(outputUri.getBucket(), outputUri.getKey(), outputFile); } /** * @param LambdaRequest request * @param Context context * @return LambdaResponse */ public LambdaResponse handleRequest(LambdaRequest request, Context context) { LambdaResponse response = new LambdaResponse(); try { generatePdfUsingS3( request.getDataUrl(), request.getXsltUrl(), request.getOutputUrl() ); response.setOutputUrl(request.getOutputUrl()); } catch (Exception exception) { response.setErrorMessage(exception.getMessage()); response.setHasError(true); exception.printStackTrace(System.err); } return response; } }
package main.flowstoneenergy.blocks; import java.util.List; import main.flowstoneenergy.FlowstoneEnergy; import main.flowstoneenergy.core.libs.ModInfo; import net.minecraft.block.BlockOre; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockOres extends BlockOre { //public IIcon[] icon = new IIcon[16]; public final static PropertyEnum<EnumOreTypes> TYPE = PropertyEnum.<EnumOreTypes> create("type", EnumOreTypes.class); public BlockOres() { super(); this.setHardness(2F); this.setUnlocalizedName(ModInfo.MODID + ".ores"); this.setCreativeTab(FlowstoneEnergy.blockTab); this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, EnumOreTypes.COPPER)); } @Override public IBlockState getStateFromMeta(int meta) { IBlockState state = this.getDefaultState(); switch (meta) { case 0: return state.withProperty(TYPE, EnumOreTypes.COPPER); case 1: return state.withProperty(TYPE, EnumOreTypes.TIN); case 2: return state.withProperty(TYPE, EnumOreTypes.LEAD); case 3: return state.withProperty(TYPE, EnumOreTypes.SILVER); case 4: return state.withProperty(TYPE, EnumOreTypes.NICKEL); } return super.getStateFromMeta(meta); } @Override public int getMetaFromState(IBlockState state) { return ((EnumOreTypes) state.getValue(TYPE)).getMeta(); } @Override protected BlockState createBlockState() { return new BlockState(this, TYPE); } @Override protected ItemStack createStackedBlock(IBlockState state) { return new ItemStack(this, 1, getMetaFromState(state)); } /*@Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister ir) { this.icon[0] = ir.registerIcon(ModInfo.MODID + ":ores/copperOre"); this.icon[1] = ir.registerIcon(ModInfo.MODID + ":ores/tinOre"); this.icon[2] = ir.registerIcon(ModInfo.MODID + ":ores/leadOre"); this.icon[3] = ir.registerIcon(ModInfo.MODID + ":ores/silverOre"); this.icon[4] = ir.registerIcon(ModInfo.MODID + ":ores/nickelOre"); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return this.icon[meta]; } */ @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item id, CreativeTabs tab, List<ItemStack> list) { for (int i = 0; i < 5; i++) { list.add(new ItemStack(id, 1, i)); } } @Override public int damageDropped(IBlockState blockState) { return getMetaFromState(blockState); } @Override public int getDamageValue(World worldIn, BlockPos pos) { IBlockState blockState = worldIn.getBlockState(pos); return getMetaFromState(blockState); } public static enum EnumOreTypes implements IStringSerializable { COPPER("copper", 0), TIN("tin", 1), LEAD("lead", 2), SILVER("silver", 3), NICKEL("nickel", 4); private String name; private int meta; EnumOreTypes(String name, int meta) { this.name = name; this.meta = meta; } @Override public String getName() { return this.name; } public int getMeta() { return meta; } @Override public String toString() { return this.name; } } }
package mcjty.deepresonance.proxy; import mcjty.deepresonance.DeepResonance; import mcjty.deepresonance.ForgeEventHandlers; import mcjty.deepresonance.blocks.ModBlocks; import mcjty.deepresonance.blocks.generator.GeneratorConfiguration; import mcjty.deepresonance.blocks.laser.LaserBonusConfiguration; import mcjty.deepresonance.fluid.DRFluidRegistry; import mcjty.deepresonance.gui.GuiProxy; import mcjty.deepresonance.items.ModItems; import mcjty.deepresonance.network.DRMessages; import mcjty.deepresonance.radiation.RadiationConfiguration; import mcjty.deepresonance.radiation.RadiationTickEvent; import mcjty.deepresonance.radiation.SuperGenerationConfiguration; import mcjty.deepresonance.worldgen.WorldGen; import mcjty.deepresonance.worldgen.WorldGenConfiguration; import mcjty.deepresonance.worldgen.WorldTickHandler; import mcjty.lib.network.PacketHandler; import mcjty.lib.proxy.AbstractCommonProxy; import mcjty.lib.varia.WrenchChecker; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import org.apache.logging.log4j.Level; public abstract class CommonProxy extends AbstractCommonProxy { @Override public void preInit(FMLPreInitializationEvent e) { super.preInit(e); MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers()); mainConfig = DeepResonance.config; readMainConfig(); SimpleNetworkWrapper network = PacketHandler.registerMessages(DeepResonance.MODID, "deepresonance"); DRMessages.registerNetworkMessages(network); ModItems.init(); ModBlocks.init(); WorldGen.init(); DRFluidRegistry.initFluids(); } private void readMainConfig() { Configuration cfg = mainConfig; try { cfg.load(); cfg.addCustomCategoryComment(WorldGenConfiguration.CATEGORY_WORLDGEN, "Configuration for worldgen"); cfg.addCustomCategoryComment(GeneratorConfiguration.CATEGORY_GENERATOR, "Configuration for the generator multiblock"); cfg.addCustomCategoryComment(RadiationConfiguration.CATEGORY_RADIATION, "Configuration for the radiation"); cfg.addCustomCategoryComment(LaserBonusConfiguration.CATEGORY_LASERBONUS, "Configuration for the laser bonuses"); cfg.addCustomCategoryComment(SuperGenerationConfiguration.CATEGORY_SUPERGEN, "Configuration for super power generation (using pulser)"); WorldGenConfiguration.init(cfg); GeneratorConfiguration.init(cfg); RadiationConfiguration.init(cfg); LaserBonusConfiguration.init(cfg); SuperGenerationConfiguration.init(cfg); } catch (Exception e1) { FMLLog.log(Level.ERROR, e1, "Problem loading config file!"); } finally { if (mainConfig.hasChanged()) { mainConfig.save(); } } } @Override public void init(FMLInitializationEvent e) { super.init(e); NetworkRegistry.INSTANCE.registerGuiHandler(DeepResonance.instance, new GuiProxy()); MinecraftForge.EVENT_BUS.register(WorldTickHandler.instance); MinecraftForge.EVENT_BUS.register(new RadiationTickEvent()); } @Override public void postInit(FMLPostInitializationEvent e) { super.postInit(e); if (mainConfig.hasChanged()) { mainConfig.save(); } mainConfig = null; WrenchChecker.init(); } public abstract void throwException(Exception e, int i); }
package net.glowstone.entity; import com.flowpowered.networking.Message; import net.glowstone.EventFactory; import net.glowstone.constants.GlowPotionEffect; import net.glowstone.inventory.EquipmentMonitor; import net.glowstone.net.message.play.entity.EntityEffectMessage; import net.glowstone.net.message.play.entity.EntityEquipmentMessage; import net.glowstone.net.message.play.entity.EntityRemoveEffectMessage; import org.bukkit.EntityEffect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.entity.*; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.BlockIterator; import org.bukkit.util.Vector; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Criterias; import java.util.*; /** * A GlowLivingEntity is a {@link org.bukkit.entity.Player} or {@link org.bukkit.entity.Monster}. * * @author Graham Edgecombe. */ public abstract class GlowLivingEntity extends GlowEntity implements LivingEntity { /** * Potion effects on the entity. */ private final Map<PotionEffectType, PotionEffect> potionEffects = new HashMap<>(); /** * The entity's health. */ protected double health; /** * The magnitude of the last damage the entity took. */ private double lastDamage; /** * How long the entity has until it runs out of air. */ private int airTicks = 300; /** * The maximum amount of air the entity can hold. */ private int maximumAir = 300; /** * The number of ticks remaining in the invincibility period. */ private int noDamageTicks = 0; /** * The default length of the invincibility period. */ private int maxNoDamageTicks = 10; /** * A custom overhead name to be shown for non-Players. */ private String customName; /** * Whether the custom name is shown. */ private boolean customNameVisible; /** * Whether the entity should be removed if it is too distant from players. */ private boolean removeDistance; /** * Whether the (non-Player) entity can pick up armor and tools. */ private boolean pickupItems; /** * Monitor for the equipment of this entity. */ private EquipmentMonitor equipmentMonitor = new EquipmentMonitor(this); /** * The LivingEntity's AttributeManager. */ private final AttributeManager attributeManager; /** * Creates a mob within the specified world. * * @param location The location. */ public GlowLivingEntity(Location location) { super(location); attributeManager = new AttributeManager(this); attributeManager.setProperty(AttributeManager.Key.KEY_MAX_HEALTH, 20); health = AttributeManager.Key.KEY_MAX_HEALTH.getDef(); } // Internals @Override public void pulse() { super.pulse(); // invulnerability if (noDamageTicks > 0) { --noDamageTicks; } Material mat = getEyeLocation().getBlock().getType(); // breathing if (mat == Material.WATER || mat == Material.STATIONARY_WATER) { if (canTakeDamage(EntityDamageEvent.DamageCause.DROWNING)) { --airTicks; if (airTicks <= -20) { airTicks = 0; damage(1, EntityDamageEvent.DamageCause.DROWNING); } } } else { airTicks = maximumAir; } if (isTouchingMaterial(Material.CACTUS) && canTakeDamage(EntityDamageEvent.DamageCause.CONTACT)) { damage(1, EntityDamageEvent.DamageCause.CONTACT); } if (location.getY() < -64) { // no canTakeDamage call - pierces through game modes damage(4, EntityDamageEvent.DamageCause.VOID); } if (isWithinSolidBlock()) damage(1, EntityDamageEvent.DamageCause.SUFFOCATION); // potion effects List<PotionEffect> effects = new ArrayList<>(potionEffects.values()); for (PotionEffect effect : effects) { // pulse effect PotionEffectType type = effect.getType(); GlowPotionEffect glowType = GlowPotionEffect.getEffect(type); if (glowType != null) { glowType.pulse(this, effect); } if (effect.getDuration() > 0) { // reduce duration and re-add addPotionEffect(new PotionEffect(type, effect.getDuration() - 1, effect.getAmplifier(), effect.isAmbient()), true); } else { // remove removePotionEffect(type); } } } @Override public void reset() { super.reset(); equipmentMonitor.resetChanges(); } @Override public List<Message> createUpdateMessage() { List<Message> messages = super.createUpdateMessage(); for (EquipmentMonitor.Entry change : equipmentMonitor.getChanges()) { messages.add(new EntityEquipmentMessage(id, change.slot, change.item)); } attributeManager.applyMessages(messages); return messages; } public AttributeManager getAttributeManager() { return attributeManager; } // Properties @Override public double getEyeHeight() { return 0; } @Override public double getEyeHeight(boolean ignoreSneaking) { return getEyeHeight(); } @Override public Location getEyeLocation() { return getLocation().add(0, getEyeHeight(), 0); } @Override public Player getKiller() { return null; } @Override public boolean hasLineOfSight(Entity other) { return false; } @Override public EntityEquipment getEquipment() { return null; } // Properties @Override public int getNoDamageTicks() { return noDamageTicks; } @Override public void setNoDamageTicks(int ticks) { noDamageTicks = ticks; } @Override public int getMaximumNoDamageTicks() { return maxNoDamageTicks; } @Override public void setMaximumNoDamageTicks(int ticks) { maxNoDamageTicks = ticks; } @Override public int getRemainingAir() { return airTicks; } @Override public void setRemainingAir(int ticks) { airTicks = Math.min(ticks, maximumAir); } @Override public int getMaximumAir() { return maximumAir; } @Override public void setMaximumAir(int ticks) { maximumAir = Math.max(0, ticks); } @Override public boolean getRemoveWhenFarAway() { return removeDistance; } @Override public void setRemoveWhenFarAway(boolean remove) { removeDistance = remove; } @Override public boolean getCanPickupItems() { return pickupItems; } @Override public void setCanPickupItems(boolean pickup) { pickupItems = pickup; } /** * Get the hurt sound of this entity, or null for silence. * @return the hurt sound if available */ protected Sound getHurtSound() { return null; } /** * Get the death sound of this entity, or null for silence. * @return the death sound if available */ protected Sound getDeathSound() { return null; } /** * Get whether this entity should take damage from the specified source. * Usually used to check environmental sources such as drowning. * @param damageCause the damage source to check * @return whether this entity can take damage from the source */ public boolean canTakeDamage(EntityDamageEvent.DamageCause damageCause) { return true; } // Line of Sight private List<Block> getLineOfSight(Set<Material> transparent, int maxDistance, int maxLength) { // same limit as CraftBukkit if (maxDistance > 120) { maxDistance = 120; } LinkedList<Block> blocks = new LinkedList<>(); Iterator<Block> itr = new BlockIterator(this, maxDistance); while (itr.hasNext()) { Block block = itr.next(); blocks.add(block); if (maxLength != 0 && blocks.size() > maxLength) { blocks.removeFirst(); } Material material = block.getType(); if (transparent == null) { if (material != Material.AIR) { break; } } else { if (!transparent.contains(material)) { break; } } } return blocks; } private List<Block> getLineOfSight(HashSet<Byte> transparent, int maxDistance, int maxLength) { Set<Material> materials = new HashSet<Material>(); Iterator<Byte> itr = transparent.iterator(); while (itr.hasNext()) { byte b = itr.next().byteValue(); materials.add(Material.getMaterial((int) b)); } return getLineOfSight(materials, maxDistance, maxLength); } @Override public List<Block> getLineOfSight(Set<Material> transparent, int maxDistance) { return getLineOfSight(transparent, maxDistance, 0); } @Deprecated @Override public List<Block> getLineOfSight(HashSet<Byte> transparent, int maxDistance) { return getLineOfSight(transparent, maxDistance, 0); } @Deprecated @Override public Block getTargetBlock(HashSet<Byte> transparent, int maxDistance) { return getLineOfSight(transparent, maxDistance).get(0); } @Override public Block getTargetBlock(Set<Material> materials, int maxDistance) { return getLineOfSight(materials, maxDistance).get(0); } @Deprecated @Override public List<Block> getLastTwoTargetBlocks(HashSet<Byte> transparent, int maxDistance) { return getLineOfSight(transparent, maxDistance, 2); } @Override public List<Block> getLastTwoTargetBlocks(Set<Material> materials, int maxDistance) { return getLineOfSight(materials, maxDistance, 2); } /** * Returns whether the entity's eye location is within a solid block */ public boolean isWithinSolidBlock() { return getEyeLocation().getBlock().getType().isOccluding(); } // Projectiles @Override public Egg throwEgg() { return launchProjectile(Egg.class); } @Override public Snowball throwSnowball() { return launchProjectile(Snowball.class); } @Override public Arrow shootArrow() { return launchProjectile(Arrow.class); } @Override public <T extends Projectile> T launchProjectile(Class<? extends T> projectile) { return launchProjectile(projectile, getLocation().getDirection()); // todo: multiply by some speed } @Override public <T extends Projectile> T launchProjectile(Class<? extends T> projectile, Vector velocity) { T entity = world.spawn(getEyeLocation(), projectile); entity.setVelocity(velocity); return entity; } // Health @Override public double getHealth() { return health; } @Override public void setHealth(double health) { if (health < 0) health = 0; if (health > getMaxHealth()) health = getMaxHealth(); this.health = health; //TODO: Once Glowstone has proper entity support, entities can have UUID names on the scoreboard if (this instanceof GlowPlayer) { GlowPlayer player = (GlowPlayer) this; for (Objective objective: getServer().getScoreboardManager().getMainScoreboard().getObjectivesByCriteria(Criterias.HEALTH)) { objective.getScore(player.getName()).setScore((int) health); } } } @Override public void damage(double amount) { damage(amount, null, EntityDamageEvent.DamageCause.CUSTOM); } @Override public void damage(double amount, Entity source) { damage(amount, source, EntityDamageEvent.DamageCause.CUSTOM); } @Override public void damage(double amount, EntityDamageEvent.DamageCause cause) { damage(amount, null, cause); } @Override public void damage(double amount, Entity source, EntityDamageEvent.DamageCause cause) { // invincibility timer if (noDamageTicks > 0 || health <= 0 || !canTakeDamage(cause)) { return; } else { noDamageTicks = maxNoDamageTicks; } // fire resistance if (cause != null && hasPotionEffect(PotionEffectType.FIRE_RESISTANCE)) { switch (cause) { case PROJECTILE: if (source == null || !(source instanceof Fireball)) { break; } case FIRE: case FIRE_TICK: case LAVA: return; } } // fire event // todo: use damage modifier system EntityDamageEvent event; if (source == null) { event = new EntityDamageEvent(this, cause, amount); } else { event = new EntityDamageByEntityEvent(source, this, cause, amount); } EventFactory.callEvent(event); if (event.isCancelled()) { return; } // apply damage amount = event.getFinalDamage(); lastDamage = amount; setHealth(health - amount); playEffect(EntityEffect.HURT); // play sounds, handle death if (health <= 0.0) { Sound deathSound = getDeathSound(); if (deathSound != null) { world.playSound(location, deathSound, 1.0f, 1.0f); } // todo: drop items } else { Sound hurtSound = getHurtSound(); if (hurtSound != null) { world.playSound(location, hurtSound, 1.0f, 1.0f); } } } @Override public double getMaxHealth() { return attributeManager.getPropertyValue(AttributeManager.Key.KEY_MAX_HEALTH); } @Override public void setMaxHealth(double health) { attributeManager.setProperty(AttributeManager.Key.KEY_MAX_HEALTH, health); } @Override public void resetMaxHealth() { setMaxHealth(20); } @Override public double getLastDamage() { return lastDamage; } @Override public void setLastDamage(double damage) { lastDamage = damage; } // Invalid health methods @Override public void _INVALID_damage(int amount) { damage(amount); } @Override public int _INVALID_getLastDamage() { return (int) getLastDamage(); } @Override public void _INVALID_setLastDamage(int damage) { setLastDamage(damage); } @Override public void _INVALID_setMaxHealth(int health) { setMaxHealth(health); } @Override public int _INVALID_getMaxHealth() { return (int) getMaxHealth(); } @Override public void _INVALID_damage(int amount, Entity source) { damage(amount, source); } @Override public int _INVALID_getHealth() { return (int) getHealth(); } @Override public void _INVALID_setHealth(int health) { setHealth(health); } // Potion effects @Override public boolean addPotionEffect(PotionEffect effect) { return addPotionEffect(effect, false); } @Override public boolean addPotionEffect(PotionEffect effect, boolean force) { if (potionEffects.containsKey(effect.getType())) { if (force) { removePotionEffect(effect.getType()); } else { return false; } } potionEffects.put(effect.getType(), effect); EntityEffectMessage msg = new EntityEffectMessage(getEntityId(), effect.getType().getId(), effect.getAmplifier(), effect.getDuration(), effect.isAmbient()); for (GlowPlayer player : world.getRawPlayers()) { if (player == this) { // special handling for players having a different view of themselves player.getSession().send(new EntityEffectMessage(0, effect.getType().getId(), effect.getAmplifier(), effect.getDuration(), effect.isAmbient())); } else if (player.canSeeEntity(this)) { player.getSession().send(msg); } } return true; } @Override public boolean addPotionEffects(Collection<PotionEffect> effects) { boolean result = true; for (PotionEffect effect : effects) { if (!addPotionEffect(effect)) { result = false; } } return result; } @Override public boolean hasPotionEffect(PotionEffectType type) { return potionEffects.containsKey(type); } @Override public void removePotionEffect(PotionEffectType type) { if (!hasPotionEffect(type)) return; potionEffects.remove(type); EntityRemoveEffectMessage msg = new EntityRemoveEffectMessage(getEntityId(), type.getId()); for (GlowPlayer player : world.getRawPlayers()) { if (player == this) { // special handling for players having a different view of themselves player.getSession().send(new EntityRemoveEffectMessage(0, type.getId())); } else if (player.canSeeEntity(this)) { player.getSession().send(msg); } } } @Override public Collection<PotionEffect> getActivePotionEffects() { return Collections.unmodifiableCollection(potionEffects.values()); } @Override public void setOnGround(boolean onGround) { super.setOnGround(onGround); if (onGround && getFallDistance() > 3) { float damage = this.getFallDistance() - 3; damage = Math.round(damage); if (damage == 0) { setFallDistance(0); return; } EntityDamageEvent ev = new EntityDamageEvent(this, EntityDamageEvent.DamageCause.FALL, damage); this.getServer().getPluginManager().callEvent(ev); if (ev.isCancelled()) { setFallDistance(0); return; } this.setLastDamageCause(ev); this.damage(ev.getDamage()); } this.setFallDistance(0); } // Custom name @Override public void setCustomName(String name) { customName = name; } @Override public String getCustomName() { return customName; } @Override public void setCustomNameVisible(boolean flag) { customNameVisible = flag; } @Override public boolean isCustomNameVisible() { return customNameVisible; } // Leashes @Override public boolean isLeashed() { return false; } @Override public Entity getLeashHolder() throws IllegalStateException { return null; } @Override public boolean setLeashHolder(Entity holder) { return false; } }
package sonarqube; import graphql.GraphQL; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLList; import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLTypeReference; import org.sonarqube.ws.Issues; import org.sonarqube.ws.Rules; import org.sonarqube.ws.client.HttpConnector; import org.sonarqube.ws.client.WsClient; import org.sonarqube.ws.client.WsClientFactories; import org.sonarqube.ws.client.issue.SearchWsRequest; import static graphql.Scalars.GraphQLString; import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition; import static graphql.schema.GraphQLObjectType.newObject; import static java.util.Arrays.asList; public class Schema { public static GraphQL create() { GraphQLObjectType ruleType = newObject() .name("Rule") .field(newFieldDefinition() .name("key") .type(GraphQLString) .build()) .field(newFieldDefinition() .name("name") .type(GraphQLString) .build()) .build(); GraphQLObjectType issueType = newObject() .name("Issue") .description("A SonarQube issue") .field(newFieldDefinition() .name("key") .description("The key.") .type(GraphQLString) .build()) .field(newFieldDefinition() .name("message") .description("The msg") .type(GraphQLString) .build()) .field(newFieldDefinition() .name("severity") .description("The severity") .type(GraphQLString) .build()) .field(newFieldDefinition() .name("rule") .type(ruleType) .dataFetcher(env -> { Issues.Issue issue = (Issues.Issue) env.getSource(); return searchRule(issue.getRule()); }) .build()) .build(); GraphQLObjectType queryType = newObject() .name("sonarQubeQuery") .field(newFieldDefinition() .type(ruleType) .name("rule") .argument(GraphQLArgument.newArgument() .name("key") .type(new GraphQLNonNull(GraphQLString)) .build()) .dataFetcher(env -> searchRule(env.getArgument("key"))) .build()) .field(newFieldDefinition() .type(new GraphQLList(new GraphQLTypeReference("Issue"))) .name("issues") .argument(GraphQLArgument.newArgument() .name("severity") .type(GraphQLString) .build()) .dataFetcher(env -> searchIssues(new SearchWsRequest().setSeverities(asList((String)env.getArgument("severity")))).getIssuesList()) .build()) .field(newFieldDefinition() .type(issueType) .name("issue") .dataFetcher(env -> searchIssues(new SearchWsRequest()).getIssues(0)) .build()) .build(); GraphQLSchema schema = GraphQLSchema.newSchema() .query(queryType) .build(); return new GraphQL(schema); } public static Issues.SearchWsResponse searchIssues(SearchWsRequest request) { System.out.println("HTTP HttpConnector httpConnector = HttpConnector.newBuilder() .url("https://sonarqube.com") .build(); WsClient wsClient = WsClientFactories.getDefault().newClient(httpConnector); request.setPageSize(5); return wsClient.issues().search(request); } public static Rules.Rule searchRule(String key) { System.out.println("HTTP HttpConnector httpConnector = HttpConnector.newBuilder() .url("https://sonarqube.com") .build(); WsClient wsClient = WsClientFactories.getDefault().newClient(httpConnector); return wsClient.rules().search(new org.sonarqube.ws.client.rule.SearchWsRequest().setRuleKey(key)).getRules(0); } }
package org.arachb.owlbuilder.lib; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.arachb.arachadmin.AbstractConnection; import org.arachb.arachadmin.PElementBean; import org.arachb.arachadmin.ParticipantBean; import org.arachb.arachadmin.PropertyBean; import org.arachb.arachadmin.TermBean; import org.arachb.owlbuilder.Owlbuilder; import org.semanticweb.owlapi.model.AddAxiom; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAxiom; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLIndividual; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; public class Participant implements GeneratingEntity{ final static String BADTAXQuantifiedParticipant = "Term without IRI referenced as participant taxon: participant QuantifiedParticipantxon id = %s"; final static String BADANATOMYIRI = "Term without IRQuantifiedParticipantd as participant anatomy: participant id = %s; anatomy id = %s"; final static String BADSUBSTRATEIRI = "Term without IRI referenced as participant substrate; participant id = %s; substrate id = %s"; private static Logger log = Logger.getLogger(Participant.class); private final ParticipantBean bean; final Set<ParticipantElement> elements = new HashSet<ParticipantElement>(); private final ParticipantElement headElement; private final PropertyTerm property; public Participant(ParticipantBean b){ bean = b; property = new PropertyTerm(PropertyBean.getCached(b.getProperty())); headElement = ParticipantElement.getElement(PElementBean.getCached(bean.getHeadElement())); } /** * Utility for making Participant Sets from sets of beans */ public static Set<Participant> wrapSet(Set<ParticipantBean> bset){ final Set<Participant>result = new HashSet<Participant>(); for(ParticipantBean b : bset){ result.add(new Participant(b)); } return result; } final static String BADELEMENTMSG = "head Element generated neither a class or a individual: %s"; //TODO work through the assumption here /* * @return true if the headElement is an individual * This should suffice, at least for the moment * */ boolean isIndividual(){ return headElement.isIndividual(); } @Override public OWLObject generateOWL(Owlbuilder builder, Map<String,OWLObject> owlElements) throws Exception{ OWLObject headObject = headElement.generateOWL(builder, owlElements); Set <Integer>children = headElement.getChildren(); switch (children.size()){ case 0: if (headObject instanceof OWLClassExpression){ return generateNoDependentOWL(builder, property, headObject,owlElements); } else if (headObject instanceof OWLIndividual){ return generateNoDependentOWL(builder, property, headObject,owlElements); } else { throw new RuntimeException(String.format(BADELEMENTMSG,headElement)); } case 1: Integer childIndex = children.iterator().next(); ParticipantElement child = headElement.getChildElement(childIndex); PropertyTerm childProperty = headElement.getChildProperty(childIndex); if (headObject instanceof OWLClassExpression){ OWLObject childObject = generateRestrictionClass(builder, owlElements, child, childProperty); return generateDependentOWLClass(builder, childProperty, (OWLClassExpression)headObject, childObject, owlElements); } else if (headObject instanceof OWLIndividual){ OWLObject childObject = generateRestrictionClass(builder, owlElements, child, childProperty); return generateDependentOWLIndividual(builder, childProperty, (OWLIndividual)headObject, childObject, owlElements); } else { throw new RuntimeException(String.format(BADELEMENTMSG,headElement)); } default: throw new RuntimeException(String.format("Didn't expect %d children",children.size())); } } final Map<String,OWLObject> defaultElementTable = new HashMap<String,OWLObject>(); @Override public OWLObject generateOWL(Owlbuilder b) throws Exception{ defaultElementTable.clear(); OWLObject result = null; try{ result = generateOWL(b,defaultElementTable); } finally{ defaultElementTable.clear(); } return result; } /** * @param factory * @param headProperty * @param headObject * @param childObject * @param names * @return */ private OWLObject generateDependentOWLClass(Owlbuilder builder, PropertyTerm childProperty, OWLClassExpression headClassExpr, OWLObject childObject, Map<String,OWLObject> names) throws Exception{ final OWLDataFactory factory = builder.getDataFactory(); OWLObjectProperty elementProperty = (OWLObjectProperty)childProperty.generateOWL(builder,names); if (childObject != null){ if (childObject instanceof OWLClassExpression){ final OWLClassExpression childClass = (OWLClassExpression)childObject; OWLClassExpression intersect = factory.getOWLObjectIntersectionOf(headClassExpr,childClass); OWLClassExpression propertyRestriction = factory.getOWLObjectSomeValuesFrom(elementProperty,intersect); log.info("Generated Property restriction(2): " + propertyRestriction); return intersect; } else if (childObject instanceof OWLIndividual){ log.info("Individual child of class"); } else { throw new RuntimeException("child is neither a class expression or individual: " + childObject); } } OWLClassExpression propertyRestriction = factory.getOWLObjectSomeValuesFrom(elementProperty,headClassExpr); log.info("Generated Property restriction: " + propertyRestriction); return headClassExpr; } private OWLObject generateDependentOWLIndividual(Owlbuilder builder, PropertyTerm childProperty, OWLIndividual headInd, OWLObject childObject, Map<String,OWLObject> names) throws Exception{ final OWLDataFactory factory = builder.getDataFactory(); OWLObjectProperty elementProperty = (OWLObjectProperty)childProperty.generateOWL(builder,names); log.info("Generated Individual reference: " + headInd); if (childObject != null){ if (childObject instanceof OWLIndividual){ OWLIndividual childIndividual = (OWLIndividual)childObject; OWLObjectPropertyAssertionAxiom assertion = factory.getOWLObjectPropertyAssertionAxiom(elementProperty, headInd, childIndividual); // Finally, add the axiom to our ontology and save AddAxiom addAxiomChange = new AddAxiom(builder.getTarget(), assertion); builder.getOntologyManager().applyChange(addAxiomChange); } else { //child is class expression? log.info("class child of individual"); } } return headInd; //TODO finish implementing individual case } /** * @param builder * @param headProperty * @param headObject * @param names * @return */ private OWLObject generateNoDependentOWL(Owlbuilder builder, PropertyTerm headProperty, OWLObject headObject, Map<String,OWLObject> names) throws Exception { final OWLDataFactory factory = builder.getDataFactory(); final OWLObjectProperty elementProperty = (OWLObjectProperty)headProperty.generateOWL(builder,names); if (headObject instanceof OWLClassExpression){ final OWLClassExpression headClass = (OWLClassExpression)headObject; OWLClassExpression propertyRestriction = factory.getOWLObjectSomeValuesFrom(elementProperty,headClass); log.info("Generated Property restriction: " + propertyRestriction); return propertyRestriction; } else if (headObject instanceof OWLIndividual){ log.info("Generated Individual reference: " + headObject); OWLIndividual eventIndividual = factory.getOWLAnonymousIndividual(); //OWLClassAssertionAxiom clAssertion = factory.getOWLClassAssertionAxiom(headObject, eventIndividual); //builder.getOntologyManager().addAxiom(builder.getTarget(), clAssertion); OWLIndividual headIndividual = (OWLIndividual)headObject; OWLObjectPropertyAssertionAxiom assertion = factory.getOWLObjectPropertyAssertionAxiom(elementProperty, eventIndividual, headIndividual); // Finally, add the axiom to our ontology and save AddAxiom addAxiomChange = new AddAxiom(builder.getTarget(), assertion); builder.getOntologyManager().applyChange(addAxiomChange); return headObject; //TODO finish implementing individual case } else { throw new RuntimeException("Bad head object in participant: " + headObject); } } /** * @param builder * @param owlElements * @param factory * @param childBean * @return */ private OWLObject generateRestrictionClass(Owlbuilder builder, final Map<String, OWLObject> owlElements, ParticipantElement pe, PropertyTerm pt) throws Exception{ final OWLDataFactory factory = builder.getDataFactory(); //PropertyBean childProp = peb.getParentProperty(parentIndex); IRI childPropIRI = IRI.create(pt.getSourceId()); OWLObjectProperty childProperty = factory.getOWLObjectProperty(childPropIRI); OWLObject childElement = pe.generateOWL(builder, owlElements); int s = pe.getChildren().size(); if (s >0){ log.info("children size: " + s); } if (childElement instanceof OWLClassExpression){ final OWLClassExpression childClass = (OWLClassExpression)childElement; OWLClassExpression childPropertyRestriction = factory.getOWLObjectSomeValuesFrom(childProperty, childClass); log.info("Generated (child) Property restriction: " + childPropertyRestriction); return childPropertyRestriction; } else if (childElement instanceof OWLIndividual){ return childElement; } else { throw new RuntimeException("Bad child element: " + childElement); } } public OWLClassExpression generateTermOWL(TermBean tb, Owlbuilder builder, Map<String, OWLObject> elements){ final OWLDataFactory factory = builder.getDataFactory(); IRI termIRI; try { String termString = tb.checkIRIString(builder.getIRIManager()); if (elements.containsKey(termString)){ return (OWLClassExpression)elements.get(termString); } termIRI = IRI.create(termString); log.info("Creating OWL class: " + termIRI); OWLClass termClass = factory.getOWLClass(termIRI); builder.initializeMiscTermAndParents(termClass); elements.put(termString, termClass); return termClass; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } //TODO should these be merged? public void loadElements(AbstractConnection c) throws Exception{ log.debug("In load elements"); // special handling for head participation property if (bean.getElements().isEmpty()){ throw new RuntimeException("bean " + bean.getId() + " has no elements"); } log.debug("Should be listing elements here"); for (Integer id : bean.getElements()){ c.getPElement(id).cache(); final ParticipantElement pe = ParticipantElement.getElement(PElementBean.getCached(id)); log.debug(" loading element" + pe); log.debug(" id is" + pe.getId()); log.debug(" entity is " + pe.entity); elements.add(pe); } for (ParticipantElement pe : elements){ pe.resolveLinks(c); } } public void resolveElements() throws Exception{ assert elements.size() > 0 : "Participant: " + bean.getId() + " has no elements"; log.debug(" pb: " + this.getId() + " element count: " + elements.size()); assert bean.getHeadElement() > 0; assert bean.getProperty() > 0; assert PElementBean.getCached(bean.getHeadElement()) != null; //assert elements.contains(bean.getHeadElement()) : "Participant: " + bean.getId() + " has unregistered head element: " + bean.getHeadElement(); PElementBean head = PElementBean.getCached(bean.getHeadElement()); //headElement = ParticipantElement.getElement(head); } void processTaxon(Owlbuilder builder,OWLClass taxon){ final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ //add appropriate when figured out //log.info("Need to add taxon: " + taxon.getIRI()); //log.info("Defining Axioms"); manager.addAxioms(extracted, merged.getAxioms(taxon,org.semanticweb.owlapi.model.parameters.Imports.INCLUDED)); //log.info("Annotations"); Set<OWLAnnotationAssertionAxiom> taxonAnnotations = merged.getAnnotationAssertionAxioms(taxon.getIRI()); for (OWLAnnotationAssertionAxiom a : taxonAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.debug("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } } public void processAnatomy(Owlbuilder builder, OWLClass anatomyClass) { final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ log.info("Need to add anatomy: " + anatomyClass.getIRI()); Set<OWLClassAxiom> anatAxioms = merged.getAxioms(anatomyClass,org.semanticweb.owlapi.model.parameters.Imports.INCLUDED); manager.addAxioms(extracted, anatAxioms); Set<OWLAnnotationAssertionAxiom> anatAnnotations = merged.getAnnotationAssertionAxioms(anatomyClass.getIRI()); for (OWLAnnotationAssertionAxiom a : anatAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.info("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } builder.initializeMiscTermAndParents(anatomyClass); } public void processSubstrate(Owlbuilder builder, OWLClass substrateClass) { builder.initializeMiscTermAndParents(substrateClass); } public ParticipantElement getHeadElement(){ return headElement; } public PropertyTerm getProperty(){ return property; } // /** // * // * @param builder // * @param iri // */ // void processParticipantSubstrateForIndividual(Owlbuilder builder, IRI iri){ // final OWLOntology target = builder.getTarget(); // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // boolean substrate_duplicate = target.containsClassInSignature(iri); // if (!substrate_duplicate){ // boolean substrate_exists = merged.containsClassInSignature(iri); // if (substrate_exists){ // log.info("Found class in signature of merged ontology for: " + iri); // OWLClass substrateClass = factory.getOWLClass(iri); // processSubstrate(builder,substrateClass); // /** // * @param builder // * @param factory // * @param target // * @param manager // * @param partofProperty // * @param ind // */ // private void generateOWLforAnatomy(Owlbuilder builder, final OWLIndividual ind) { // final OWLDataFactory factory = builder.getDataFactory(); // OWLOntology target = builder.getTarget(); // OWLOntologyManager manager = builder.getOntologyManager(); // final OWLObjectProperty partofProperty = factory.getOWLObjectProperty(Vocabulary.partOfProperty); // if (bean.getAnatomyIri() != null){ // final OWLClass anatomyClass =processParticipantAnatomy(builder,IRI.create(bean.getAnatomyIri())); // log.info("anatomy is " + anatomyClass); // // and the taxon (anatomy w/o taxon should be flagged as a curation error // if (bean.getTaxon() != 0){ // if (bean.getTaxonIri() != null){ // // This will require some more attention - curation should be able to // // label the organisms because different parts of the same organism or // // the same part will be mentioned multiple times - this is why arachb // // uses individuals in the first place // log.info("taxon is " + bean.getTaxonIri()); // OWLIndividual organism = factory.getOWLAnonymousIndividual(); // OWLClass taxon = processParticipantTaxon(builder,IRI.create(bean.getTaxonIri())); // OWLClassAssertionAxiom taxonAssertion = factory.getOWLClassAssertionAxiom(taxon,organism); // log.warn("assert " + organism + " is " + taxon); // manager.addAxiom(target, taxonAssertion); // OWLObjectPropertyAssertionAxiom partofAssertion = // factory.getOWLObjectPropertyAssertionAxiom(partofProperty, organism, ind); // log.warn("assert " + organism + " part of " + ind); // manager.addAxiom(target, partofAssertion); // OWLClassAssertionAxiom anatomyAssertion = factory.getOWLClassAssertionAxiom(anatomyClass, ind); // log.warn("assert " + ind + " is " + anatomyClass); // manager.addAxiom(target, anatomyAssertion); // else { // final String msg = String.format("No taxon IRI available; id = %s",getId()); // else { // final String msg = String.format("No taxon specified; id = %s", getId()); // else{ // final String msg = String.format("No anatomy IRI available; id = %s",getId()); // /** // * // * @param builder // * @param iri // * @return // */ // OWLClass processParticipantTaxon(Owlbuilder builder,IRI iri){ // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // OWLOntology target = builder.getTarget(); // boolean taxon_duplicate = target.containsClassInSignature(iri); // if (!taxon_duplicate){ // if (merged.containsClassInSignature(iri)) // taxon in merged (so from NCBI) // return processNCBITaxon(builder, iri); // else // return processNonNCBITaxon(builder, iri); // else{ // OWLClass taxonClass = factory.getOWLClass(iri); // return taxonClass; // may not be right // /** // * // * @param builder // * @param iri // * @return class for anatomy // */ // OWLClass processParticipantAnatomy(Owlbuilder builder, IRI iri){ // final OWLOntology target = builder.getTarget(); // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // boolean anatomy_duplicate = target.containsClassInSignature(iri); // if (!anatomy_duplicate){ // boolean anatomy_exists = merged.containsClassInSignature(iri); // if (anatomy_exists){ // log.info("Found class in signature of merged ontology for: " + iri); // OWLClass anatomyClass = factory.getOWLClass(iri); // processAnatomyForIndividual(builder,anatomyClass); // return anatomyClass; // else{ // log.info("Did not find class in signature of merged ontology for: " + bean.getTaxonIri()); // return null; // else{ // OWLClass anatomyClass = factory.getOWLClass(iri); // return anatomyClass; // may not be right // OWLClass processParticipantTaxonForClass(Owlbuilder builder,IRI iri){ // final OWLOntology target = builder.getTarget(); // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // final OWLReasoner reasoner = builder.getPreReasoner(); // boolean taxon_duplicate = target.containsClassInSignature(iri); // if (!taxon_duplicate){ // boolean taxon_exists = merged.containsClassInSignature(iri); // if (taxon_exists){ // log.info("Found class in signature of merged ontology for: " + getTaxonIri()); // OWLClass taxonClass = factory.getOWLClass(iri); // final NodeSet<OWLClass> taxonParents = reasoner.getSuperClasses(taxonClass, false); // log.info("Node count = " + taxonParents.getNodes().size()); // Set<OWLClass>parentList = taxonParents.getFlattened(); // log.info("Flattened parent count = " + parentList.size()); // parentList.add(taxonClass); // for (OWLClass taxon : parentList){ // participantProcessTaxon(builder,taxon); // return taxonClass; // else{ // log.info("Did not find taxon class in signature of merged ontology for: " + getTaxonIri()); // final IRI taxonIri = IRI.create(getTaxonIri()); // final Map<IRI,Taxon> nonNCBITaxa = builder.getNonNCBITaxa(); // final OWLOntologyManager manager = builder.getOntologyManager(); // Taxon t = nonNCBITaxa.get(taxonIri); // if (t == null){ // log.info("Taxon IRI not found in declared non-NCBI taxa"); // final OWLClass taxonClass = factory.getOWLClass(iri); // if (t.getParentSourceId() != null){ // IRI parentIri = IRI.create(t.getParentSourceId()); // OWLClass parentClass = factory.getOWLClass(parentIri); // log.info("Parent IRI is " + parentIri.toString()); // OWLAxiom sc_ax = factory.getOWLSubClassOfAxiom(taxonClass, parentClass); // manager.addAxiom(target, sc_ax); // else{ // log.info("failed to find IRI of parent of " + getTaxonIri()); // if (t.getName() != null){ // OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(), // factory.getOWLLiteral(t.getName())); // OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(iri, labelAnno); // // Add the axiom to the ontology // manager.addAxiom(target,ax); // return taxonClass; // else{ // OWLClass taxonClass = factory.getOWLClass(iri); // return taxonClass; // may not be right // void participantProcessTaxon(Owlbuilder builder,OWLClass taxon){ // final OWLOntologyManager manager = builder.getOntologyManager(); // final OWLOntology merged = builder.getMergedSources(); // final OWLOntology extracted = builder.getTarget(); // if (true){ //add appropriate when figured out // log.info("Need to add taxon: " + taxon.getIRI()); // //log.info("Defining Axioms"); // manager.addAxioms(extracted, merged.getAxioms(taxon)); // //log.info("Annotations"); // Set<OWLAnnotationAssertionAxiom> taxonAnnotations = merged.getAnnotationAssertionAxioms(taxon.getIRI()); // for (OWLAnnotationAssertionAxiom a : taxonAnnotations){ // //log.info(" Annotation Axiom: " + a.toString()); // if (a.getAnnotation().getProperty().isLabel()){ // log.info("Label is " + a.getAnnotation().getValue().toString()); // manager.addAxiom(extracted, a); // /** // * // * @param builder // * @param iri // * @return // */ // OWLClass processParticipantTaxonForIndividual(Owlbuilder builder,IRI iri){ // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // OWLOntology target = builder.getTarget(); // boolean taxon_duplicate = target.containsClassInSignature(iri); // if (!taxon_duplicate){ // if (merged.containsClassInSignature(iri)) // taxon in merged (so from NCBI) // return processNCBITaxon(builder, iri); // else // return processNonNCBITaxon(builder, iri); // else{ // OWLClass taxonClass = factory.getOWLClass(iri); // return taxonClass; // may not be right // /** // * // * @param builder // * @param iri // * @return // */ // private OWLClass processNCBITaxon(Owlbuilder builder, IRI iri) { // log.info("Found class in signature of merged ontology for: " + iri); // final OWLDataFactory factory = builder.getDataFactory(); // final OWLReasoner reasoner = builder.getPreReasoner(); // OWLClass taxonClass = factory.getOWLClass(iri); // final NodeSet<OWLClass> taxonParents = reasoner.getSuperClasses(taxonClass, false); // log.info("Node count = " + taxonParents.getNodes().size()); // Set<OWLClass>parentList = taxonParents.getFlattened(); // log.info("Flattened parent count = " + parentList.size()); // parentList.add(taxonClass); // for (OWLClass taxon : parentList){ // processTaxon(builder,taxon); // return taxonClass; // void processTaxon(Owlbuilder builder,OWLClass taxon){ // final OWLOntologyManager manager = builder.getOntologyManager(); // final OWLOntology merged = builder.getMergedSources(); // final OWLOntology extracted = builder.getTarget(); // if (true){ //add appropriate when figured out // log.info("Need to add taxon: " + taxon.getIRI()); // //log.info("Defining Axioms"); // manager.addAxioms(extracted, merged.getAxioms(taxon)); // //log.info("Annotations"); // Set<OWLAnnotationAssertionAxiom> taxonAnnotations = merged.getAnnotationAssertionAxioms(taxon.getIRI()); // for (OWLAnnotationAssertionAxiom a : taxonAnnotations){ // //log.info(" Annotation Axiom: " + a.toString()); // if (a.getAnnotation().getProperty().isLabel()){ // log.info("Label is " + a.getAnnotation().getValue().toString()); // manager.addAxiom(extracted, a); // /** // * @param builder // * @param iri // * @return // */ // private OWLClass processNonNCBITaxon(Owlbuilder builder, IRI iri) { // final OWLDataFactory factory = builder.getDataFactory(); // final OWLOntology target = builder.getTarget(); // log.info("Did not find taxon class in signature of merged ontology for: " + bean.getTaxonIri()); // final IRI taxonIri = IRI.create(bean.getTaxonIri()); // final Map<IRI, Taxon> nonNCBITaxa = builder.getNonNCBITaxa(); // final OWLOntologyManager manager = builder.getOntologyManager(); // final Taxon t = nonNCBITaxa.get(taxonIri); // if (t == null){ // log.info("Taxon IRI not found in declared non-NCBI taxa"); // final OWLClass taxonClass = factory.getOWLClass(iri); // if (t.getParentSourceId() != null){ // IRI parentIri = IRI.create(t.getParentSourceId()); // OWLClass parentClass = factory.getOWLClass(parentIri); // log.info("Parent IRI is " + parentIri.toString()); // OWLAxiom sc_ax = factory.getOWLSubClassOfAxiom(taxonClass, parentClass); // manager.addAxiom(target, sc_ax); // else{ // log.info("failed to find IRI of parent of " + bean.getTaxonIri()); // if (t.getName() != null){ // OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(), // factory.getOWLLiteral(t.getName())); // OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(iri, labelAnno); // // Add the axiom to the ontology // manager.addAxiom(target,ax); // return taxonClass; // OWLClass processParticipantAnatomyForClass(Owlbuilder builder, IRI iri){ // final OWLOntology target = builder.getTarget(); // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // boolean anatomy_duplicate = target.containsClassInSignature(iri); // if (!anatomy_duplicate){ // boolean anatomy_exists = merged.containsClassInSignature(iri); // if (anatomy_exists){ // log.info("Found class in signature of merged ontology for: " + iri); // OWLClass anatomyClass = factory.getOWLClass(iri); // participantProcessAnatomy(builder,anatomyClass); // return anatomyClass; // else{ // log.info("Did not find class in signature of merged ontology for: " + getAnatomyIri()); // return null; // else{ // OWLClass taxonClass = factory.getOWLClass(iri); // return taxonClass; // may not be right // public void participantProcessAnatomy(Owlbuilder builder, OWLClass anatomyClass) { // final OWLOntologyManager manager = builder.getOntologyManager(); // final OWLOntology merged = builder.getMergedSources(); // final OWLOntology extracted = builder.getTarget(); // if (true){ // log.info("Need to add anatomy: " + anatomyClass.getIRI()); // Set<OWLClassAxiom> anatAxioms = merged.getAxioms(anatomyClass); // manager.addAxioms(extracted, anatAxioms); // Set<OWLAnnotationAssertionAxiom> anatAnnotations = // merged.getAnnotationAssertionAxioms(anatomyClass.getIRI()); // for (OWLAnnotationAssertionAxiom a : anatAnnotations){ // //log.info(" Annotation Axiom: " + a.toString()); // if (a.getAnnotation().getProperty().isLabel()){ // log.info("Label is " + a.getAnnotation().getValue().toString()); // manager.addAxiom(extracted, a); // builder.initializeMiscTermAndParents(anatomyClass); // public void processAnatomyForIndividual(Owlbuilder builder, OWLClass anatomyClass) { // final OWLOntologyManager manager = builder.getOntologyManager(); // final OWLOntology merged = builder.getMergedSources(); // final OWLOntology extracted = builder.getTarget(); // if (true){ // log.info("Need to add anatomy: " + anatomyClass.getIRI()); // Set<OWLClassAxiom> anatAxioms = merged.getAxioms(anatomyClass); // manager.addAxioms(extracted, anatAxioms); // Set<OWLAnnotationAssertionAxiom> anatAnnotations = // merged.getAnnotationAssertionAxioms(anatomyClass.getIRI()); // for (OWLAnnotationAssertionAxiom a : anatAnnotations){ // //log.info(" Annotation Axiom: " + a.toString()); // if (a.getAnnotation().getProperty().isLabel()){ // log.info("Label is " + a.getAnnotation().getValue().toString()); // manager.addAxiom(extracted, a); // builder.initializeMiscTermAndParents(anatomyClass); // void processParticipantSubstrateForClass(Owlbuilder builder, IRI iri){ // final OWLOntology target = builder.getTarget(); // final OWLOntology merged = builder.getMergedSources(); // final OWLDataFactory factory = builder.getDataFactory(); // boolean substrate_duplicate = target.containsClassInSignature(iri); // if (!substrate_duplicate){ // boolean substrate_exists = merged.containsClassInSignature(iri); // if (substrate_exists){ // log.info("Found class in signature of merged ontology for: " + iri); // OWLClass substrateClass = factory.getOWLClass(iri); // processSubstrate(builder,substrateClass); // public void processSubstrate(Owlbuilder builder, OWLClass substrateClass) { // builder.initializeMiscTermAndParents(substrateClass); public int getId(){ return bean.getId(); } public int getTaxon(){ return bean.getTaxon(); } public int getSubstrate(){ return bean.getSubstrate(); } public int getAnatomy(){ return bean.getAnatomy(); } public String getQuantification(){ return bean.getQuantification(); } public String getPublicationTaxon(){ return bean.getPublicationTaxon(); } public String getLabel(){ return bean.getLabel(); } public String getPublicationAnatomy(){ return bean.getPublicationAnatomy(); } public String getPublicationSubstrate(){ return bean.getPublicationSubstrate(); } public String getTaxonIri(){ return bean.getTaxonIri(); } public String getSubstrateIri(){ return bean.getSubstrateIri(); } public String getAnatomyIri(){ return bean.getAnatomyIri(); } public String getGeneratedId(){ return bean.getGeneratedId(); } public void setGeneratedId(String s){ bean.setGeneratedId(s); } }
package org.bitvector.microservice2; import akka.actor.AbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.pf.ReceiveBuilder; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.UndertowOptions; import io.undertow.server.HttpServerExchange; import io.undertow.server.RoutingHandler; import io.undertow.server.handlers.Cookie; import io.undertow.util.FlexBase64; import io.undertow.util.Headers; import io.undertow.util.Methods; import io.undertow.util.StatusCodes; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Objects; public class HttpActor extends AbstractActor { private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private SettingsImpl settings = Settings.get(getContext().system()); private Undertow server; private Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); private SecurityManager securityManager = factory.getInstance(); public HttpActor() { receive(ReceiveBuilder .match(Start.class, this::doStart) .match(Stop.class, this::doStop) .matchAny(obj -> log.error("HttpActor received unknown message " + obj.toString())) .build() ); } private void doStart(Start msg) { log.info("HttpActor received start"); SecurityUtils.setSecurityManager(securityManager); ProductCtrl productCtrl = new ProductCtrl(getContext()); RoutingHandler rootHandler = Handlers.routing() .add(Methods.GET, "/logout", exchange -> exchange.dispatch(this::doLogout)) .add(Methods.GET, "/login", exchange -> exchange.dispatch(this::doLogin)) .addAll(productCtrl.getRoutingHandler()); server = Undertow.builder() .addHttpListener(settings.LISTEN_PORT(), settings.LISTEN_ADDRESS(), rootHandler) .setServerOption(UndertowOptions.ENABLE_HTTP2, true) .build(); try { server.start(); } catch (RuntimeException e) { log.error("Failed to create HTTP actor: " + e.getMessage()); getContext().stop(self()); } } private void doStop(Stop msg) { log.info("HttpActor received stop"); server.stop(); } private void doLogin(HttpServerExchange exchange) { try { // Header value looks like "Basic c3RldmVsOmZ1Y2tvZmY=" String[] authorizationHeader = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION).split(" "); if (!Objects.equals(authorizationHeader[0].toLowerCase().trim(), Headers.BASIC.toString().toLowerCase())) { throw new Exception("Bad Authentication Scheme"); } // Decoded credentials look like "stevel:fuckoff" ByteBuffer buffer = FlexBase64.decode(authorizationHeader[1]); String[] credentials = new String(buffer.array(), Charset.forName("utf-8")).split(":"); // Send to Apache Shiro for assertion Subject currentUser = SecurityUtils.getSubject(); if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(credentials[0].trim(), credentials[1].trim()); token.setRememberMe(true); currentUser.login(token); } // All forms of failure are some Exception. Make it here and you are logged in and get a JWT Cookie. String jwt = Jwts.builder() .setSubject(currentUser.getPrincipal().toString()) .signWith(SignatureAlgorithm.HS512, settings.SECRET_KEY()) .compact(); exchange.getResponseHeaders().put(Headers.SET_COOKIE, "access_token=" + jwt + "; " + "HttpOnly; "); exchange.setStatusCode(StatusCodes.OK); exchange.getResponseSender().close(); } catch (Exception e) { exchange.setStatusCode(StatusCodes.UNAUTHORIZED); exchange.getResponseHeaders().put(Headers.WWW_AUTHENTICATE, Headers.BASIC.toString() + " " + "realm=\"Login Required\""); exchange.getResponseSender().close(); } } private void doLogout(HttpServerExchange exchange) { try { Cookie accessToken = exchange.getRequestCookies().get("access_token"); Claims body = Jwts.parser() .setSigningKey(settings.SECRET_KEY()) .parseClaimsJws(accessToken.getValue()) .getBody(); // Subject currentUser = SecurityUtils.getSubject(); // currentUser.logout(); } catch (Exception e) { log.error("Exception caught: " + e.getMessage()); } } public static class Start implements Serializable { } public static class Stop implements Serializable { } }
package org.bricolages.streaming; import org.bricolages.streaming.filter.*; import org.bricolages.streaming.event.*; import org.bricolages.streaming.s3.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import lombok.*; import lombok.extern.slf4j.Slf4j; @RequiredArgsConstructor @Slf4j public class Preprocessor implements EventHandlers { final EventQueue eventQueue; final LogQueue logQueue; final S3Agent s3; final ObjectMapper mapper; final ObjectFilterFactory filterFactory; public void run() throws IOException { log.info("server started"); trapSignals(); try { while (!isTerminating()) { // FIXME: insert sleep on empty result try { handleEvents(); eventQueue.flushDelete(); } catch (SQSException ex) { safeSleep(5); } } } catch (ApplicationAbort ex) { // ignore } eventQueue.flushDeleteForce(); log.info("application is gracefully shut down"); } public void runOneshot() throws Exception { trapSignals(); try { while (!isTerminating()) { val empty = handleEvents(); if (empty) break; } } catch (ApplicationAbort ex) { // ignore } eventQueue.flushDeleteForce(); } public boolean processUrl(SourceLocator src, BufferedWriter out) { val mapResult = mapper.map(src.toString()); if (mapResult == null) { log.warn("S3 object could not mapped: {}", src); return false; } String streamName = mapResult.getStreamName(); S3ObjectLocation dest = mapResult.getDestLocation(); FilterResult result = new FilterResult(src.toString(), dest.urlString()); try { ObjectFilter filter = filterFactory.load(streamName); try (BufferedReader r = src.open()) { filter.apply(r, out, src.toString(), result); } log.debug("src: {}, dest: {}, in: {}, out: {}", src.toString(), dest.urlString(), result.inputRows, result.outputRows); return true; } catch (IOException ex) { log.error("src: {}, error: {}", src.toString(), ex.getMessage()); return false; } } boolean handleEvents() { boolean empty = true; for (val event : eventQueue.poll()) { log.debug("processing message: {}", event.getMessageBody()); event.callHandler(this); empty = false; } return empty; } @Override public void handleUnknownEvent(UnknownEvent event) { // FIXME: notify? log.warn("unknown message: {}", event.getMessageBody()); eventQueue.deleteAsync(event); } @Override public void handleShutdownEvent(ShutdownEvent event) { // Use sync delete to avoid duplicated shutdown eventQueue.delete(event); initiateShutdown(); } Thread mainThread; boolean isTerminating = false; void trapSignals() { mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { initiateShutdown(); waitMainThread(); } }); } void initiateShutdown() { log.info("initiate shutdown; mainThread={}", mainThread); this.isTerminating = true; if (mainThread != null) { mainThread.interrupt(); } } boolean isTerminating() { if (isTerminating) return true; if (mainThread.isInterrupted()) { this.isTerminating = true; return true; } else { return false; } } void waitMainThread() { if (mainThread == null) return; try { log.info("waiting main thread..."); mainThread.join(); } catch (InterruptedException ex) { // ignore } } void safeSleep(int sec) { try { Thread.sleep(sec * 1000); } catch (InterruptedException ex) { this.isTerminating = true; } } @Autowired FilterResultRepository repos; @Autowired DataStreamRepository streamRepos; @Autowired StreamBundleRepository streamBundleRepos; public void logNewStream(long streamId, String streamName) { log.warn("new stream: stream_id={}, stream_name={}", streamId, streamName); } public void logNewStreamBundle(long streamId, String streamPrefix) { log.warn("new stream bundle: stream_id={}, stream_prefix={}", streamId, streamPrefix); } public void logNotMappedObject(String src) { log.warn("S3 object could not mapped: {}", src); } @Override public void handleS3Event(S3Event event) { log.debug("handling URL: {}", event.getLocation().toString()); S3ObjectLocation src = event.getLocation(); String srcBucket = src.bucket(); val mapResult = mapper.map(src.urlString()); if (mapResult == null) { // object mapping failed; this means invalid event or bad configuration. // We should remove invalid events from queue and // we must fix bad configuration by hand. // We cannot resolve latter case automatically, optimize for former case. logNotMappedObject(src.toString()); eventQueue.deleteAsync(event); return; } String streamName = mapResult.getStreamName(); S3ObjectLocation dest = mapResult.getDestLocation(); DataStream stream = streamRepos.findStream(streamName); if (stream == null) { try { // create new stream with disabled (to avoid to produce non preprocessed output) stream = new DataStream(streamName); streamRepos.save(stream); logNewStream(stream.getId(), streamName); } catch (DataIntegrityViolationException ex) { stream = streamRepos.findStream(streamName); } log.info("new data packet for unconfigured stream: stream_id={}, stream_name={}, url={}", stream.getId(), streamName, src); } if (stream.doesDefer()) { // Processing is temporary disabled; process objects later return; } String streamPrefix = mapResult.getStreamPrefix(); StreamBundle streamBundle = streamBundleRepos.findStreamBundle(stream, srcBucket, streamPrefix); if (streamBundle == null) { try { streamBundle = new StreamBundle(stream, srcBucket, streamPrefix); streamBundleRepos.save(streamBundle); logNewStreamBundle(stream.getId(), streamPrefix); } catch (DataIntegrityViolationException ex) { streamBundle = streamBundleRepos.findStreamBundle(stream, srcBucket, mapResult.getStreamPrefix()); } } if (stream.doesDiscard()) { // Just ignore without processing, do not keep SQS messages. log.info("discard event: {}", event.getLocation().toString()); eventQueue.deleteAsync(event); return; } FilterResult result = new FilterResult(src.urlString(), dest.urlString()); try { repos.save(result); ObjectFilter filter = filterFactory.load(streamName); val srcLocator = new S3ObjectSourceLocator(s3, src); S3ObjectMetadata obj = applyFilter(filter, srcLocator, dest, result, streamName); log.debug("src: {}, dest: {}, in: {}, out: {}", src.urlString(), dest.urlString(), result.inputRows, result.outputRows); result.succeeded(); repos.save(result); if (!event.doesNotDispatch() && !stream.doesNotDispatch()) { logQueue.send(new FakeS3Event(obj)); result.dispatched(); repos.save(result); } eventQueue.deleteAsync(event); } catch (S3IOException | IOException | ConfigError ex) { log.error("src: {}, error: {}", src.urlString(), ex.getMessage()); result.failed(ex.getMessage()); repos.save(result); } } public S3ObjectMetadata applyFilter(ObjectFilter filter, SourceLocator src, S3ObjectLocation dest, FilterResult result, String streamName) throws S3IOException, IOException { try (S3Agent.Buffer buf = s3.openWriteBuffer(dest, streamName)) { try (BufferedReader r = src.open()) { filter.apply(r, buf.getBufferedWriter(), src.toString(), result); } return buf.commit(); } } }
package org.deeplearning4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.models.featuredetectors.rbm.RBM; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.OutputPreProcessor; import org.deeplearning4j.nn.conf.preprocessor.BinomialSamplingPreProcessor; import org.deeplearning4j.nn.layers.OutputLayer; import org.deeplearning4j.nn.layers.factory.LayerFactories; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.spark.impl.multilayer.SparkDl4jMultiLayer; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.nd4j.linalg.api.activation.Activations; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; public class DistributedExample { @Option(name="--batchSize") private int batchSize = 10000; @Option(name = "--frameSize") private int frameSize = 600000; @Option(name = "--masterUrl",required = true) private String masterUrl; @Option(name = "--iterations") private int iterations = 5; @Option(name = "--output") private String outputPath = "mnist.ser"; @Option(name = "--avgiteration") private boolean averageEachIteration = false; private static Logger log = LoggerFactory.getLogger(DistributedExample.class); public DistributedExample(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { parser.printUsage(System.err); log.error("Unable to parse args",e); } } public static void main(String[] args) throws Exception { DistributedExample app = new DistributedExample(args); // set to test mode SparkConf sparkConf = new SparkConf().set("spark.executor.extraJavaOptions","-Ddtype=float") .setMaster(app.masterUrl).set("spark.akka.frameSize", String.valueOf(app.frameSize)) .set(SparkDl4jMultiLayer.AVERAGE_EACH_ITERATION, String.valueOf(app.averageEachIteration)) .setAppName("mnist"); System.out.println("Setting up Spark Context..."); JavaSparkContext sc = new JavaSparkContext(sparkConf); Map<Integer,OutputPreProcessor> preProcessorMap = new HashMap<>(); preProcessorMap.put(0,new BinomialSamplingPreProcessor()); preProcessorMap.put(1,new BinomialSamplingPreProcessor()); preProcessorMap.put(2,new BinomialSamplingPreProcessor()); MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().iterations(app.iterations).momentum(0.5) .l2(2e-4).regularization(true).optimizationAlgo(OptimizationAlgorithm.ITERATION_GRADIENT_DESCENT) .nIn(784).nOut(10).layerFactory(LayerFactories.getFactory(RBM.class)).batchSize(app.batchSize).momentumAfter(Collections.singletonMap(20,0.9)) .list(4).hiddenLayerSizes(600, 500, 400) .override(new NeuralNetConfiguration.ConfOverride() { @Override public void override(int i, NeuralNetConfiguration.Builder builder) { if (i == 3) { builder.activationFunction(Activations.softMaxRows()); builder.layerFactory(LayerFactories.getFactory(OutputLayer.class)); builder.lossFunction(LossFunctions.LossFunction.MCXENT); } } }).build(); System.out.println("Initializing network"); SparkDl4jMultiLayer master = new SparkDl4jMultiLayer(sc,conf); DataSet d = new MnistDataSetIterator(60000,60000).next(); List<DataSet> next = new ArrayList<>(); for(int i = 0; i < d.numExamples(); i++) next.add(d.get(i).copy()); Collections.shuffle(next); JavaRDD<DataSet> data = sc.parallelize(next); MultiLayerNetwork network = master.fitDataSet(data); Evaluation evaluation = new Evaluation(); evaluation.eval(d.getLabels(),network.output(d.getFeatureMatrix())); System.out.println("Averaged once " + evaluation.stats()); String json = conf.toJson(); FileUtils.writeStringToFile(new File(app.outputPath + ".json"),json); FileUtils.writeStringToFile(new File(app.outputPath + ".params"), StringUtils.join(network.params().data().asDouble(),',')); } }
package org.dita.dost.writer; import static org.dita.dost.util.Constants.*; import static org.dita.dost.writer.DitaWriter.*; import static org.dita.dost.reader.ChunkMapReader.*; import static org.dita.dost.module.GenMapAndTopicListModule.*; import static org.dita.dost.util.FileUtils.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.Stack; import org.dita.dost.exception.DITAOTException; import org.dita.dost.exception.DITAOTXMLErrorHandler; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.Content; import org.dita.dost.util.DITAAttrUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.Job; import org.dita.dost.util.StringUtils; import org.dita.dost.util.TopicIdParser; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; /** * ChunkTopicParser class, writing chunking content into relative topic files * and then update list. Not reusable and not thread-safe. * * <p>TODO: Refactor to be a SAX filter.</p> */ public final class ChunkTopicParser extends AbstractXMLWriter { private static final String ATTR_CHUNK_VALUE_SELECT_BRANCH = "select-branch"; private static final String ATTR_CHUNK_VALUE_TO_CONTENT = "to-content"; private static final String ATTR_CHUNK_VALUE_SELECT_TOPIC = "select-topic"; private static final String ATTR_CHUNK_VALUE_SELECT_DOCUMENT = "select-document"; private LinkedHashMap<String,String> changeTable = null; private Hashtable<String,String> conflictTable = null; private Element elem = null; private Element topicDoc = null; private boolean separate = false; private String filePath = null; private String currentParsingFile = null; private String outputFile = null; private final Stack<String> outputFileNameStack; private String targetTopicId = null; private String selectMethod = ATTR_CHUNK_VALUE_SELECT_DOCUMENT; //flag whether output the nested nodes private boolean include = false; private boolean skip = false; private int includelevel = 0; private int skipLevel = 0; private final Set<String> topicSpecSet; private boolean startFromFirstTopic = false; private final XMLReader reader; private Writer output = null; private final Stack<Writer> fileWriterStack; private final Stack<Element> stubStack; //stub is used as the anchor to mark where to insert generated child topicref inside current topicref private Element stub = null; //siblingStub is similar to stub. The only different is it is used to insert generated topicref sibling to current topicref private Element siblingStub = null; private String ditaext = null; private Set<String> topicID; private final Set<String> copyto; private final Set<String> copytoSource; private final Map<String,String> copytotarget2source; private Map<String, String> currentParsingFileTopicIDChangeTable; private final Random random; private static final String ditaarchNSValue = "http://dita.oasis-open.org/architecture/2005/"; /** * Constructor. */ public ChunkTopicParser() { super(); topicSpecSet = new HashSet<String>(INT_16); fileWriterStack = new Stack<Writer>(); stubStack = new Stack<Element>(); outputFileNameStack = new Stack<String>(); topicID = new HashSet<String>(); copyto = new HashSet<String>(); copytoSource = new HashSet<String>(); copytotarget2source = new HashMap<String,String>(); try { reader = StringUtils.getXMLReader(); reader.setContentHandler(this); reader.setProperty(LEXICAL_HANDLER_PROPERTY,this); reader.setFeature(FEATURE_NAMESPACE_PREFIX, true); reader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true); reader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } random = new Random(); } @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { if (include) { try { output.write(StringUtils.escapeXML(ch,start, length)); } catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } @Override public void comment(final char[] ch, final int start, final int length) throws SAXException { super.comment(ch, start, length); } @Override public void endDocument() throws SAXException { include = false; skip = false; } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (skip && skipLevel > 0) { skipLevel } else if (skip) { include = true; skip = false; skipLevel = 0; } if(include){ try{ includelevel if(includelevel >= 0){ // prevent adding </dita> into output writeEndElement(output, qName); } if (includelevel == 0 && !ATTR_CHUNK_VALUE_SELECT_DOCUMENT.equals(selectMethod)){ include = false; } if (topicSpecSet.contains(qName) && separate && !fileWriterStack.isEmpty()){ // if it is end of topic and separate is true try { output.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } output = fileWriterStack.pop(); outputFile = outputFileNameStack.pop(); stub.getParentNode().removeChild(stub); stub = stubStack.pop(); } }catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } @Override public void endPrefixMapping(final String prefix) throws SAXException { super.endPrefixMapping(prefix); } @Override public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException { if (include) { try { output.write(ch, start, length); } catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } @Override public void processingInstruction(final String target, final String data) throws SAXException { if(include || PI_WORKDIR_TARGET.equalsIgnoreCase(target) || PI_WORKDIR_TARGET_URI.equals(target) || PI_PATH2PROJ_TARGET.equalsIgnoreCase(target)){ try { writeProcessingInstruction(output, target, data); } catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } @Override public void setContent(final Content content) { // NOOP } @Override public void skippedEntity(final String name) throws SAXException { if(include){ try { output.write(StringUtils.getEntity(name)); } catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } } @Override public void startDocument() throws SAXException { //dontWriteDita = true; //difference between to-content & select-topic if (ATTR_CHUNK_VALUE_SELECT_DOCUMENT.equals(selectMethod)){ //currentParsingFile can never equal outputFile except when chunk="to-content" //is set at map level //TODO former is set and line 606(895) and the later is set at line 838 if((currentParsingFile).equals(outputFile)){ // if current file serves as root of new chunk // include will be set to true in startDocument() // in order to copy PIs and <dita> element // otherwise, if current file is copied to other file // do not copy PIs and <dita>element include = true; skip = false; skipLevel = 0; }else{ include = false; startFromFirstTopic = true; skip = false; skipLevel = 0; } } } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); final String idValue = atts.getValue(ATTRIBUTE_NAME_ID); if (skip && skipLevel > 0) { skipLevel++; } try{ if(classValue!=null && TOPIC_TOPIC.matches(classValue)){ topicSpecSet.add(qName); final String id = atts.getValue(ATTRIBUTE_NAME_ID); //search node by id. final Element element = DITAAttrUtils.getInstance(). searchForNode(topicDoc, id, ATTRIBUTE_NAME_ID, TOPIC_TOPIC.matcher); //only by topic if (separate && include && !ATTR_CHUNK_VALUE_SELECT_TOPIC.equals(selectMethod)){ //chunk="by-topic" and next topic element found fileWriterStack.push(output); outputFileNameStack.push(outputFile); //need generate new file based on new topic id String newFileName = FileUtils.resolveFile(filePath, idValue + ditaext); if(StringUtils.isEmptyString(idValue) || FileUtils.fileExists(newFileName)) { final String t = newFileName; newFileName = FileUtils.resolveFile(filePath, generateFilename()); conflictTable.put(newFileName, t); } outputFile = newFileName; output = new OutputStreamWriter( new FileOutputStream(newFileName) ,UTF8); //write xml header and workdir PI to the new generated file writeStartDocument(output); if(OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS)==-1) { writeProcessingInstruction(output, PI_WORKDIR_TARGET, filePath); }else{ writeProcessingInstruction(output, PI_WORKDIR_TARGET, UNIX_SEPARATOR + filePath); } writeProcessingInstruction(output, PI_WORKDIR_TARGET_URI, new File(filePath).toURI().toString()); changeTable.put(newFileName,newFileName); if(idValue != null){ changeTable.put(currentParsingFile+SHARP+idValue, newFileName+SHARP+idValue); }else{ changeTable.put(currentParsingFile, newFileName); } //create a new child element //in separate case elem is equals to parameter //element in separateChunk(Element element) final Element newChild = elem.getOwnerDocument() .createElement(MAP_TOPICREF.localName); newChild.setAttribute(ATTRIBUTE_NAME_HREF, FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,newFileName)); newChild.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_TOPICREF.toString()); newChild.setAttribute(ATTRIBUTE_NAME_XTRF, ATTR_XTRF_VALUE_GENERATED); createTopicMeta(element, newChild); if(stub!=null){ if (includelevel == 0 && siblingStub != null){ //if it is the following sibling topic to the first topic in ditabase //The first topic will not enter the logic at here because when meeting //with first topic in ditabase, the include value is false siblingStub.getParentNode().insertBefore(newChild, siblingStub); }else{ stub.getParentNode().insertBefore(newChild,stub); } //<element> // <newchild/> // <stub/> // <stub/> //</element> //<siblingstub/> stubStack.push(stub); stub = (Element)stub.cloneNode(false); newChild.appendChild(stub); } } if(include && ATTR_CHUNK_VALUE_SELECT_TOPIC.equals(selectMethod)){ //if select method is "select-topic" and //current topic is the nested topic in //target topic-->skip it. include = false; skipLevel = 1; skip = true; // Fix: no need to close the tag, just skip the nested topic. //output.write("</"+qName+">"); }else if(include){ //if select method is "select-document" or "select-branch" // and current topic is the nested topic in target topic. // if file name has been changed, add an entry in changeTable if(!currentParsingFile.equals(outputFile)){ if(idValue != null){ changeTable.put(currentParsingFile+SHARP+idValue, outputFile+SHARP+idValue); }else{ changeTable.put(currentParsingFile, outputFile); } } } else if(skip) { skipLevel = 1; } else if(!include && idValue!=null && (idValue.equals(targetTopicId) || startFromFirstTopic)){ //if the target topic has not been found and //current topic is the target topic include = true; includelevel = 0; skip = false; skipLevel = 0; startFromFirstTopic = false; if(!currentParsingFile.equals(outputFile)){ changeTable.put(currentParsingFile+SHARP+idValue, outputFile+SHARP+idValue); } } } if(include){ includelevel++; final AttributesImpl resAtts = new AttributesImpl(atts); for(int i = 0; i < resAtts.getLength(); i++){ final String attrName = resAtts.getQName(i); String attrValue = resAtts.getValue(i); if(ATTRIBUTE_NAME_ID.equals(attrName) && TOPIC_TOPIC.matches(classValue)){ //change topic @id if there are conflicts. if(topicID.contains(attrValue)){ final String oldAttrValue = attrValue; attrValue = generateID(); topicID.add(attrValue); String tmpVal = changeTable.get(currentParsingFile+SHARP+idValue); if (tmpVal!=null && tmpVal.equalsIgnoreCase(outputFile+SHARP+idValue)){ changeTable.put(currentParsingFile+SHARP+idValue, outputFile+SHARP+attrValue); } tmpVal = changeTable.get(currentParsingFile); if (tmpVal!=null && tmpVal.equalsIgnoreCase(outputFile+SHARP+idValue)){ changeTable.put(currentParsingFile, outputFile+SHARP+attrValue); } currentParsingFileTopicIDChangeTable.put(oldAttrValue, attrValue); } else { topicID.add(attrValue); } } String value = attrValue; if(ATTRIBUTE_NAME_HREF.equals(attrName)){ //update @href value if(checkHREF(resAtts)){ // if current @href value needs to be updated String relative = FileUtils.getRelativePath(outputFile,currentParsingFile); if (conflictTable.containsKey(outputFile)){ final String realoutputfile = conflictTable.get(outputFile); relative = FileUtils.getRelativePath(realoutputfile,currentParsingFile); } if(attrValue.startsWith(SHARP)){ // if @href refers to a location inside current parsing file // update @href to point back to current file // if the location is moved to chunk, @href will be update again // to the new location. value = relative+attrValue; }else if (relative.indexOf(SLASH)!=-1){ // if new file is not under the same directory with current file // add path information to the @href value relative = relative.substring(0,relative.lastIndexOf(SLASH)); value = FileUtils.resolveTopic(relative,attrValue); }else{ // if new file is under the same directory with current file // do not update the @href value } }else{ // if current @href value does not need to be updated } } resAtts.setValue(i, value); } if (classValue != null && TOPIC_TOPIC.matches(classValue) && resAtts.getValue("xmlns:ditaarch") == null){ //if there is none declaration for ditaarch namespace, //processor need to add it XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAMESPACE_PREFIX_DITAARCHVERSION, ditaarchNSValue); } writeStartElement(output, qName, resAtts); } }catch(final Exception e){ logger.logError(e.getMessage(), e) ; } } /** * Convenience method to write document start. */ private void writeStartDocument(final Writer output) throws IOException { output.write(XML_HEAD); } /** * Convenience method to write an end element. * * @param name element name */ private void writeStartElement(final Writer output, final String name, final Attributes atts) throws IOException { output.write(LESS_THAN); output.write(name); for (int i = 0; i < atts.getLength(); i++) { writeAttribute(output, atts.getQName(i), atts.getValue(i)); } output.write(GREATER_THAN); } /** * Convenience method to write an attribute. * * @param name attribute name * @param value attribute value */ private void writeAttribute(final Writer output, final String name, final String value) throws IOException { output.write(STRING_BLANK); output.write(name); output.write(EQUAL); output.write(QUOTATION); output.write(StringUtils.escapeXML(value)); output.write(QUOTATION); } /** * Convenience method to write an end element. * * @param name element name */ private void writeEndElement(final Writer output, final String name) throws IOException { output.write(LESS_THAN); output.write(SLASH); output.write(name); output.write(GREATER_THAN); } /** * Convenience method to write a processing instruction. * * @param name PI name * @param value PI value, may be {@code null} */ private void writeProcessingInstruction(final Writer output, final String name, final String value) throws IOException { output.write(LESS_THAN); output.write(QUESTION); output.write(name); if (value != null) { output.write(STRING_BLANK); output.write(value); } output.write(QUESTION); output.write(GREATER_THAN); } /** * Generate ID. * * @return generated ID */ private String generateID() { return "unique_" + random.nextInt(Integer.MAX_VALUE); } @Override public void write(final String filename) throws DITAOTException { // pass map's directory path filePath = filename; //not chunk "by-topic" if(!separate){ //TODO create the initial output output = new StringWriter(); processChunk(elem,null); }else{ //chunk "by-topic" separateChunk(elem); } if(!copyto.isEmpty()){ updateList(); // now only update copyto list and does not update any topic ditamap ditamaptopic list } } private void updateList(){ try{ // XXX: This may have to use new File(FileUtils.resolveFile(filePath,FILE_NAME_DITA_LIST_XML)).getParent() final Job job = new Job(new File(filePath)); final Set<String> copytosourcelist = job.getSet(COPYTO_SOURCE_LIST); final Set<String> copytotarget2sourcemaplist = job.getSet(COPYTO_TARGET_TO_SOURCE_MAP_LIST); //in the following, all the 4 arrays are updated according to the set copyto and //map copytotarget2source. // //copy all the file name in copytosourcelist to a new set for(final String source:copytosourcelist){ copytoSource.add(source); } //copy all the copytotarget2sourcemaplist to a new hashmap for(final String target2source:copytotarget2sourcemaplist){ if(target2source.indexOf(EQUAL)!=-1) { copytotarget2source.put(target2source.substring(0, target2source.indexOf(EQUAL)), target2source.substring(target2source.indexOf(EQUAL)-1)); } } //in the case of chunk='to-content' and copy-to='*.dita' //the @href value are added in fullditatopic and fullditamapandtopic, //while they are not supposed to be contained, so should be be removed job.setSet(COPYTO_SOURCE_LIST, copytoSource); job.setMap(COPYTO_TARGET_TO_SOURCE_MAP_LIST, copytotarget2source); job.write(); }catch (final Exception e){ /*logger.logWarn(e.toString());*/ logger.logError(e.getMessage(), e) ; } finally { if (output != null) { try { output.close(); } catch (final IOException e) { logger.logError(e.getMessage(), e) ; } } } } private void separateChunk(final Element element) { final String hrefValue = element.getAttribute(ATTRIBUTE_NAME_HREF); final String copytoValue = element.getAttribute(ATTRIBUTE_NAME_COPY_TO); final String scopeValue = element.getAttribute(ATTRIBUTE_NAME_SCOPE); String parseFilePath = null; Writer tempOutput = null; final String chunkValue = element.getAttribute(ATTRIBUTE_NAME_CHUNK); final String processRoleValue = element.getAttribute(ATTRIBUTE_NAME_PROCESSING_ROLE); boolean dotchunk = false; if (copytoValue.length() != 0 && !chunkValue.contains(ATTR_CHUNK_VALUE_TO_CONTENT)){ if (getFragment(hrefValue) != null){ parseFilePath = copytoValue + SHARP + getFragment(hrefValue); }else{ parseFilePath = copytoValue; } }else{ parseFilePath = hrefValue; } // if @copy-to is processed in chunk module, the list file needs to be updated. // Because @copy-to should be included in fulltopiclist, and the source of coyy-to should be excluded in fulltopiclist. if(copytoValue.length() != 0 && chunkValue.contains(ATTR_CHUNK_VALUE_TO_CONTENT)){ copyto.add(copytoValue); if(getFragment(hrefValue) != null){ copytoSource.add(stripFragment(hrefValue)); copytotarget2source.put(copytoValue, stripFragment(hrefValue)); }else{ copytoSource.add(hrefValue); copytotarget2source.put(copytoValue,hrefValue); } } try { if (!StringUtils.isEmptyString(parseFilePath) && !ATTR_SCOPE_VALUE_EXTERNAL.equalsIgnoreCase(scopeValue) && !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue)) { // if the path to target file make sense currentParsingFile = FileUtils.resolveFile(filePath,parseFilePath); String outputFileName = null; /* * FIXME: we have code flaws here, references in ditamap need to be updated to * new created file. */ String id = null; String firstTopicID = null; if (getFragment(parseFilePath) != null) { id = getFragment(parseFilePath); if (chunkValue.contains(ATTR_CHUNK_VALUE_SELECT_BRANCH)) { outputFileName = FileUtils.resolveFile(filePath, id + ditaext); targetTopicId = id; startFromFirstTopic = false; selectMethod = ATTR_CHUNK_VALUE_SELECT_BRANCH; } else if (chunkValue.contains(ATTR_CHUNK_VALUE_SELECT_DOCUMENT)) { firstTopicID = this.getFirstTopicId(FileUtils.resolveFile(filePath, parseFilePath)); topicDoc = DITAAttrUtils.getInstance().getTopicDoc(FileUtils.resolveFile(filePath, parseFilePath)); if (!StringUtils.isEmptyString(firstTopicID)) { outputFileName = FileUtils.resolveFile(filePath, firstTopicID + ditaext); targetTopicId = firstTopicID; } else { outputFileName = currentParsingFile + FILE_EXTENSION_CHUNK; dotchunk = true; targetTopicId = null; } selectMethod = ATTR_CHUNK_VALUE_SELECT_DOCUMENT; } else { outputFileName = FileUtils.resolveFile(filePath, id + ditaext); targetTopicId = id; startFromFirstTopic = false; selectMethod = ATTR_CHUNK_VALUE_SELECT_TOPIC; } } else { firstTopicID = this.getFirstTopicId(FileUtils.resolveFile(filePath, parseFilePath)); topicDoc = DITAAttrUtils.getInstance().getTopicDoc(FileUtils.resolveFile(filePath, parseFilePath)); if (!StringUtils.isEmptyString(firstTopicID)) { outputFileName = FileUtils.resolveFile(filePath, firstTopicID + ditaext); targetTopicId = firstTopicID; } else { outputFileName = currentParsingFile + FILE_EXTENSION_CHUNK; dotchunk = true; targetTopicId = null; } selectMethod = ATTR_CHUNK_VALUE_SELECT_DOCUMENT; } if (copytoValue.length() != 0){ // use @copy-to value as the new file name outputFileName = FileUtils.resolveFile(filePath,copytoValue); } if (FileUtils.fileExists(outputFileName)) { final String t = outputFileName; outputFileName = FileUtils.resolveFile(filePath, generateFilename()); conflictTable.put(outputFileName, t); dotchunk = false; } tempOutput = output; output = new OutputStreamWriter(new FileOutputStream( outputFileName), UTF8); outputFile = outputFileName; if (!dotchunk) { changeTable.put(FileUtils.resolveTopic(filePath, parseFilePath), outputFileName + (id == null ? "" : SHARP+id)); //new generated file changeTable.put(outputFileName, outputFileName); } //change the href value if (StringUtils.isEmptyString(firstTopicID)) { element.setAttribute(ATTRIBUTE_NAME_HREF, FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,outputFileName) + (id == null ? "" : SHARP+id)); } else { element.setAttribute(ATTRIBUTE_NAME_HREF, FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,outputFileName) + SHARP + firstTopicID); } include = false; //just a mark? stub = element.getOwnerDocument().createElement(ELEMENT_STUB); siblingStub = element.getOwnerDocument().createElement(ELEMENT_STUB); //<element> // <stub/> //</element> //<siblingstub/> //Place stub if(element.hasChildNodes()){ final NodeList list = element.getElementsByTagName(MAP_TOPICMETA.localName); if(list.getLength() > 0){ final Node node = list.item(0); final Node nextSibling = node.getNextSibling(); //no sibling so node is the last child if(nextSibling == null){ node.getParentNode().appendChild(stub); }else{ //has sibling node node.getParentNode().insertBefore(stub, nextSibling); } }else{ //no topicmeta tag. element.insertBefore(stub,element.getFirstChild()); } //element.insertBefore(stub,element.getFirstChild()); }else{ element.appendChild(stub); } //Place siblingStub if(element.getNextSibling() != null){ element.getParentNode().insertBefore(siblingStub, element.getNextSibling()); }else{ element.getParentNode().appendChild(siblingStub); } reader.setErrorHandler(new DITAOTXMLErrorHandler(currentParsingFile, logger)); reader.parse(new File(currentParsingFile).toURI().toString()); output.flush(); //remove stub and siblingStub stub.getParentNode().removeChild(stub); siblingStub.getParentNode().removeChild(siblingStub); } }catch (final Exception e) { logger.logError(e.getMessage(), e) ; }finally{ try{ if(output!=null){ output.close(); if(dotchunk && !new File(currentParsingFile).delete()){ logger.logError(MessageUtils.getInstance().getMessage("DOTJ009E", currentParsingFile, outputFile).toString()); } if(dotchunk && !new File(outputFile).renameTo(new File(currentParsingFile))){ logger.logError(MessageUtils.getInstance().getMessage("DOTJ009E", currentParsingFile, outputFile).toString()); } } output = tempOutput; }catch (final Exception ex) { logger.logError(ex.getMessage(), ex) ; } } } /** * Generate file name. * * @return generated file name */ private String generateFilename() { return "Chunk" + random.nextInt(Integer.MAX_VALUE) + ditaext; } private void processChunk(final Element element, final String outputFile) { final String hrefValue = element.getAttribute(ATTRIBUTE_NAME_HREF); final String chunkValue = element.getAttribute(ATTRIBUTE_NAME_CHUNK); final String copytoValue = element.getAttribute(ATTRIBUTE_NAME_COPY_TO); final String scopeValue = element.getAttribute(ATTRIBUTE_NAME_SCOPE); final String classValue = element.getAttribute(ATTRIBUTE_NAME_CLASS); final String processRoleValue = element.getAttribute(ATTRIBUTE_NAME_PROCESSING_ROLE); //Get id value final String id = element.getAttribute(ATTRIBUTE_NAME_ID); //Get navtitle value final String navtitle = element.getAttribute(ATTRIBUTE_NAME_NAVTITLE); //file which will be parsed String parseFilePath = null; String outputFileName = outputFile; //Writer tempWriter = null; Writer tempWriter = new StringWriter(); //Set<String> tempTopicID = null; Set<String> tempTopicID = new HashSet<String>(); targetTopicId = null; selectMethod = ATTR_CHUNK_VALUE_SELECT_DOCUMENT; include = false; boolean needWriteDitaTag = true; try { //Get target chunk file name if (copytoValue.length() != 0 && !chunkValue.contains(ATTR_CHUNK_VALUE_TO_CONTENT)){ if (getFragment(hrefValue) != null){ parseFilePath = copytoValue + SHARP + getFragment(hrefValue); }else{ parseFilePath = copytoValue; } }else{ parseFilePath = hrefValue; } // if @copy-to is processed in chunk module, the list file needs to be updated. // Because @copy-to should be included in fulltopiclist, and the source of coyy-to should be excluded in fulltopiclist. if(copytoValue.length() != 0 && chunkValue.contains(ATTR_CHUNK_VALUE_TO_CONTENT) && hrefValue.length() != 0){ copyto.add(copytoValue); if(getFragment(hrefValue) != null){ copytoSource.add(stripFragment(hrefValue)); copytotarget2source.put(copytoValue, stripFragment(hrefValue)); }else{ copytoSource.add(hrefValue); copytotarget2source.put(copytoValue,hrefValue); } } if ( !StringUtils.isEmptyString(classValue) ) { if ((!MAPGROUP_D_TOPICGROUP.matches(classValue)) && (!StringUtils.isEmptyString(parseFilePath)) && (!ATTR_SCOPE_VALUE_EXTERNAL.equalsIgnoreCase(scopeValue))) { // now the path to target file make sense if(chunkValue.indexOf(ATTR_CHUNK_VALUE_TO_CONTENT)!=-1){ //if current element contains "to-content" in chunk attribute //we need to create new buffer and flush the buffer to file //after processing is finished tempWriter = output; tempTopicID = topicID; output = new StringWriter(); topicID = new HashSet<String>(); //if (ELEMENT_NAME_MAP.equalsIgnoreCase(element.getNodeName())) { if (MAP_MAP.matches(classValue)) { // Very special case, we have a map element with href value. // This is a map that needs to be chunked to content. // No need to parse any file, just generate a stub output. outputFileName = FileUtils.resolveFile(filePath, parseFilePath); needWriteDitaTag = false; } else if (copytoValue.length() != 0){ // use @copy-to value as the new file name outputFileName = FileUtils.resolveFile(filePath,copytoValue); } else if (hrefValue.length() != 0) { // try to use href value as the new file name if (chunkValue.contains(ATTR_CHUNK_VALUE_SELECT_TOPIC) || chunkValue.contains(ATTR_CHUNK_VALUE_SELECT_BRANCH)) { if (getFragment(hrefValue) != null) { // if we have an ID here, use it. outputFileName = FileUtils.resolveFile(filePath, getFragment(hrefValue) + ditaext); } else { // Find the first topic id in target file if any. final String firstTopic = this.getFirstTopicId(FileUtils.resolveFile(filePath, hrefValue)); if (!StringUtils.isEmptyString(firstTopic)) { outputFileName = FileUtils.resolveFile(filePath, firstTopic + ditaext); } else { outputFileName = FileUtils.resolveFile(filePath,hrefValue); } } } else { // otherwise, use the href value instead outputFileName = FileUtils.resolveFile(filePath,hrefValue); } } else { // use randomly generated file name outputFileName = FileUtils.resolveFile(filePath, generateFilename()); } // Check if there is any conflict if(FileUtils.fileExists(outputFileName) && !MAP_MAP.matches(classValue)) { final String t = outputFileName; outputFileName = FileUtils.resolveFile(filePath, generateFilename()); conflictTable.put(outputFileName, t); } // add newly generated file to changTable // the new entry in changeTable has same key and value // in order to indicate it is a newly generated file changeTable.put(outputFileName,outputFileName); } //"by-topic" couldn't reach here this.outputFile = outputFileName; { final String path = FileUtils.resolveTopic(filePath,parseFilePath); String newpath = null; if(getFragment(path) != null){ newpath = outputFileName + SHARP + getFragment(path); }else{ final String firstTopicID = this.getFirstTopicId(path); if(!StringUtils.isEmptyString(firstTopicID)) { newpath = outputFileName + SHARP + firstTopicID; } else { newpath = outputFileName; } } // add file name changes to changeTable, this will be used in //TopicRefWriter's updateHref method, very important!!! changeTable.put(path, newpath); // update current element's @href value element.setAttribute(ATTRIBUTE_NAME_HREF, FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP ,newpath)); } if(getFragment(parseFilePath) != null){ targetTopicId = getFragment(parseFilePath); } if(chunkValue.indexOf("select")!=-1){ final int endIndex = chunkValue.indexOf(STRING_BLANK, chunkValue.indexOf("select")); if (endIndex ==-1){ // if there is no space after select-XXXX in chunk attribute selectMethod = chunkValue.substring(chunkValue.indexOf("select")); }else{ selectMethod = chunkValue.substring(chunkValue.indexOf("select"), endIndex); } if (ATTR_CHUNK_VALUE_SELECT_TOPIC.equals(selectMethod) || ATTR_CHUNK_VALUE_SELECT_BRANCH.equals(selectMethod)){ //if the current topic href referred to a entire topic file,it will be handled in "document" level. if(targetTopicId == null){ selectMethod = ATTR_CHUNK_VALUE_SELECT_DOCUMENT; } } } final String tempPath = currentParsingFile; currentParsingFile = FileUtils.resolveFile(filePath,parseFilePath); if ( !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue)) { currentParsingFileTopicIDChangeTable = new HashMap<String, String>(); //TODO recursive point reader.parse(new File(currentParsingFile).toURI().toString()); if(currentParsingFileTopicIDChangeTable.size()>0) { String href = element.getAttribute(ATTRIBUTE_NAME_HREF); href = FileUtils.separatorsToUnix(href); final String pathtoElem = getFragment(href) != null ? getFragment(href) : ""; final String old_elementid = pathtoElem.contains(SLASH) ? pathtoElem.substring(0, pathtoElem.indexOf(SLASH)) : pathtoElem; if(old_elementid.length()>0) { final String new_elementid = currentParsingFileTopicIDChangeTable.get(old_elementid); if(new_elementid!=null&&new_elementid.length()>0) { href = href.replaceFirst(SHARP + old_elementid, SHARP + new_elementid); element.setAttribute(ATTRIBUTE_NAME_HREF, href); } } } currentParsingFileTopicIDChangeTable = null; } //restore the currentParsingFile currentParsingFile = tempPath; } //use @copy-to value(dita spec v1.2) if(outputFileName == null){ if (!StringUtils.isEmptyString(copytoValue)){ outputFileName = FileUtils.resolveFile(filePath, copytoValue); //use id value }else if(!StringUtils.isEmptyString(id)){ outputFileName = FileUtils.resolveFile(filePath, id + ditaext); }else{ // use randomly generated file name outputFileName = FileUtils.resolveFile(filePath, generateFilename()); // Check if there is any conflict if(FileUtils.fileExists(outputFileName) && !MAP_MAP.matches(classValue)) { final String t = outputFileName; outputFileName = FileUtils.resolveFile(filePath, generateFilename()); conflictTable.put(outputFileName, t); } } //if topicref has child node or topicref has @navtitle if(element.hasChildNodes() || !StringUtils.isEmptyString(navtitle)){ final DITAAttrUtils utils = DITAAttrUtils.getInstance(); String navtitleValue = null; String shortDescValue = null; //get navtitle value. navtitleValue = utils.getChildElementValueOfTopicmeta(element, TOPIC_NAVTITLE.matcher); //get shortdesc value shortDescValue = utils.getChildElementValueOfTopicmeta(element, MAP_SHORTDESC.matcher); //no navtitle tag exists. if(navtitleValue == null){ //use @navtitle navtitleValue = navtitle; } // add newly generated file to changTable // the new entry in changeTable has same key and value // in order to indicate it is a newly generated file changeTable.put(outputFileName,outputFileName); // update current element's @href value //create a title-only topic when there is a title if(!StringUtils.isEmptyString(navtitleValue)){ element.setAttribute(ATTRIBUTE_NAME_HREF, FileUtils.getRelativePath(filePath+UNIX_SEPARATOR+FILE_NAME_STUB_DITAMAP, outputFileName)); //manually create a new topic chunk final StringBuffer buffer = new StringBuffer(); buffer.append("<topic id=\"topic\" class=\"- topic/topic \">") .append("<title class=\"- topic/title \">") .append(navtitleValue).append("</title>"); //has shortdesc value if(shortDescValue != null){ buffer.append("<shortdesc class=\"- topic/shortdesc \">") .append(shortDescValue).append("</shortdesc>"); } buffer.append("</topic>"); final StringReader rder = new StringReader(buffer.toString()); final InputSource source = new InputSource(rder); //for recursive final String tempPath = currentParsingFile; currentParsingFile = outputFileName; //insert not append the nested topic parseFilePath = outputFileName; //create chunk reader.parse(source); //restore the currentParsingFile currentParsingFile = tempPath; } } } //Added 20100818 for bug:3042978 end if (element.hasChildNodes()){ //if current element has child nodes and chunk results for this element has value //which means current element makes sense for chunk action. final StringWriter temp = (StringWriter)output; output = new StringWriter(); final NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++){ final Node current = children.item(i); if (current.getNodeType() == Node.ELEMENT_NODE && ((Element)current).getAttribute(ATTRIBUTE_NAME_CLASS) .indexOf(MAP_TOPICREF.matcher)!=-1){ processChunk((Element)current,outputFileName); } } // merge results final StringBuffer parentResult = temp.getBuffer(); // Skip empty parents and @processing-role='resource-only' entries. if (parentResult.length() > 0 && !StringUtils.isEmptyString(parseFilePath) && !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equalsIgnoreCase(processRoleValue)) { int insertpoint = parentResult.lastIndexOf("</"); final int end = parentResult.indexOf(">",insertpoint); if(insertpoint==-1 || end==-1){ logger.logError(MessageUtils.getInstance().getMessage("DOTJ033E", hrefValue).toString()); } else { if (ELEMENT_NAME_DITA.equalsIgnoreCase(parentResult.substring(insertpoint,end).trim())){ insertpoint = parentResult.lastIndexOf("</",insertpoint); } parentResult.insert(insertpoint,((StringWriter)output).getBuffer()); } } else { parentResult.append(((StringWriter)output).getBuffer()); } //restore back to parent's output this is a different temp output = temp; } if(chunkValue.indexOf(ATTR_CHUNK_VALUE_TO_CONTENT)!=-1){ //flush the buffer to file after processing is finished //and restore back original output final FileOutputStream fileOutput = new FileOutputStream(outputFileName); OutputStreamWriter ditaFileOutput = null; try { ditaFileOutput = new OutputStreamWriter(fileOutput, UTF8); if (outputFileName.equals(changeTable.get(outputFileName))){ // if the output file is newly generated file // write the xml header and workdir PI into new file writeStartDocument(ditaFileOutput); final File workDir = new File(outputFileName).getParentFile().getAbsoluteFile(); if(OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS)==-1) { writeProcessingInstruction(ditaFileOutput, PI_WORKDIR_TARGET, workDir.getAbsolutePath()); }else{ writeProcessingInstruction(ditaFileOutput, PI_WORKDIR_TARGET, UNIX_SEPARATOR + workDir.getAbsolutePath()); } writeProcessingInstruction(ditaFileOutput, PI_WORKDIR_TARGET_URI, workDir.toURI().toString()); if ((conflictTable.get(outputFileName)!=null)){ final String relativePath = FileUtils .getRelativePath(filePath + UNIX_SEPARATOR + FILE_NAME_STUB_DITAMAP, conflictTable.get(outputFileName)); String path2project = FileUtils .getRelativePath(relativePath); if (null==path2project){ path2project=""; } writeProcessingInstruction(ditaFileOutput, PI_PATH2PROJ_TARGET, path2project); } } if (needWriteDitaTag) { final AttributesImpl atts = new AttributesImpl(); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAMESPACE_PREFIX_DITAARCHVERSION, ditaarchNSValue); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_PREFIX_DITAARCHVERSION + COLON + ATTRIBUTE_NAME_DITAARCHVERSION, "1.2"); writeStartElement(ditaFileOutput, ELEMENT_NAME_DITA, atts); } //write the final result to the output file ditaFileOutput.write(((StringWriter)output).getBuffer().toString()); if (needWriteDitaTag) { writeEndElement(ditaFileOutput, ELEMENT_NAME_DITA); } ditaFileOutput.flush(); } finally { ditaFileOutput.close(); } // restore back original output output = tempWriter; topicID = tempTopicID; } } } catch (final Exception e) { logger.logError(e.getMessage(), e) ; } } /** * Set up the class. * @param changeTable changeTable * @param conflictTable conflictTable * @param refFileSet refFileSet * @param elem chunking topicref * @param separate separate * @param chunkByTopic chunkByTopic * @param ditaext ditaext */ public void setup(final LinkedHashMap<String, String> changeTable, final Hashtable<String, String> conflictTable, final Set<String> refFileSet, final Element elem, final boolean separate, final boolean chunkByTopic, final String ditaext) { // Initialize ChunkTopicParser this.changeTable = changeTable; this.elem = elem; this.separate = separate; this.ditaext = ditaext; this.conflictTable = conflictTable; } /** Check whether current href needs to be updated */ private boolean checkHREF(final Attributes atts){ final String hrefValue = atts.getValue(ATTRIBUTE_NAME_HREF); if (hrefValue == null || hrefValue.indexOf(COLON_DOUBLE_SLASH)!=-1){ return false; } String scopeValue = atts.getValue(ATTRIBUTE_NAME_SCOPE); if (scopeValue == null){ scopeValue = ATTR_SCOPE_VALUE_LOCAL; } if (scopeValue != null && scopeValue.equals(ATTR_SCOPE_VALUE_EXTERNAL)){ return false; } return true; } /** * * Get the first topic id from the given dita file. * @param absolutePathToFile The absolute path to a dita file. * @return The first topic id from the given dita file if success, * otherwise an empty string is returned. */ private String getFirstTopicId(final String absolutePathToFile){ final StringBuffer firstTopicId = new StringBuffer(); if(absolutePathToFile == null || !FileUtils.isAbsolutePath(absolutePathToFile)) { return firstTopicId.toString(); } final TopicIdParser parser = new TopicIdParser(firstTopicId); try{ final XMLReader reader = StringUtils.getXMLReader(); reader.setContentHandler(parser); reader.parse(new File(absolutePathToFile).toURI().toString()); }catch (final Exception e){ logger.logError(e.getMessage(), e) ; } return firstTopicId.toString(); } /** * Create topicmeta node. * @param element document element of a topic file. * @param newChild node to be appended by topicmeta. */ private void createTopicMeta(final Element element, final Element newChild) { //create topicmeta element final Element topicmeta = elem.getOwnerDocument() .createElement(MAP_TOPICMETA.localName); topicmeta.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_TOPICMETA.toString()); newChild.appendChild(topicmeta); final DITAAttrUtils utils = DITAAttrUtils.getInstance(); //iterate the node. if(element != null){ //search for title and navtitle tag final NodeList list = element.getChildNodes(); Node title = null; Node navtitle = null; for (int i = 0; i < list.getLength(); i++) { final Node node = list.item(i); if(node.getNodeType() == Node.ELEMENT_NODE){ final Element childNode = (Element)node; if(childNode.getAttribute(ATTRIBUTE_NAME_CLASS). contains(TOPIC_TITLE.matcher)){ //set title node title = childNode; } //navtitle node if(childNode.getAttribute(ATTRIBUTE_NAME_CLASS). contains(TOPIC_TITLEALTS.matcher)){ final NodeList subList = childNode.getChildNodes(); for(int j = 0; j < subList.getLength(); j ++ ){ final Node subNode = subList.item(j); if(subNode.getNodeType() == Node.ELEMENT_NODE){ final Element subChildNode = (Element)subNode; if(subChildNode.getAttribute(ATTRIBUTE_NAME_CLASS). contains(TOPIC_NAVTITLE.matcher)){ //set navtitle node navtitle = subChildNode; } } } } } } //shordesc node Node shortDesc = null; final NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final Element elem = (Element) node; final String clazzValue = elem .getAttribute(ATTRIBUTE_NAME_CLASS); //if needed node is found if (clazzValue != null && TOPIC_SHORTDESC.matches(clazzValue)) { shortDesc = elem; } } } final Element navtitleNode = elem.getOwnerDocument() .createElement(TOPIC_NAVTITLE.localName); navtitleNode.setAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_NAVTITLE.toString()); //append navtitle node if(navtitle != null){ //Get text value final String text = utils.getText(navtitle); final Text titleText = elem.getOwnerDocument().createTextNode(text); navtitleNode.appendChild(titleText); topicmeta.appendChild(navtitleNode); }else{ //Get text value final String text = utils.getText(title); final Text titleText = elem.getOwnerDocument().createTextNode(text); navtitleNode.appendChild(titleText); topicmeta.appendChild(navtitleNode); } //append gentext pi final Node pi = elem.getOwnerDocument() .createProcessingInstruction("ditaot", "gentext"); topicmeta.appendChild(pi); //append linktext final Element linkTextNode = elem.getOwnerDocument() .createElement(TOPIC_LINKTEXT.localName); linkTextNode.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_LINKTEXT.toString()); //Get text value final String text = utils.getText(title); final Text textNode = elem.getOwnerDocument().createTextNode(text); linkTextNode.appendChild(textNode); topicmeta.appendChild(linkTextNode); //append genshortdesc pi final Node pii = elem.getOwnerDocument() .createProcessingInstruction("ditaot", "genshortdesc"); topicmeta.appendChild(pii); //append shortdesc final Element shortDescNode = elem.getOwnerDocument() .createElement(TOPIC_SHORTDESC.localName); shortDescNode.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_SHORTDESC.toString()); //Get text value final String shortDescText = utils.getText(shortDesc); final Text shortDescTextNode = elem.getOwnerDocument().createTextNode(shortDescText); shortDescNode.appendChild(shortDescTextNode); topicmeta.appendChild(shortDescNode); } } }
package org.approvaltests.combinations.pairwise; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public final class InParameterOrderStrategy { public static List<List<Case>> generatePairs(List<Parameter<?>> parameters) { final List<Parameter> accumulator = new ArrayList<>(); Stream<Parameter<?>> sortedBySize = parameters.stream() .sorted((o1, o2) -> Integer.compare(o2.size(), o1.size())); Stream<ArrayList<Parameter>> arrayListStream = sortedBySize.map(parameter -> { accumulator.add(parameter); return new ArrayList<>(accumulator); }); return arrayListStream.map(chunk -> crossJoin(chunk)).collect(Collectors.toList()); } public static List<Case> horizontalGrowth(List<Case> cases, List<Case> pairs) { List<Case> result = new ArrayList<>(); for (Case aCase : cases) { Case best = best(pairs, aCase); pairs.removeIf(p -> p.matches(aCase)); result.add(best); } return result; } public static List<Case> verticalGrowth(List<Case> pairs) { return removeDuplicates(pairs); } public static List<Case> removeDuplicates(List<Case> pairs) { List<Case> collected = new ArrayList<>(); for (Case aCase : pairs) { if (!collected.contains(aCase)) { collected.add(aCase); } } return collected; } public static List<Case> crossJoin(List<Parameter> chunk) { final Parameter multiplier = chunk.get(chunk.size() - 1); return new ArrayList<Case>() { { IntStream.range(0, chunk.get(chunk.size() - 1).size()).forEach(last -> IntStream.range(0, chunk.size() - 1) .forEach(column -> IntStream.range(0, chunk.get(column).size()).forEach(cursor -> this.add(new Case() { { Parameter parameter = chunk.get(column); this.put(parameter.getPosition(), parameter.get(cursor)); this.put(multiplier.getPosition(), multiplier.get(last)); } })))); } }; } private static Case best(List<Case> pairs, Case aCaseParameter) { List<Case> list = new ArrayList<>(); for (Case aCase : pairs) { if (aCaseParameter.matches(aCase)) { list.add(aCase); } } final Map<String, String> lazyKey = new HashMap<>(); List<Object> values = new ArrayList<>(); for (Case p : list) { String newKey = p.keySet().stream().reduce((ignored, o) -> o).orElse(null); Object value = p.get(lazyKey.computeIfAbsent("key", i -> newKey)); values.add(value); } Map<Object, List<Object>> storage = new HashMap<>(); for (Object value : values) { storage.computeIfAbsent(value, x -> new ArrayList<Object>()); storage.get(value).add(value); } int amount = 0; Object obj = null; for (Object o : storage.keySet()) { int size = storage.get(o).size(); if (amount < size) { obj = o; amount = size; } } if (obj != null) { aCaseParameter.put(lazyKey.get("key"), obj); } return aCaseParameter; } public static List<Case> combineAppleSauce(List<Case> createManyCases, List<Case> cases) { List<Case> horizontalAndVerticalGrowth = horizontalGrowth(createManyCases, cases); horizontalAndVerticalGrowth.addAll(verticalGrowth(cases)); return horizontalAndVerticalGrowth; } }
package org.dungeon.entity.creatures; import org.dungeon.entity.Entity; import org.dungeon.entity.LightSource; import org.dungeon.entity.Luminosity; import org.dungeon.entity.TagSet; import org.dungeon.entity.items.CreatureInventory; import org.dungeon.entity.items.Item; import org.dungeon.game.Location; import org.dungeon.logging.DungeonLogger; import org.dungeon.stats.CauseOfDeath; import org.dungeon.util.Percentage; import org.jetbrains.annotations.NotNull; import java.util.List; /** * The Creature class. */ public class Creature extends Entity { private final int attack; private final AttackAlgorithmId attackAlgorithmId; private final TagSet<Tag> tagSet; private final CreatureInventory inventory; private final LightSource lightSource; private final CreatureHealth health; private final Dropper dropper; private Item weapon; private Location location; /** * What caused the death of this creature. If getHealth().isAlive() evaluates to true, this should be null. */ private CauseOfDeath causeOfDeath; public Creature(CreaturePreset preset) { super(preset); health = CreatureHealth.makeCreatureIntegrity(preset.getHealth(), this); attack = preset.getAttack(); tagSet = TagSet.copyTagSet(preset.getTagSet()); attackAlgorithmId = preset.getAttackAlgorithmId(); inventory = new CreatureInventory(this, preset.getInventoryItemLimit(), preset.getInventoryWeightLimit()); lightSource = new LightSource(preset.getLuminosity()); dropper = new Dropper(this, preset.getDropList()); } public boolean hasTag(Tag tag) { return tagSet.hasTag(tag); } public CreatureHealth getHealth() { return health; } Dropper getDropper() { return dropper; } public int getAttack() { return attack; } public CreatureInventory getInventory() { return inventory; } @Override public Luminosity getLuminosity() { if (hasWeapon()) { double luminosityFromWeapon = getWeapon().getLuminosity().toPercentage().toDouble(); double luminosityFromLightSource = lightSource.getLuminosity().toPercentage().toDouble(); return new Luminosity(new Percentage(luminosityFromWeapon + luminosityFromLightSource)); } else { return lightSource.getLuminosity(); } } public LightSource getLightSource() { return lightSource; } public Item getWeapon() { return weapon; } /** * Sets an Item as the currently equipped weapon. The Item must be in this Creature's inventory and have the WEAPON * tag. * * @param weapon an Item that must be in this Creature's inventory and have the WEAPON tag */ public void setWeapon(Item weapon) { if (inventory.hasItem(weapon)) { if (weapon.hasTag(Item.Tag.WEAPON)) { this.weapon = weapon; } else { DungeonLogger.warning(String.format("Tried to equip %s (no WEAPON tag) on %s.", weapon.getName(), getName())); } } else { DungeonLogger.warning("Tried to equip an Item that is not in the inventory of " + getName() + "."); } } /** * Unequips the currently equipped weapon. */ public void unsetWeapon() { this.weapon = null; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } /** * Hits the specified target Creature. * * @param target the target */ public void hit(Creature target) { AttackAlgorithms.renderAttack(this, target); } boolean hasWeapon() { return getWeapon() != null; } void dropItem(Item item) { if (getInventory().hasItem(item)) { getInventory().removeItem(item); getLocation().addItem(item); } else { throw new IllegalStateException("item should be in the creature's inventory."); } } public AttackAlgorithmId getAttackAlgorithmId() { return attackAlgorithmId; } /** * Retrieves what caused the death of this creature. If getHealth().isAlive() evaluates to true, this method returns * null. */ public CauseOfDeath getCauseOfDeath() { return causeOfDeath; } /** * Sets what caused the death of this creature. Should be called only once and after the creature is dead. */ public void setCauseOfDeath(@NotNull CauseOfDeath causeOfDeath) { if (this.causeOfDeath != null) { throw new IllegalStateException("creature already has a CauseOfDeath."); } else if (getHealth().isAlive()) { throw new IllegalStateException("creature is still alive."); } else { this.causeOfDeath = causeOfDeath; } } /** * Returns a List with all the items this Creature dropped when it died. If this Creature is still alive, returns an * empty list. * * @return a List with the Items this Creature dropped when it died */ @NotNull public List<Item> getDroppedItemsList() { return getDropper().getDroppedItemsList(); } @Override public String toString() { return getName().getSingular(); } public enum Tag {MILKABLE, CORPSE} }
package org.enoir.graphvizapi; import org.enoir.graphvizapi.exception.AttributeNotFondException; import java.util.ArrayList; import java.util.List; public abstract class BaseGraphObject { private String id; private List<Attribute> attrList; /** * Constructor. * @param id This graph object's id. */ public BaseGraphObject(String id) { this.id = id; attrList = new ArrayList<Attribute>(); } /** * Add an attribute to attribute list. * @param attr attribute */ public void addAttribute(Attribute attr){ this.attrList.add(attr); } /** * Remove attribute by attribute name. If this graph object has two or more attribute * with same name, it will remove them. * @param attributeName */ public void removeAttribute(String attributeName){ List<Attribute> removeList = new ArrayList<Attribute>(); for(Attribute attr : this.attrList){ if(attr.getAttrName().equals(attributeName)){ removeList.add(attr); } } if(removeList.size()==0){ throw new AttributeNotFondException("ID: "+id+";attribute:"+attributeName); } for(Attribute attr: removeList){ this.attrList.remove(attr); } } /** * Graph object id getter. * @return id */ public String getId(){ return this.id; } /** * Graph object id setter. * @param id */ public void setId(String id){ this.id = id; } /** * Attribute to dot string. * @return dot format string. */ protected String genAttributeDotString(){ StringBuilder attrDotString = new StringBuilder(); for(Attribute attr : this.attrList){ attrDotString.append(attr.getAttrName()+"="+attr.getAttrValue()+";\n"); } return attrDotString.toString(); } /** * Convert this graph object to graphviz dot format. * @return */ abstract public String genDotString(); }
package org.gem.calc; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Random; import junit.framework.Assert; import org.gem.engine.hazard.redis.Cache; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.opensha.commons.calc.magScalingRelations.magScalingRelImpl.WC1994_MagLengthRelationship; import org.opensha.commons.data.Site; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.commons.data.function.DiscretizedFuncAPI; import org.opensha.commons.geo.BorderType; import org.opensha.commons.geo.GriddedRegion; import org.opensha.commons.geo.Location; import org.opensha.commons.geo.LocationList; import org.opensha.commons.geo.Region; import org.opensha.commons.param.DoubleParameter; import org.opensha.commons.param.event.ParameterChangeWarningListener; import org.opensha.sha.calc.HazardCurveCalculator; import org.opensha.sha.earthquake.EqkRupForecast; import org.opensha.sha.earthquake.EqkRupForecastAPI; import org.opensha.sha.earthquake.EqkRupture; import org.opensha.sha.earthquake.ProbEqkSource; import org.opensha.sha.earthquake.rupForecastImpl.FloatingPoissonFaultSource; import org.opensha.sha.faultSurface.FaultTrace; import org.opensha.sha.faultSurface.StirlingGriddedSurface; import org.opensha.sha.imr.ScalarIntensityMeasureRelationshipAPI; import org.opensha.sha.imr.attenRelImpl.BA_2008_AttenRel; import org.opensha.sha.imr.param.IntensityMeasureParams.PGA_Param; import org.opensha.sha.imr.param.OtherParams.ComponentParam; import org.opensha.sha.imr.param.OtherParams.SigmaTruncLevelParam; import org.opensha.sha.imr.param.OtherParams.SigmaTruncTypeParam; import org.opensha.sha.imr.param.OtherParams.StdDevTypeParam; import org.opensha.sha.imr.param.SiteParams.Vs30_Param; import org.opensha.sha.magdist.GutenbergRichterMagFreqDist; import org.opensha.sha.util.TectonicRegionType; public class HazardCalculatorTest { private static List<Site> siteList; private static EqkRupForecastAPI erf; private static Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> gmpeMap; private static List<Double> imlVals; private static double integrationDistance = 200.0; private static Random rn = new Random(); private static Boolean correlationFlag = false; // for memcache tests: private static final int PORT = 6379; private static final String LOCALHOST = "localhost"; private Cache cache; @Before public void setUp() throws IOException { setUpSites(); setUpErf(); setUpGmpeMap(); setUpImlValues(); try { setUpMemcache(); } catch (IOException e) { tearDown(); throw e; } } @After public void tearDown() { siteList = null; erf = null; gmpeMap = null; imlVals = null; if (cache != null) { cache.flush(); cache = null; } } /** * Check that hazard curves stored in map are exactly those calculated from * the method getHazardCurve in {@link HazardCurveCalculator} */ @Test public void checkHazardCurves() { Map<Site, DiscretizedFuncAPI> results = HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); HazardCurveCalculator hazCurveCal = null; DiscretizedFuncAPI hazCurve = new ArbitrarilyDiscretizedFunc(); for (Double val : imlVals) { hazCurve.set(val, 1.0); } try { hazCurveCal = new HazardCurveCalculator(); hazCurveCal.setMaxSourceDistance(integrationDistance); for (Site site : siteList) { hazCurveCal.getHazardCurve(hazCurve, site, gmpeMap, erf); assertTrue(hazCurve.equals(results.get(site))); } } catch (RemoteException e) { e.printStackTrace(); } } /** * Test getHazardCurves when a null list of site is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesNullSiteList() { ArrayList<Site> siteList = null; HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when an empty list of site is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesEmptySiteList() { ArrayList<Site> siteList = new ArrayList<Site>(); HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when a null earthquake rupture forecast is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesNullErf() { EqkRupForecastAPI erf = null; HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when a null gmpe map is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesNullGmpeMap() { Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> gmpeMap = null; HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when an empty gmpe map is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesEmptyGmpeMap() { Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> gmpeMap = new HashMap<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI>(); HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when a null intensity measure levels array is passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesNullImlLevelsList() { List<Double> imlVals = null; HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getHazardCurves when an empty intensity measure levels array is * passed */ @Test(expected = IllegalArgumentException.class) public void getHazardCurvesEmptyImlLevelsList() { List<Double> imlVals = new ArrayList<Double>(); HazardCalculator.getHazardCurves(siteList, erf, gmpeMap, imlVals, integrationDistance); } /** * Test getGroundMotionFields when a null list of site is passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsNullSiteList() { ArrayList<Site> siteList = null; HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } /** * Test getGroundMotionFields when an empty list of site is passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsEmptySiteList() { ArrayList<Site> siteList = new ArrayList<Site>(); HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } /** * Test getGroundMotionFields when a null earthquake rupture forecast is * passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsNullErf() { EqkRupForecastAPI erf = null; HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } /** * Test getGroundMotionFields when a null gmpe map is passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsNullGmpeMap() { Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> gmpeMap = null; HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } /** * Test getGroundMotionFields when an empty gmpe map is passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsEmptyGmpeMap() { Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> gmpeMap = new HashMap<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI>(); HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } /** * Test getGroundMotionFields when null random number is passed */ @Test(expected = IllegalArgumentException.class) public void getGroundMotionFieldsNullRandomNumberGenerator() { Random rn = null; HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } @Test public void gmfToJsonTest() { int maxTries = 111; Map<EqkRupture, Map<Site, Double>> groundMotionFields = null; while (maxTries > 0 && groundMotionFields == null || groundMotionFields.values().size() == 0) { --maxTries; // HazardCalculator does not return ground motion fields in more // than 50% of the runs. Is it possible that this // has to do with the random seed? (That is the parameter that // changes for each call.) groundMotionFields = HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } if (groundMotionFields == null || groundMotionFields.values().size() == 0) { Assert.fail("HazardCalculator did not return ground motion fields after " + maxTries + " runs." + groundMotionFields.toString()); } String[] eqkRuptureIds = new String[groundMotionFields.values().size()]; for (int i = 0; i < eqkRuptureIds.length; ++i) { eqkRuptureIds[i] = "eqkRupture_id_" + i; } Map<Site, Double> firstGmf = groundMotionFields.values().iterator().next(); String[] siteIds = new String[firstGmf.size()]; for (int i = 0; i < siteIds.length; ++i) { siteIds[i] = "site_id_" + i; } String jsonString = HazardCalculator.gmfToJson("gmf_id", eqkRuptureIds, siteIds, groundMotionFields); assertNotNull("jsonString is expected to not to be null", jsonString); } @Test public void gmfToMemcacheTest() { int maxTries = 111; Map<EqkRupture, Map<Site, Double>> groundMotionFields = null; while (maxTries > 0 && groundMotionFields == null || groundMotionFields.values().size() == 0) { --maxTries; // HazardCalculator does not return ground motion fields in more // than 50% of the runs. Is it possible that this // has to do with the random seed? (That is the parameter that // changes for each call.) groundMotionFields = HazardCalculator.getGroundMotionFields(siteList, erf, gmpeMap, rn, correlationFlag); } if (groundMotionFields == null || groundMotionFields.values().size() == 0) { Assert.fail("HazardCalculator did not return ground motion fields after " + maxTries + " runs." + groundMotionFields.toString()); } Map<Site, Double> firstGmf = groundMotionFields.values().iterator().next(); String[] eqkRuptureIds = new String[groundMotionFields.values().size()]; for (int i = 0; i < eqkRuptureIds.length; ++i) { eqkRuptureIds[i] = "eqkRupture_id_" + i; } String[] siteIds = new String[firstGmf.size()]; for (int i = 0; i < siteIds.length; ++i) { siteIds[i] = "site_id_" + i; } String gmfsId = "gmfs_id"; String memCacheKey = "memCache_key"; // this is what we expect to find in memcache later String jsonFromGmf = HazardCalculator.gmfToJson("gmf_id", eqkRuptureIds, siteIds, groundMotionFields); // converts the groundmotion fields to json and stores them in the cache HazardCalculator.gmfToMemcache(cache, memCacheKey, gmfsId, eqkRuptureIds, siteIds, groundMotionFields); String jsonFromMemcache = (String) cache.get(memCacheKey); assertNotNull("test gmfToMemcacheTest: no value returned from cache", jsonFromMemcache); assertTrue(jsonFromGmf.compareTo(jsonFromGmf) == 0); } /** * Set up list of sites */ private static void setUpSites() { siteList = new ArrayList<Site>(); LocationList border = new LocationList(); border.add(new Location(35.0, 35.0)); border.add(new Location(35.0, 38.0)); border.add(new Location(38.0, 38.0)); border.add(new Location(38.0, 35.0)); Region reg = new Region(border, BorderType.MERCATOR_LINEAR); double spacing = 1.0; GriddedRegion griddedReg = new GriddedRegion(reg, spacing, null); for (Location loc : griddedReg.getNodeList()) { Site site = new Site(loc); site.addParameter(new DoubleParameter(Vs30_Param.NAME, 760.0)); siteList.add(site); } } /** * Set up ERF */ private void setUpErf() { erf = new EqkRupForecast() { @Override public String getName() { return new String( "Earthquake rupture forecast for testing pourpose"); } @Override public void updateForecast() { } @Override public ArrayList getSourceList() { ArrayList<ProbEqkSource> list = new ArrayList<ProbEqkSource>(); list.add(getFloatingPoissonFaultSource()); return list; } @Override public ProbEqkSource getSource(int iSource) { return getFloatingPoissonFaultSource(); } @Override public int getNumSources() { return 1; } }; } /** * Set up gmpe map */ private void setUpGmpeMap() { gmpeMap = new Hashtable<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI>(); ParameterChangeWarningListener warningListener = null; BA_2008_AttenRel imr = new BA_2008_AttenRel(warningListener); imr.setParamDefaults(); imr.getParameter(StdDevTypeParam.NAME).setValue( StdDevTypeParam.STD_DEV_TYPE_TOTAL); imr.getParameter(SigmaTruncTypeParam.NAME).setValue( SigmaTruncTypeParam.SIGMA_TRUNC_TYPE_2SIDED); imr.getParameter(SigmaTruncLevelParam.NAME).setValue(3.0); imr.setIntensityMeasure(PGA_Param.NAME); imr.getParameter(ComponentParam.NAME).setValue( ComponentParam.COMPONENT_GMRotI50); gmpeMap.put(TectonicRegionType.ACTIVE_SHALLOW, imr); } /** * Set up intensity measure levels */ private void setUpImlValues() { imlVals = new ArrayList<Double>(); imlVals.add(Math.log(0.005)); imlVals.add(Math.log(0.007)); imlVals.add(Math.log(0.0098)); imlVals.add(Math.log(0.0137)); imlVals.add(Math.log(0.0192)); imlVals.add(Math.log(0.0269)); imlVals.add(Math.log(0.0376)); imlVals.add(Math.log(0.0527)); imlVals.add(Math.log(0.0738)); imlVals.add(Math.log(0.103)); imlVals.add(Math.log(0.145)); imlVals.add(Math.log(0.203)); imlVals.add(Math.log(0.284)); imlVals.add(Math.log(0.397)); imlVals.add(Math.log(0.556)); imlVals.add(Math.log(0.778)); imlVals.add(Math.log(1.09)); } /** * Set up the cache to access the same host/port. * * @throws IOException */ private void setUpMemcache() throws IOException { cache = new Cache(LOCALHOST, PORT); } /** * Defines fault source (data taken from Turkey model) * * @return */ private static FloatingPoissonFaultSource getFloatingPoissonFaultSource() { FaultTrace trace = new FaultTrace("trf41"); trace.add(new Location(37.413314, 36.866757)); trace.add(new Location(37.033241, 36.640297)); trace.add(new Location(36.608673, 36.431566)); trace.add(new Location(36.488077, 36.375783)); trace.add(new Location(35.677685, 36.271872)); double occurrenceRate = 0.017; double beta = 2.115; double mMin = 6.8; double mMax = 7.9; double mfdBinWidth = 0.1; int num = (int) ((mMax - mMin) / mfdBinWidth + 1); GutenbergRichterMagFreqDist mfd = new GutenbergRichterMagFreqDist(mMin, mMax, num); mfd.setAllButTotMoRate(mMin, mMax, occurrenceRate, beta / Math.log(10)); double dip = 90.0; double rake = 0.0; double upperSeismogenicDepth = 0.0; double lowerSeismogenicDepth = 0.0; double gridSpacing = 1.0; StirlingGriddedSurface surf = new StirlingGriddedSurface(trace, dip, upperSeismogenicDepth, lowerSeismogenicDepth, gridSpacing); FloatingPoissonFaultSource src = new FloatingPoissonFaultSource(mfd, surf, new WC1994_MagLengthRelationship(), 0.0, 1.5, 1.0, rake, 50.0, mMin, 1, 12.0); src.setTectonicRegionType(TectonicRegionType.ACTIVE_SHALLOW); return src; } }
package org.example.seed.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.http.MediaType; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.time.LocalDate; // TODO: See how to add a new adapter instead of WebMvcConfigurerAdapter with Spring Fox Swagger @Configuration @EnableSwagger2 @Profile("local") @SuppressWarnings("deprecation") public class SwaggerConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/");
package org.geomajas.command.configuration; import org.geomajas.command.CommandDispatcher; import org.geomajas.command.dto.GetConfigurationRequest; import org.geomajas.command.dto.GetConfigurationResponse; import org.geomajas.configuration.client.ClientApplicationInfo; import org.geomajas.configuration.client.ClientLayerInfo; import org.geomajas.configuration.client.ClientMapInfo; import org.geomajas.configuration.client.ClientUserDataInfo; import org.geomajas.geometry.Bbox; import org.geomajas.layer.Layer; import org.geomajas.service.ConfigurationService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Verify the getting of the map configuration (and especially the transformation of maxExtent coordinates). * * @author Joachim Van der Auwera */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/org/geomajas/spring/geomajasContext.xml", "/org/geomajas/testdata/layerCountries.xml", "/org/geomajas/testdata/simplevectorsContext.xml" }) public class GetConfigurationCommandTest { private static final double DOUBLE_TOLERANCE = .0000000001; private static final String APP_ID = "simplevectors"; @Autowired private ConfigurationService configurationService; @Autowired private CommandDispatcher dispatcher; @Test public void testConvertApplication() throws Exception { GetConfigurationRequest request = new GetConfigurationRequest(); request.setApplicationId(APP_ID); GetConfigurationResponse response = (GetConfigurationResponse) dispatcher.execute( "command.configuration.Get", request, null, "en"); if (response.isError()) { response.getErrors().get(0).printStackTrace(); } Assert.assertFalse(response.isError()); ClientApplicationInfo appInfo = response.getApplication(); Assert.assertNotNull(appInfo); Assert.assertEquals(APP_ID, appInfo.getId()); Assert.assertEquals(96, appInfo.getScreenDpi()); // widget data Assert.assertNotNull(appInfo.getWidgetInfo()); Assert.assertNotNull(appInfo.getWidgetInfo("mapSelect")); Assert.assertNull(appInfo.getWidgetInfo("layerTree")); Assert.assertEquals("map1, map2", ((ClientApplicationInfo.DummyClientWidgetInfo) appInfo.getWidgetInfo("mapSelect")).getDummy()); verifyMap(appInfo.getMaps().get(2)); } private void verifyMap(ClientMapInfo mapInfo) { // first test base assumptions Layer layer = configurationService.getLayer("countries"); Bbox configMaxExtent = layer.getLayerInfo().getMaxExtent(); Assert.assertEquals(-85.05112877980659, configMaxExtent.getX(), DOUBLE_TOLERANCE); Assert.assertEquals(-85.05112877980659, configMaxExtent.getY(), DOUBLE_TOLERANCE); Assert.assertEquals(170.102257, configMaxExtent.getWidth(), DOUBLE_TOLERANCE); Assert.assertEquals(170.102257, configMaxExtent.getHeight(), DOUBLE_TOLERANCE); // now test the map conversion Assert.assertNotNull(mapInfo); Bbox mapMaxExtent = mapInfo.getLayers().get(0).getMaxExtent(); // these values were registered during a first run, they have *not* been externally verified Assert.assertEquals(-9467848.347161204, mapMaxExtent.getX(), DOUBLE_TOLERANCE); Assert.assertEquals(-2.0037508342789236E7, mapMaxExtent.getY(), DOUBLE_TOLERANCE); Assert.assertEquals(1.8935696632026553E7, mapMaxExtent.getWidth(), DOUBLE_TOLERANCE); Assert.assertEquals(4.007501596344786E7, mapMaxExtent.getHeight(), DOUBLE_TOLERANCE); // user data ClientUserDataInfo info = mapInfo.getUserData(); Assert.assertNotNull(info); Assert.assertTrue(info instanceof ClientApplicationInfo.DummyClientUserDataInfo); Assert.assertEquals("some data", ((ClientApplicationInfo.DummyClientUserDataInfo) info).getDummy()); // widget data Assert.assertNotNull(mapInfo.getWidgetInfo()); Assert.assertNull(mapInfo.getWidgetInfo("mapSelect")); Assert.assertNotNull(mapInfo.getWidgetInfo("layerTree")); Assert.assertEquals("layer1, layer2", ((ClientApplicationInfo.DummyClientWidgetInfo) mapInfo.getWidgetInfo("layerTree")).getDummy()); // widget data on the layer ClientLayerInfo layerInfo = mapInfo.getLayers().get(0); for(ClientLayerInfo i: mapInfo.getLayers()) { if(i.getId().equals("countries")) { layerInfo = i; } } Assert.assertNotNull(layerInfo); Assert.assertNotNull(layerInfo.getWidgetInfo()); Assert.assertNull(layerInfo.getWidgetInfo("layerTree")); Assert.assertNotNull(layerInfo.getWidgetInfo("customLayerInfoWidget")); Assert.assertEquals("org.geomajas.widget.IpsumWidget", ((ClientApplicationInfo.DummyClientWidgetInfo) layerInfo.getWidgetInfo("customLayerInfoWidget")).getDummy()); } }
package org.xdi.oxauth; import org.apache.commons.lang.StringUtils; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.conn.SingleClientConnManager; import org.jboss.resteasy.client.ClientExecutor; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; import org.openqa.selenium.*; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.ITestContext; import org.testng.Reporter; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.xdi.oxauth.client.*; import org.xdi.oxauth.dev.HostnameVerifierType; import org.xdi.oxauth.model.common.ResponseMode; import org.xdi.oxauth.model.error.IErrorType; import org.xdi.oxauth.model.util.SecurityProviderUtility; import org.xdi.util.StringHelper; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import static org.testng.Assert.*; /** * @author Javier Rojas Blum * @version May 23, 2018 */ public abstract class BaseTest { protected WebDriver driver; protected String authorizationEndpoint; protected String authorizationPageEndpoint; protected String gluuConfigurationEndpoint; protected String tokenEndpoint; protected String userInfoEndpoint; protected String clientInfoEndpoint; protected String checkSessionIFrame; protected String endSessionEndpoint; protected String jwksUri; protected String registrationEndpoint; protected String configurationEndpoint; protected String idGenEndpoint; protected String introspectionEndpoint; protected Map<String, List<String>> scopeToClaimsMapping; // Form Interaction private String loginFormUsername; private String loginFormPassword; private String loginFormLoginButton; private String authorizeFormAllowButton; private String authorizeFormDoNotAllowButton; @BeforeSuite public void initTestSuite(ITestContext context) throws FileNotFoundException, IOException { SecurityProviderUtility.installBCProvider(); Reporter.log("Invoked init test suite method \n", true); String propertiesFile = context.getCurrentXmlTest().getParameter("propertiesFile"); if (StringHelper.isEmpty(propertiesFile)) { propertiesFile = "target/test-classes/testng.properties"; //propertiesFile = "U:\\own\\project\\git\\oxAuth\\Client\\src\\test\\resources\\testng_yuriy.properties"; //propertiesFile = "/Users/JAVIER/IdeaProjects/oxAuth/Client/target/test-classes/testng.properties"; } FileInputStream conf = new FileInputStream(propertiesFile); Properties prop = new Properties(); prop.load(conf); Map<String, String> parameters = new HashMap<String, String>(); for (Entry<Object, Object> entry : prop.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (StringHelper.isEmptyString(key) || StringHelper.isEmptyString(value)) { continue; } parameters.put(key.toString(), value.toString()); } // Overrided test paramters context.getSuite().getXmlSuite().setParameters(parameters); } public WebDriver getDriver() { return driver; } public void setDriver(WebDriver driver) { this.driver = driver; } public String getAuthorizationEndpoint() { return authorizationEndpoint; } public void setAuthorizationEndpoint(String authorizationEndpoint) { this.authorizationEndpoint = authorizationEndpoint; } public String getTokenEndpoint() { return tokenEndpoint; } public void setTokenEndpoint(String tokenEndpoint) { this.tokenEndpoint = tokenEndpoint; } public String getUserInfoEndpoint() { return userInfoEndpoint; } public void setUserInfoEndpoint(String userInfoEndpoint) { this.userInfoEndpoint = userInfoEndpoint; } public String getClientInfoEndpoint() { return clientInfoEndpoint; } public void setClientInfoEndpoint(String clientInfoEndpoint) { this.clientInfoEndpoint = clientInfoEndpoint; } public String getCheckSessionIFrame() { return checkSessionIFrame; } public void setCheckSessionIFrame(String checkSessionIFrame) { this.checkSessionIFrame = checkSessionIFrame; } public String getEndSessionEndpoint() { return endSessionEndpoint; } public void setEndSessionEndpoint(String endSessionEndpoint) { this.endSessionEndpoint = endSessionEndpoint; } public String getJwksUri() { return jwksUri; } public void setJwksUri(String jwksUri) { this.jwksUri = jwksUri; } public String getRegistrationEndpoint() { return registrationEndpoint; } public void setRegistrationEndpoint(String registrationEndpoint) { this.registrationEndpoint = registrationEndpoint; } public String getIntrospectionEndpoint() { return introspectionEndpoint; } public void setIntrospectionEndpoint(String p_introspectionEndpoint) { introspectionEndpoint = p_introspectionEndpoint; } public Map<String, List<String>> getScopeToClaimsMapping() { return scopeToClaimsMapping; } public void setScopeToClaimsMapping(Map<String, List<String>> p_scopeToClaimsMapping) { scopeToClaimsMapping = p_scopeToClaimsMapping; } public String getIdGenEndpoint() { return idGenEndpoint; } public void setIdGenEndpoint(String p_idGenEndpoint) { idGenEndpoint = p_idGenEndpoint; } public String getConfigurationEndpoint() { return configurationEndpoint; } public void setConfigurationEndpoint(String configurationEndpoint) { this.configurationEndpoint = configurationEndpoint; } public void startSelenium() { //System.setProperty("webdriver.chrome.driver", "/Users/JAVIER/tmp/chromedriver"); //driver = new ChromeDriver(); //driver = new SafariDriver(); //driver = new FirefoxDriver(); //driver = new InternetExplorerDriver(); driver = new HtmlUnitDriver(true); } public void stopSelenium() { // driver.close(); driver.quit(); } /** * The authorization server authenticates the resource owner (via the user-agent) * and establishes whether the resource owner grants or denies the client's access request. */ public AuthorizationResponse authenticateResourceOwnerAndGrantAccess( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret) { return authenticateResourceOwnerAndGrantAccess(authorizeUrl, authorizationRequest, userId, userSecret, true); } /** * The authorization server authenticates the resource owner (via the user-agent) * and establishes whether the resource owner grants or denies the client's access request. */ public AuthorizationResponse authenticateResourceOwnerAndGrantAccess( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret, boolean cleanupCookies) { return authenticateResourceOwnerAndGrantAccess(authorizeUrl, authorizationRequest, userId, userSecret, cleanupCookies, false); } /** * The authorization server authenticates the resource owner (via the user-agent) * and establishes whether the resource owner grants or denies the client's access request. */ public AuthorizationResponse authenticateResourceOwnerAndGrantAccess( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret, boolean cleanupCookies, boolean useNewDriver) { return authenticateResourceOwnerAndGrantAccess(authorizeUrl, authorizationRequest, userId, userSecret, cleanupCookies, useNewDriver, 1); } /** * The authorization server authenticates the resource owner (via the user-agent) * and establishes whether the resource owner grants or denies the client's access request. */ public AuthorizationResponse authenticateResourceOwnerAndGrantAccess( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret, boolean cleanupCookies, boolean useNewDriver, int authzSteps) { WebDriver currentDriver = initWebDriver(useNewDriver, cleanupCookies); AuthorizeClient authorizeClient = processAuthentication(currentDriver, authorizeUrl, authorizationRequest, userId, userSecret); int remainAuthzSteps = authzSteps; String authorizationResponseStr = null; do { authorizationResponseStr = acceptAuthorization(currentDriver); remainAuthzSteps } while (remainAuthzSteps >= 1); AuthorizationResponse authorizationResponse = buildAuthorizationResponse(authorizationRequest, useNewDriver, currentDriver, authorizeClient, authorizationResponseStr); stopWebDriver(useNewDriver, currentDriver); return authorizationResponse; } private WebDriver initWebDriver(boolean useNewDriver, boolean cleanupCookies) { // Allow to run test in multi thread mode WebDriver currentDriver; if (useNewDriver) { currentDriver = new HtmlUnitDriver(); } else { startSelenium(); currentDriver = driver; if (cleanupCookies) { System.out.println("authenticateResourceOwnerAndGrantAccess: Cleaning cookies"); deleteAllCookies(); } } return currentDriver; } private void stopWebDriver(boolean useNewDriver, WebDriver currentDriver) { if (useNewDriver) { currentDriver.close(); currentDriver.quit(); } else { stopSelenium(); } } private AuthorizeClient processAuthentication(WebDriver currentDriver, String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("authenticateResourceOwnerAndGrantAccess: authorizationRequestUrl:" + authorizationRequestUrl); currentDriver.navigate().to(authorizationRequestUrl); if (userSecret != null) { if (userId != null) { WebElement usernameElement = currentDriver.findElement(By.name(loginFormUsername)); usernameElement.sendKeys(userId); } WebElement passwordElement = currentDriver.findElement(By.name(loginFormPassword)); passwordElement.sendKeys(userSecret); WebElement loginButton = currentDriver.findElement(By.name(loginFormLoginButton)); loginButton.click(); } return authorizeClient; } private String acceptAuthorization(WebDriver currentDriver) { String authorizationResponseStr = currentDriver.getCurrentUrl(); // Check for authorization form if client has no persistent authorization if (!authorizationResponseStr.contains(" //WebElement allowButton = currentDriver.findElement(By.id(authorizeFormAllowButton)); WebElement allowButton = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.id(authorizeFormAllowButton))); final String previousURL = currentDriver.getCurrentUrl(); JavascriptExecutor jse = (JavascriptExecutor) driver; jse.executeScript("scroll(0, 1000)"); Actions actions = new Actions(driver); actions.moveToElement(allowButton).click().build().perform(); WebDriverWait wait = new WebDriverWait(currentDriver, 10); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return (d.getCurrentUrl() != previousURL); } }); authorizationResponseStr = currentDriver.getCurrentUrl(); } else { fail("The authorization form was expected to be shown."); } return authorizationResponseStr; } private AuthorizationResponse buildAuthorizationResponse(AuthorizationRequest authorizationRequest, boolean useNewDriver, WebDriver currentDriver, AuthorizeClient authorizeClient, String authorizationResponseStr) { Cookie sessionStateCookie = currentDriver.manage().getCookieNamed("session_state"); String sessionState = null; if (sessionStateCookie != null) { sessionState = sessionStateCookie.getValue(); } System.out.println("authenticateResourceOwnerAndGrantAccess: sessionState:" + sessionState); AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr); if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) { authorizationResponse.setResponseMode(ResponseMode.FORM_POST); } authorizeClient.setResponse(authorizationResponse); showClientUserAgent(authorizeClient); return authorizationResponse; } public AuthorizationResponse authenticateResourceOwnerAndDenyAccess( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("authenticateResourceOwnerAndDenyAccess: authorizationRequestUrl:" + authorizationRequestUrl); startSelenium(); driver.navigate().to(authorizationRequestUrl); WebElement usernameElement = driver.findElement(By.name(loginFormUsername)); WebElement passwordElement = driver.findElement(By.name(loginFormPassword)); WebElement loginButton = driver.findElement(By.name(loginFormLoginButton)); if (userId != null) { usernameElement.sendKeys(userId); } passwordElement.sendKeys(userSecret); loginButton.click(); String authorizationResponseStr = driver.getCurrentUrl(); WebElement doNotAllowButton = driver.findElement(By.id(authorizeFormDoNotAllowButton)); final String previousURL = driver.getCurrentUrl(); doNotAllowButton.click(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return (d.getCurrentUrl() != previousURL); } }); authorizationResponseStr = driver.getCurrentUrl(); Cookie sessionIdCookie = driver.manage().getCookieNamed("session_id"); String sessionId = null; if (sessionIdCookie != null) { sessionId = sessionIdCookie.getValue(); } System.out.println("authenticateResourceOwnerAndDenyAccess: sessionId:" + sessionId); stopSelenium(); AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr); if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) { authorizationResponse.setResponseMode(ResponseMode.FORM_POST); } authorizationResponse.setSessionId(sessionId); authorizeClient.setResponse(authorizationResponse); showClientUserAgent(authorizeClient); return authorizationResponse; } public AuthorizationResponse authorizationRequestAndGrantAccess( String authorizeUrl, AuthorizationRequest authorizationRequest) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("authorizationRequestAndGrantAccess: authorizationRequestUrl:" + authorizationRequestUrl); startSelenium(); driver.navigate().to(authorizationRequestUrl); String authorizationResponseStr = driver.getCurrentUrl(); WebElement allowButton = driver.findElement(By.id(authorizeFormAllowButton)); final String previousURL = driver.getCurrentUrl(); allowButton.click(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return (d.getCurrentUrl() != previousURL); } }); authorizationResponseStr = driver.getCurrentUrl(); Cookie sessionStateCookie = driver.manage().getCookieNamed("session_state"); String sessionState = null; if (sessionStateCookie != null) { sessionState = sessionStateCookie.getValue(); } System.out.println("authorizationRequestAndGrantAccess: sessionState:" + sessionState); stopSelenium(); AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr); if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) { authorizationResponse.setResponseMode(ResponseMode.FORM_POST); } authorizeClient.setResponse(authorizationResponse); showClientUserAgent(authorizeClient); return authorizationResponse; } public AuthorizationResponse authorizationRequestAndDenyAccess( String authorizeUrl, AuthorizationRequest authorizationRequest) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("authorizationRequestAndDenyAccess: authorizationRequestUrl:" + authorizationRequestUrl); startSelenium(); driver.navigate().to(authorizationRequestUrl); WebElement doNotAllowButton = driver.findElement(By.id(authorizeFormDoNotAllowButton)); final String previousURL = driver.getCurrentUrl(); doNotAllowButton.click(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return (d.getCurrentUrl() != previousURL); } }); String authorizationResponseStr = driver.getCurrentUrl(); Cookie sessionStateCookie = driver.manage().getCookieNamed("session_state"); String sessionState = null; if (sessionStateCookie != null) { sessionState = sessionStateCookie.getValue(); } System.out.println("authorizationRequestAndDenyAccess: sessionState:" + sessionState); stopSelenium(); AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr); if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) { authorizationResponse.setResponseMode(ResponseMode.FORM_POST); } authorizeClient.setResponse(authorizationResponse); showClientUserAgent(authorizeClient); return authorizationResponse; } /** * The authorization server authenticates the resource owner (via the user-agent) * No authorization page. */ public AuthorizationResponse authenticateResourceOwner( String authorizeUrl, AuthorizationRequest authorizationRequest, String userId, String userSecret, boolean cleanupCookies) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("authenticateResourceOwner: authorizationRequestUrl:" + authorizationRequestUrl); startSelenium(); if (cleanupCookies) { System.out.println("authenticateResourceOwner: Cleaning cookies"); deleteAllCookies(); } driver.navigate().to(authorizationRequestUrl); if (userSecret != null) { if (userId != null) { WebElement usernameElement = driver.findElement(By.name(loginFormUsername)); usernameElement.sendKeys(userId); } WebElement passwordElement = driver.findElement(By.name(loginFormPassword)); passwordElement.sendKeys(userSecret); WebElement loginButton = driver.findElement(By.name(loginFormLoginButton)); loginButton.click(); } String authorizationResponseStr = driver.getCurrentUrl(); Cookie sessionStateCookie = driver.manage().getCookieNamed("session_state"); String sessionState = null; if (sessionStateCookie != null) { sessionState = sessionStateCookie.getValue(); } System.out.println("authenticateResourceOwner: sessionState:" + sessionState); stopSelenium(); AuthorizationResponse authorizationResponse = new AuthorizationResponse(authorizationResponseStr); if (authorizationRequest.getRedirectUri() != null && authorizationRequest.getRedirectUri().equals(authorizationResponseStr)) { authorizationResponse.setResponseMode(ResponseMode.FORM_POST); } authorizeClient.setResponse(authorizationResponse); showClientUserAgent(authorizeClient); return authorizationResponse; } /** * Try to open login form (via the user-agent) */ public String waitForResourceOwnerAndGrantLoginForm( String authorizeUrl, AuthorizationRequest authorizationRequest, boolean cleanupCookies) { String authorizationRequestUrl = authorizeUrl + "?" + authorizationRequest.getQueryString(); AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl); authorizeClient.setRequest(authorizationRequest); System.out.println("waitForResourceOwnerAndGrantLoginForm: authorizationRequestUrl:" + authorizationRequestUrl); startSelenium(); if (cleanupCookies) { System.out.println("waitForResourceOwnerAndGrantLoginForm: Cleaning cookies"); deleteAllCookies(); } driver.navigate().to(authorizationRequestUrl); WebElement usernameElement = driver.findElement(By.name(loginFormUsername)); WebElement passwordElement = driver.findElement(By.name(loginFormPassword)); WebElement loginButton = driver.findElement(By.name(loginFormLoginButton)); if ((usernameElement == null) || (passwordElement == null) || (loginButton == null)) { return null; } Cookie sessionStateCookie = driver.manage().getCookieNamed("session_state"); String sessionState = null; if (sessionStateCookie != null) { sessionState = sessionStateCookie.getValue(); } System.out.println("waitForResourceOwnerAndGrantLoginForm: sessionState:" + sessionState); stopSelenium(); showClientUserAgent(authorizeClient); return sessionState; } /** * Try to open login form (via the user-agent) */ public String waitForResourceOwnerAndGrantLoginForm( String authorizeUrl, AuthorizationRequest authorizationRequest) { return waitForResourceOwnerAndGrantLoginForm(authorizeUrl, authorizationRequest, true); } private void deleteAllCookies() { try { driver.manage().deleteAllCookies(); } catch (Exception e) { e.printStackTrace(); } } @BeforeTest public void discovery(ITestContext context) throws Exception { // Load Form Interaction loginFormUsername = context.getCurrentXmlTest().getParameter("loginFormUsername"); loginFormPassword = context.getCurrentXmlTest().getParameter("loginFormPassword"); loginFormLoginButton = context.getCurrentXmlTest().getParameter("loginFormLoginButton"); authorizeFormAllowButton = context.getCurrentXmlTest().getParameter("authorizeFormAllowButton"); authorizeFormDoNotAllowButton = context.getCurrentXmlTest().getParameter("authorizeFormDoNotAllowButton"); String resource = context.getCurrentXmlTest().getParameter("swdResource"); if (StringUtils.isNotBlank(resource)) { showTitle("OpenID Connect Discovery"); OpenIdConnectDiscoveryClient openIdConnectDiscoveryClient = new OpenIdConnectDiscoveryClient(resource); OpenIdConnectDiscoveryResponse openIdConnectDiscoveryResponse = openIdConnectDiscoveryClient.exec(clientExecutor(true)); showClient(openIdConnectDiscoveryClient); assertEquals(openIdConnectDiscoveryResponse.getStatus(), 200, "Unexpected response code"); assertNotNull(openIdConnectDiscoveryResponse.getSubject()); assertTrue(openIdConnectDiscoveryResponse.getLinks().size() > 0); configurationEndpoint = openIdConnectDiscoveryResponse.getLinks().get(0).getHref() + "/.well-known/openid-configuration"; System.out.println("OpenID Connect Configuration"); OpenIdConfigurationClient client = new OpenIdConfigurationClient(configurationEndpoint); client.setExecutor(clientExecutor(true)); OpenIdConfigurationResponse response = client.execOpenIdConfiguration(); showClient(client); assertEquals(response.getStatus(), 200, "Unexpected response code"); assertNotNull(response.getIssuer(), "The issuer is null"); assertNotNull(response.getAuthorizationEndpoint(), "The authorizationEndpoint is null"); assertNotNull(response.getTokenEndpoint(), "The tokenEndpoint is null"); assertNotNull(response.getUserInfoEndpoint(), "The userInfoEndPoint is null"); assertNotNull(response.getJwksUri(), "The jwksUri is null"); assertNotNull(response.getRegistrationEndpoint(), "The registrationEndpoint is null"); assertTrue(response.getScopesSupported().size() > 0, "The scopesSupported is empty"); assertTrue(response.getScopeToClaimsMapping().size() > 0, "The scope to claims mapping is empty"); assertTrue(response.getResponseTypesSupported().size() > 0, "The responseTypesSupported is empty"); assertTrue(response.getGrantTypesSupported().size() > 0, "The grantTypesSupported is empty"); assertTrue(response.getAcrValuesSupported().size() >= 0, "The acrValuesSupported is empty"); assertTrue(response.getSubjectTypesSupported().size() > 0, "The subjectTypesSupported is empty"); assertTrue(response.getIdTokenSigningAlgValuesSupported().size() > 0, "The idTokenSigningAlgValuesSupported is empty"); assertTrue(response.getRequestObjectSigningAlgValuesSupported().size() > 0, "The requestObjectSigningAlgValuesSupported is empty"); assertTrue(response.getTokenEndpointAuthMethodsSupported().size() > 0, "The tokenEndpointAuthMethodsSupported is empty"); assertTrue(response.getClaimsSupported().size() > 0, "The claimsSupported is empty"); authorizationEndpoint = response.getAuthorizationEndpoint(); tokenEndpoint = response.getTokenEndpoint(); userInfoEndpoint = response.getUserInfoEndpoint(); clientInfoEndpoint = response.getClientInfoEndpoint(); checkSessionIFrame = response.getCheckSessionIFrame(); endSessionEndpoint = response.getEndSessionEndpoint(); jwksUri = response.getJwksUri(); registrationEndpoint = response.getRegistrationEndpoint(); idGenEndpoint = response.getIdGenerationEndpoint(); introspectionEndpoint = response.getIntrospectionEndpoint(); scopeToClaimsMapping = response.getScopeToClaimsMapping(); gluuConfigurationEndpoint = determineGluuConfigurationEndpoint(openIdConnectDiscoveryResponse.getLinks().get(0).getHref()); } else { showTitle("Loading configuration endpoints from properties file"); authorizationEndpoint = context.getCurrentXmlTest().getParameter("authorizationEndpoint"); tokenEndpoint = context.getCurrentXmlTest().getParameter("tokenEndpoint"); userInfoEndpoint = context.getCurrentXmlTest().getParameter("userInfoEndpoint"); clientInfoEndpoint = context.getCurrentXmlTest().getParameter("clientInfoEndpoint"); checkSessionIFrame = context.getCurrentXmlTest().getParameter("checkSessionIFrame"); endSessionEndpoint = context.getCurrentXmlTest().getParameter("endSessionEndpoint"); jwksUri = context.getCurrentXmlTest().getParameter("jwksUri"); registrationEndpoint = context.getCurrentXmlTest().getParameter("registrationEndpoint"); configurationEndpoint = context.getCurrentXmlTest().getParameter("configurationEndpoint"); idGenEndpoint = context.getCurrentXmlTest().getParameter("idGenEndpoint"); introspectionEndpoint = context.getCurrentXmlTest().getParameter("introspectionEndpoint"); scopeToClaimsMapping = new HashMap<String, List<String>>(); } authorizationPageEndpoint = determineAuthorizationPageEndpoint(authorizationEndpoint); } private String determineAuthorizationPageEndpoint(String authorizationEndpoint) { return authorizationEndpoint.replace("/restv1/authorize", "/authorize"); } private String determineGluuConfigurationEndpoint(String host) { return host + "/oxauth/restv1/gluu-configuration"; } public void showTitle(String title) { title = "TEST: " + title; System.out.println(" System.out.println(title); System.out.println(" } public void showEntity(String entity) { if (entity != null) { System.out.println("Entity: " + entity.replace("\\n", "\n")); } } public static void showClient(BaseClient client) { ClientUtils.showClient(client); } public static void showClient(BaseClient client, CookieStore cookieStore) { ClientUtils.showClient(client, cookieStore); } public static void showClientUserAgent(BaseClient client) { ClientUtils.showClientUserAgent(client); } public static void assertErrorResponse(BaseResponseWithErrors p_response, IErrorType p_errorType) { assertEquals(p_response.getStatus(), 400, "Unexpected response code. Entity: " + p_response.getEntity()); assertNotNull(p_response.getEntity(), "The entity is null"); assertEquals(p_response.getErrorType(), p_errorType); assertTrue(StringUtils.isNotBlank(p_response.getErrorDescription())); } public static DefaultHttpClient createHttpClient() { return createHttpClient(HostnameVerifierType.DEFAULT); } public static DefaultHttpClient createHttpClient(HostnameVerifierType p_verifierType) { if (p_verifierType != null && p_verifierType != HostnameVerifierType.DEFAULT) { switch (p_verifierType) { case ALLOW_ALL: HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; DefaultHttpClient client = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); return new DefaultHttpClient(mgr, client.getParams()); case DEFAULT: return new DefaultHttpClient(); } } return new DefaultHttpClient(); } public static ClientExecutor clientExecutor() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { return clientExecutor(false); } public static ClientExecutor clientExecutor(boolean trustAll) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { if (trustAll) { return new ApacheHttpClient4Executor(createHttpClientTrustAll()); } return ClientRequest.getDefaultExecutor(); } public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); return new DefaultHttpClient(ccm); } }
package org.geomajas.internal.configuration; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.geomajas.configuration.AttributeInfo; import org.geomajas.configuration.FeatureStyleInfo; import org.geomajas.configuration.LayerInfo; import org.geomajas.configuration.NamedStyleInfo; import org.geomajas.configuration.RasterLayerInfo; import org.geomajas.configuration.VectorLayerInfo; import org.geomajas.configuration.client.ClientApplicationInfo; import org.geomajas.configuration.client.ClientLayerInfo; import org.geomajas.configuration.client.ClientLayerTreeInfo; import org.geomajas.configuration.client.ClientLayerTreeNodeInfo; import org.geomajas.configuration.client.ClientMapInfo; import org.geomajas.configuration.client.ClientVectorLayerInfo; import org.geomajas.configuration.client.ScaleInfo; import org.geomajas.geometry.Bbox; import org.geomajas.geometry.Coordinate; import org.geomajas.geometry.Crs; import org.geomajas.geometry.CrsTransform; import org.geomajas.global.ExceptionCode; import org.geomajas.global.GeomajasException; import org.geomajas.layer.Layer; import org.geomajas.layer.LayerException; import org.geomajas.layer.RasterLayer; import org.geomajas.layer.VectorLayer; import org.geomajas.service.DtoConverterService; import org.geomajas.service.GeoService; import org.geomajas.service.StyleConverterService; import org.geomajas.sld.NamedLayerInfo; import org.geomajas.sld.RuleInfo; import org.geomajas.sld.StyledLayerDescriptorInfo; import org.geomajas.sld.UserLayerInfo; import org.geomajas.sld.UserStyleInfo; import org.geotools.geometry.DirectPosition2D; import org.geotools.referencing.GeodeticCalculator; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import com.vividsolutions.jts.geom.Envelope; /** * Post-processes configuration DTOs. Generally responsible for any behaviour that would violate the DTO contract * (especially for GWT) if it would be added to the configuration objects themselves, such as hooking up client * configurations to their server layers. * * @author Jan De Moerloose */ @Component public class ConfigurationDtoPostProcessor { private static final double METER_PER_INCH = 0.0254; private final Logger log = LoggerFactory.getLogger(ConfigurationDtoPostProcessor.class); @Autowired private DtoConverterService converterService; @Autowired private GeoService geoService; @Autowired private StyleConverterService styleConverterService; @Autowired(required = false) protected Map<String, ClientApplicationInfo> applicationMap = new LinkedHashMap<String, ClientApplicationInfo>(); @Autowired(required = false) protected Map<String, NamedStyleInfo> namedStyleMap = new LinkedHashMap<String, NamedStyleInfo>(); @Autowired(required = false) protected Map<String, Layer<?>> layerMap = new LinkedHashMap<String, Layer<?>>(); @Autowired(required = false) protected Map<String, RasterLayer> rasterLayerMap = new LinkedHashMap<String, RasterLayer>(); @Autowired(required = false) protected Map<String, VectorLayer> vectorLayerMap = new LinkedHashMap<String, VectorLayer>(); @Autowired(required = true) private ApplicationContext applicationContext; public ConfigurationDtoPostProcessor() { } @PostConstruct protected void processConfiguration() throws BeansException { try { for (RasterLayer layer : rasterLayerMap.values()) { postProcess(layer); } for (VectorLayer layer : vectorLayerMap.values()) { postProcess(layer); } for (ClientApplicationInfo application : applicationMap.values()) { postProcess(application); } for (NamedStyleInfo style : namedStyleMap.values()) { postProcess(style); } } catch (LayerException e) { throw new BeanInitializationException("Invalid configuration", e); } } private void postProcess(RasterLayer layer) throws LayerException { RasterLayerInfo info = layer.getLayerInfo(); for (ScaleInfo scale : info.getZoomLevels()) { // for raster layers we don't accept x:y notation ! if (scale.getDenominator() != 0) { throw new LayerException(ExceptionCode.CONVERSION_PROBLEM, "Raster layer " + layer.getId() + " has zoom level " + scale.getNumerator() + ":" + scale.getDenominator() + " in disallowed x:y notation"); } // add the resolution for deprecated api support info.getResolutions().add(1. / scale.getPixelPerUnit()); } } private void postProcess(VectorLayer layer) throws LayerException { VectorLayerInfo info = layer.getLayerInfo(); if (info != null) { // check for invalid attribute names for (AttributeInfo attributeInfo : info.getFeatureInfo().getAttributes()) { if (attributeInfo.getName().contains(".") || attributeInfo.getName().contains("/")) { throw new LayerException(ExceptionCode.INVALID_ATTRIBUTE_NAME, attributeInfo.getName(), layer.getId()); } } // convert sld to old styles for (NamedStyleInfo namedStyle : info.getNamedStyleInfos()) { // check sld location if (namedStyle.getSldLocation() != null) { Resource resource = applicationContext.getResource(namedStyle.getSldLocation()); IBindingFactory bindingFactory; try { bindingFactory = BindingDirectory.getFactory(StyledLayerDescriptorInfo.class); IUnmarshallingContext unmarshallingContext = bindingFactory.createUnmarshallingContext(); StyledLayerDescriptorInfo sld = (StyledLayerDescriptorInfo) unmarshallingContext .unmarshalDocument(new InputStreamReader(resource.getInputStream())); String layerName = (namedStyle.getSldLayerName() != null ? namedStyle.getSldLayerName() : layer .getId()); String styleName = (namedStyle.getSldStyleName() != null ? namedStyle.getSldStyleName() : layer .getId()); namedStyle.setUserStyle(extractStyle(sld, layerName, styleName)); } catch (JiBXException e) { throw new LayerException(e, ExceptionCode.INVALID_SLD, namedStyle.getSldLocation(), layer.getId()); } catch (IOException e) { throw new LayerException(e, ExceptionCode.INVALID_SLD, namedStyle.getSldLocation(), layer.getId()); } NamedStyleInfo sldStyle = styleConverterService.convert(namedStyle.getUserStyle(), info.getFeatureInfo()); namedStyle.setFeatureStyles(sldStyle.getFeatureStyles()); namedStyle.setLabelStyle(sldStyle.getLabelStyle()); } } // check for at least 1 style if (info.getNamedStyleInfos().size() == 0) { info.getNamedStyleInfos().add(new NamedStyleInfo()); } // apply defaults to all styles for (NamedStyleInfo namedStyle : info.getNamedStyleInfos()) { namedStyle.applyDefaults(); } // convert old styles to sld for (NamedStyleInfo namedStyle : info.getNamedStyleInfos()) { if (namedStyle.getUserStyle() == null) { UserStyleInfo userStyle = styleConverterService.convert(namedStyle, info.getLayerType()); namedStyle.setUserStyle(userStyle); } } } } private UserStyleInfo extractStyle(StyledLayerDescriptorInfo sld, String sldLayerName, String sldStyleName) throws LayerException { NamedLayerInfo namedLayerInfo = null; UserLayerInfo userLayerInfo = null; // find first named layer or find by name for (StyledLayerDescriptorInfo.ChoiceInfo choice : sld.getChoiceList()) { // we only support named layers, pick the right name or the first one if (choice.ifNamedLayer()) { if (sldLayerName != null) { if (sldLayerName.equals(choice.getNamedLayer().getName())) { namedLayerInfo = choice.getNamedLayer(); break; } } if (namedLayerInfo == null) { namedLayerInfo = choice.getNamedLayer(); } } else if (choice.ifUserLayer()) { if (sldLayerName != null) { if (sldLayerName.equals(choice.getUserLayer().getName())) { userLayerInfo = choice.getUserLayer(); break; } } if (namedLayerInfo == null) { userLayerInfo = choice.getUserLayer(); } } } if (namedLayerInfo == null && userLayerInfo == null) { throw new LayerException(ExceptionCode.INVALID_SLD, sld.getName(), sldLayerName); } UserStyleInfo userStyleInfo = null; if (namedLayerInfo != null) { for (NamedLayerInfo.ChoiceInfo choice : namedLayerInfo.getChoiceList()) { // we only support user styles, pick the right name or the first if (choice.ifUserStyle()) { if (sldStyleName != null) { if (sldStyleName.equals(choice.getUserStyle().getName())) { userStyleInfo = choice.getUserStyle(); break; } } if (userStyleInfo == null) { userStyleInfo = choice.getUserStyle(); } } } } else if (userLayerInfo != null) { for (UserStyleInfo userStyle : userLayerInfo.getUserStyleList()) { if (sldStyleName != null) { if (sldStyleName.equals(userStyle.getName())) { userStyleInfo = userStyle; break; } } if (userStyleInfo == null) { userStyleInfo = userStyle; } } } if (userStyleInfo == null) { throw new LayerException(ExceptionCode.INVALID_SLD, sld.getName(), sldLayerName); } else { return userStyleInfo; } } private ClientApplicationInfo postProcess(ClientApplicationInfo client) throws LayerException, BeansException { // initialize maps for (ClientMapInfo map : client.getMaps()) { map.setUnitLength(getUnitLength(map.getCrs(), map.getInitialBounds())); // result should be m = (m/inch) / (number/inch) map.setPixelLength(METER_PER_INCH / client.getScreenDpi()); log.debug("Map " + map.getId() + " has unit length : " + map.getUnitLength() + "m, pixel length " + map.getPixelLength() + "m"); // calculate scales double pixPerUnit = map.getUnitLength() / map.getPixelLength(); // if resolutions have been defined the old way, calculate the scale configuration if (map.getResolutions().size() > 0) { for (Double resolution : map.getResolutions()) { if (map.isResolutionsRelative()) { map.getScaleConfiguration().getZoomLevels().add(new ScaleInfo(1., resolution)); } else { map.getScaleConfiguration().getZoomLevels().add(new ScaleInfo(1. / resolution)); } } map.getResolutions().clear(); } // convert the scales so we have both relative and pix/unit boolean relativeScales = true; for (ScaleInfo scale : map.getScaleConfiguration().getZoomLevels()) { if (scale.getDenominator() == 0) { relativeScales = false; } else if (!relativeScales) { throw new LayerException(ExceptionCode.SCALE_CONVERSION_PROBLEM, map.getId()); } completeScale(scale, pixPerUnit); // add the resolution for deprecated api support if (!map.isResolutionsRelative()) { map.getResolutions().add(1. / scale.getPixelPerUnit()); } else { map.getResolutions().add(scale.getDenominator() / scale.getNumerator()); } } completeScale(map.getScaleConfiguration().getMaximumScale(), pixPerUnit); for (ClientLayerInfo layer : map.getLayers()) { String layerId = layer.getServerLayerId(); Layer<?> serverLayer = layerMap.get(layerId); if (serverLayer == null) { throw new LayerException(ExceptionCode.LAYER_NOT_FOUND, layerId); } LayerInfo layerInfo = serverLayer.getLayerInfo(); layer.setLayerInfo(layerInfo); layer.setMaxExtent(getClientMaxExtent(map.getCrs(), layer.getCrs(), layerInfo.getMaxExtent(), layerId)); completeScale(layer.getMaximumScale(), pixPerUnit); completeScale(layer.getMinimumScale(), pixPerUnit); log.debug("Layer " + layer.getId() + " has scale range : " + layer.getMinimumScale().getPixelPerUnit() + "," + layer.getMaximumScale().getPixelPerUnit()); if (layer instanceof ClientVectorLayerInfo) { postProcess((ClientVectorLayerInfo) layer); } } checkLayerTree(map); } return client; } private ClientVectorLayerInfo postProcess(ClientVectorLayerInfo layer) throws LayerException { // copy feature info from server if not explicitly defined if (layer.getFeatureInfo() == null) { VectorLayerInfo serverInfo = (VectorLayerInfo) layer.getLayerInfo(); layer.setFeatureInfo(serverInfo.getFeatureInfo()); } return layer; } private NamedStyleInfo postProcess(NamedStyleInfo client) { // index styles/rules int i = 0; for (FeatureStyleInfo style : client.getFeatureStyles()) { style.setIndex(i++); style.setStyleId(client.getName() + "-" + style.getIndex()); } i = 0; if (client.getUserStyle() != null) { for (RuleInfo rule : client.getUserStyle().getFeatureTypeStyleList().get(0).getRuleList()) { rule.setName(client.getName() + "-" + i++); } } return client; } private double getUnitLength(String mapCrsKey, Bbox mapBounds) throws LayerException { try { if (null == mapBounds) { throw new LayerException(ExceptionCode.MAP_MAX_EXTENT_MISSING); } Crs crs = geoService.getCrs2(mapCrsKey); GeodeticCalculator calculator = new GeodeticCalculator(crs); Coordinate center = new Coordinate(0.5 * (mapBounds.getX() + mapBounds.getMaxX()), 0.5 * (mapBounds.getY() + mapBounds.getMaxY())); calculator.setStartingPosition(new DirectPosition2D(crs, center.getX(), center.getY())); calculator.setDestinationPosition(new DirectPosition2D(crs, center.getX() + 1, center.getY())); return calculator.getOrthodromicDistance(); } catch (TransformException e) { throw new LayerException(e, ExceptionCode.TRANSFORMER_CREATE_LAYER_TO_MAP_FAILED); } } public Bbox getClientMaxExtent(String mapCrsKey, String layerCrsKey, Bbox serverBbox, String layer) throws LayerException { if (mapCrsKey.equals(layerCrsKey)) { return serverBbox; } try { Crs mapCrs = geoService.getCrs2(mapCrsKey); Crs layerCrs = geoService.getCrs2(layerCrsKey); Envelope serverEnvelope = converterService.toInternal(serverBbox); CrsTransform transformer = geoService.getCrsTransform(layerCrs, mapCrs); Bbox res = converterService.toDto(geoService.transform(serverEnvelope, transformer)); if (Double.isNaN(res.getX()) || Double.isNaN(res.getY()) || Double.isNaN(res.getWidth()) || Double.isNaN(res.getHeight())) { throw new LayerException(ExceptionCode.LAYER_EXTENT_CANNOT_CONVERT, layer, mapCrsKey); } return res; } catch (GeomajasException e) { throw new LayerException(e, ExceptionCode.TRANSFORMER_CREATE_LAYER_TO_MAP_FAILED); } } /** * Convert the scale in pixels per unit or relative values, which ever is missing. * * @param scaleInfo scaleInfo object which needs to be completed * @param mapUnitInPixels the number of pixels in a map unit */ public void completeScale(ScaleInfo scaleInfo, double mapUnitInPixels) { if (0 == mapUnitInPixels) { throw new IllegalArgumentException("ScaleInfo.completeScale mapUnitInPixels should never be zero."); } double denominator = scaleInfo.getDenominator(); double numerator = scaleInfo.getNumerator(); if (denominator != 0) { scaleInfo.setPixelPerUnit(numerator / denominator * mapUnitInPixels); } else { double pixelPerUnit = scaleInfo.getPixelPerUnit(); if (pixelPerUnit > mapUnitInPixels) { scaleInfo.setNumerator(pixelPerUnit / mapUnitInPixels); scaleInfo.setDenominator(1); } else { scaleInfo.setNumerator(1); scaleInfo.setDenominator(mapUnitInPixels / pixelPerUnit); } } } private void checkLayerTree(ClientMapInfo map) throws BeansException { // if the map contains a layer tree, verify that the layers are part of the map ClientLayerTreeInfo layerTree = map.getLayerTree(); if (null != layerTree) { checkTreeNode(map, layerTree.getTreeNode()); } } private void checkTreeNode(ClientMapInfo map, ClientLayerTreeNodeInfo node) throws BeansException { for (ClientLayerInfo layer : node.getLayers()) { if (!mapContains(map, layer)) { throw new BeanInitializationException( "A LayerTreeNodeInfo object can only reference layers which are part of the map, layer " + layer.getId() + " is not part of map " + map.getId() + "."); } } for (ClientLayerTreeNodeInfo child : node.getTreeNodes()) { checkTreeNode(map, child); } } private boolean mapContains(ClientMapInfo map, ClientLayerInfo layer) { String id = layer.getId(); boolean res = false; if (null != id) { for (ClientLayerInfo mapLayer : map.getLayers()) { res |= id.equals(mapLayer.getId()); } } return res; } }
package helloTriangle; import com.jogamp.nativewindow.util.Dimension; import com.jogamp.newt.Display; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.GL; import static com.jogamp.opengl.GL.GL_INVALID_ENUM; import static com.jogamp.opengl.GL.GL_INVALID_FRAMEBUFFER_OPERATION; import static com.jogamp.opengl.GL.GL_INVALID_OPERATION; import static com.jogamp.opengl.GL.GL_INVALID_VALUE; import static com.jogamp.opengl.GL.GL_NO_ERROR; import static com.jogamp.opengl.GL.GL_OUT_OF_MEMORY; import static com.jogamp.opengl.GL2ES2.GL_FRAGMENT_SHADER; import static com.jogamp.opengl.GL2ES2.GL_VERTEX_SHADER; import com.jogamp.opengl.GL4; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.math.FloatUtil; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLBuffers; import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; import framework.Semantic; import java.nio.ByteBuffer; import java.nio.ShortBuffer; /** * * @author gbarbieri */ public class HelloTriangle implements GLEventListener, KeyListener { private static int screenIdx = 0; private static Dimension windowSize = new Dimension(1024, 768); private static boolean undecorated = false; private static boolean alwaysOnTop = false; private static boolean fullscreen = false; private static boolean mouseVisible = true; private static boolean mouseConfined = false; public static GLWindow glWindow; public static Animator animator; public static void main(String[] args) { Display display = NewtFactory.createDisplay(null); Screen screen = NewtFactory.createScreen(display, screenIdx); GLProfile glProfile = GLProfile.get(GLProfile.GL4); GLCapabilities glCapabilities = new GLCapabilities(glProfile); glWindow = GLWindow.create(screen, glCapabilities); glWindow.setSize(windowSize.getWidth(), windowSize.getHeight()); glWindow.setPosition(50, 50); glWindow.setUndecorated(undecorated); glWindow.setAlwaysOnTop(alwaysOnTop); glWindow.setFullscreen(fullscreen); glWindow.setPointerVisible(mouseVisible); glWindow.confinePointer(mouseConfined); glWindow.setVisible(true); HelloTriangle helloTriangle = new HelloTriangle(); glWindow.addGLEventListener(helloTriangle); glWindow.addKeyListener(helloTriangle); animator = new Animator(glWindow); animator.start(); } private int[] objects = new int[Semantic.Object.size]; // Position interleaved with colors (to be normalized). private byte[] vertexData = new byte[]{ (byte) -1, (byte) -1, (byte) Byte.MAX_VALUE, (byte) 0, (byte) 0, (byte) +0, (byte) +2, (byte) 0, (byte) 0, (byte) Byte.MAX_VALUE, (byte) +1, (byte) -1, (byte) 0, (byte) Byte.MAX_VALUE, (byte) 0 }; private short[] indexData = new short[]{ 0, 2, 1 }; private int program, modelToClipMatrixUL; private final String SHADERS_ROOT = "src/helloTriangle/shaders"; /** Use pools, you don't want to create and let them cleaned by the garbage collector continuosly in the display() method. */ private float[] scale = new float[16]; private float[] zRotazion = new float[16]; private float[] modelToClip = new float[16]; private long start, now; public HelloTriangle() { } @Override public void init(GLAutoDrawable drawable) { System.out.println("init"); GL4 gl4 = drawable.getGL().getGL4(); initVbo(gl4); initIbo(gl4); initVao(gl4); initProgram(gl4); gl4.glEnable(GL4.GL_DEPTH_TEST); start = System.currentTimeMillis(); } private void initVbo(GL4 gl4) { gl4.glGenBuffers(1, objects, Semantic.Object.vbo); gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, objects[Semantic.Object.vbo]); { ByteBuffer vertexBuffer = GLBuffers.newDirectByteBuffer(vertexData); int size = vertexData.length * GLBuffers.SIZEOF_BYTE; gl4.glBufferData(GL4.GL_ARRAY_BUFFER, size, vertexBuffer, GL4.GL_STATIC_DRAW); } gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); checkError(gl4, "initVbo"); } private void initIbo(GL4 gl4) { gl4.glGenBuffers(1, objects, Semantic.Object.ibo); gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, objects[Semantic.Object.ibo]); { ShortBuffer indexBuffer = GLBuffers.newDirectShortBuffer(indexData); int size = indexData.length * GLBuffers.SIZEOF_SHORT; gl4.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, size, indexBuffer, GL4.GL_STATIC_DRAW); } gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0); checkError(gl4, "initIbo"); } private void initVao(GL4 gl4) { /** Let's create the VAO and save in it all the attributes properties. */ gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, objects[Semantic.Object.vbo]); { gl4.glGenVertexArrays(1, objects, Semantic.Object.vao); gl4.glBindVertexArray(objects[Semantic.Object.vao]); { gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, objects[Semantic.Object.ibo]); { int stride = (2 + 3) * GLBuffers.SIZEOF_BYTE; /** We draw 2D, so we need just two coordinates for the position. */ gl4.glEnableVertexAttribArray(Semantic.Attr.position); gl4.glVertexAttribPointer(Semantic.Attr.position, 2, GL4.GL_BYTE, false, stride, 0 * GLBuffers.SIZEOF_BYTE); /** Color needs three coordinates. We show the usage of normalization, where signed value get normalized [-1, 1] like in this case. unsigned will get normalized in the [0, 1] instead, but take in account java use always signed, althought you can trick it. */ gl4.glEnableVertexAttribArray(Semantic.Attr.color); gl4.glVertexAttribPointer(Semantic.Attr.color, 3, GL4.GL_BYTE, true, stride, 2 * GLBuffers.SIZEOF_BYTE); } } /** In this sample we bind VBO and VAO to the default values, this is not a cheapier binding, it costs always as a binding, so here we have for example 2 vbo and 2 vao bindings. Every binding means additional validation and overhead, this may affect your performances. So if you are looking for high performances skip these calls, but remember that OpenGL is a state machine, so what you left bound remains bound! */ gl4.glBindVertexArray(0); } gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); checkError(gl4, "initVao"); } private void initProgram(GL4 gl4) { ShaderCode vertShader = ShaderCode.create(gl4, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null, "vs", "glsl", null, true); ShaderCode fragShader = ShaderCode.create(gl4, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null, "fs", "glsl", null, true); ShaderProgram shaderProgram = new ShaderProgram(); shaderProgram.add(vertShader); shaderProgram.add(fragShader); shaderProgram.init(gl4); program = shaderProgram.program(); /** These links don't go into effect until you link the program. If you want to change index, you need to link the program again. */ gl4.glBindAttribLocation(program, Semantic.Attr.position, "position"); gl4.glBindAttribLocation(program, Semantic.Attr.color, "color"); gl4.glBindFragDataLocation(program, Semantic.Frag.color, "outputColor"); shaderProgram.link(gl4, System.out); /** Take in account that JOGL offers a GLUniformData class, here we don't use it, but take a look to it since it may be interesting for you. */ modelToClipMatrixUL = gl4.glGetUniformLocation(program, "modelToClipMatrix"); checkError(gl4, "initProgram"); } @Override public void dispose(GLAutoDrawable drawable) { System.out.println("dispose"); GL4 gl4 = drawable.getGL().getGL4(); gl4.glDeleteProgram(program); /** Clean VAO first in order to minimize problems. If you delete IBO first, VAO will still have the IBO id, this may lead to crashes. */ gl4.glDeleteVertexArrays(1, objects, objects[Semantic.Object.vao]); gl4.glDeleteBuffers(1, objects, Semantic.Object.vbo); gl4.glDeleteBuffers(1, objects, Semantic.Object.ibo); System.exit(0); } @Override public void display(GLAutoDrawable drawable) { // System.out.println("display"); GL4 gl4 = drawable.getGL().getGL4(); /** We set the clear color and depth (althought depth is not necessary since it is 1 by default). */ gl4.glClearColor(0f, .33f, 0.66f, 1f); gl4.glClearDepthf(1f); gl4.glClear(GL4.GL_COLOR_BUFFER_BIT | GL4.GL_DEPTH_BUFFER_BIT); gl4.glUseProgram(program); { /** VBO still needs to be bound because it is not part of VAO. */ gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, objects[Semantic.Object.vbo]); { gl4.glBindVertexArray(objects[Semantic.Object.vao]); { now = System.currentTimeMillis(); float diff = (float) (now - start) / 1000; scale = FloatUtil.makeScale(scale, true, 0.5f, 0.5f, 0.5f); zRotazion = FloatUtil.makeRotationEuler(zRotazion, 0, 0, 0, diff); modelToClip = FloatUtil.multMatrix(scale, zRotazion); gl4.glUniformMatrix4fv(modelToClipMatrixUL, 1, false, modelToClip, 0); gl4.glDrawElements(GL4.GL_TRIANGLES, indexData.length, GL4.GL_UNSIGNED_SHORT, 0); } gl4.glBindVertexArray(0); } gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); } gl4.glUseProgram(0); checkError(gl4, "display"); } protected boolean checkError(GL gl, String title) { int error = gl.glGetError(); if (error != GL_NO_ERROR) { String errorString; switch (error) { case GL_INVALID_ENUM: errorString = "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: errorString = "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: errorString = "GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: errorString = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: errorString = "GL_OUT_OF_MEMORY"; break; default: errorString = "UNKNOWN"; break; } System.out.println("OpenGL Error(" + errorString + "): " + title); throw new Error(); } return error == GL_NO_ERROR; } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { System.out.println("reshape"); GL4 gl4 = drawable.getGL().getGL4(); /** Just the glViewport for this sample, normally here you update your projection matrix. */ gl4.glViewport(x, y, width, height); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { HelloTriangle.animator.stop(); HelloTriangle.glWindow.destroy(); } } @Override public void keyReleased(KeyEvent e) { } }
package org.jbpm.simulation; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.eclipse.bpmn2.Activity; import org.eclipse.bpmn2.BoundaryEvent; import org.eclipse.bpmn2.Bpmn2Package; import org.eclipse.bpmn2.CompensateEventDefinition; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.DocumentRoot; import org.eclipse.bpmn2.EndEvent; import org.eclipse.bpmn2.Event; import org.eclipse.bpmn2.EventDefinition; import org.eclipse.bpmn2.ExclusiveGateway; import org.eclipse.bpmn2.FlowElement; import org.eclipse.bpmn2.Gateway; import org.eclipse.bpmn2.GatewayDirection; import org.eclipse.bpmn2.InclusiveGateway; import org.eclipse.bpmn2.IntermediateCatchEvent; import org.eclipse.bpmn2.IntermediateThrowEvent; import org.eclipse.bpmn2.LinkEventDefinition; import org.eclipse.bpmn2.MessageEventDefinition; import org.eclipse.bpmn2.ParallelGateway; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.RootElement; import org.eclipse.bpmn2.SequenceFlow; import org.eclipse.bpmn2.SignalEventDefinition; import org.eclipse.bpmn2.StartEvent; import org.eclipse.bpmn2.SubProcess; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.Resource.Diagnostic; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.FeatureMap; import org.jbpm.simulation.PathContext.Type; import org.jbpm.simulation.util.JBPMBpmn2ResourceFactoryImpl; import org.jbpm.simulation.util.JBPMBpmn2ResourceImpl; public class ProcessPathFinder { private List<FlowElement> processElements = new ArrayList<FlowElement>(); private Map<String, FlowElement> catchingEvents = new HashMap<String, FlowElement>(); private List<PathContext> completePaths = new ArrayList<PathContext>(); private Stack<PathContext> paths = new Stack<PathContext>(); public void findPath(String bpmn2) throws IOException { findPath(getDefinitions(streamToString(this.getClass() .getResourceAsStream(bpmn2)))); } public void findPath(Definitions def) throws IOException { List<RootElement> rootElements = def.getRootElements(); for (RootElement root : rootElements) { if (root instanceof Process) { Process process = (Process) root; // find flow elements and traverse it find path List<FlowElement> flowElements = process.getFlowElements(); for (FlowElement fElement : flowElements) { if (fElement instanceof StartEvent) { processElements.add(0, fElement); } else if (fElement instanceof IntermediateCatchEvent) { String key = null; List<EventDefinition> eventDefinitions = ((IntermediateCatchEvent) fElement) .getEventDefinitions(); if (eventDefinitions != null) { for (EventDefinition edef : eventDefinitions) { if (edef instanceof SignalEventDefinition) { key = ((SignalEventDefinition) edef) .getSignalRef(); } else if (edef instanceof MessageEventDefinition) { key = ((MessageEventDefinition) edef) .getMessageRef().getId(); } else if (edef instanceof LinkEventDefinition) { key = ((LinkEventDefinition) edef).getName(); } else if (edef instanceof CompensateEventDefinition) { key = ((CompensateEventDefinition) edef) .getActivityRef().getId(); } if (key != null) { catchingEvents.put(key, fElement); } } } } } } } // show what was found for (FlowElement fe : processElements) { if (fe instanceof StartEvent) { traverseGraph(fe); } } for (PathContext context : this.paths) { if (context.getType() != PathContext.Type.ROOT) { this.completePaths.add(context); } } } protected void traverseGraph(FlowElement startAt) { PathContext context = getContextFromStack(); addToPath(startAt, context); List<SequenceFlow> outgoing = null; if (startAt instanceof StartEvent) { outgoing = ((StartEvent) startAt).getOutgoing(); } else if (startAt instanceof SubProcess) { SubProcess subProcess = ((SubProcess) startAt); // process internal nodes of the sub process List<FlowElement> sbElements = subProcess.getFlowElements(); StartEvent start = null; for (FlowElement sbElement : sbElements) { if (sbElement instanceof StartEvent) { start = (StartEvent) sbElement; break; } } boolean canBeFinsihed = getContextFromStack().isCanBeFinished(); getContextFromStack().setCanBeFinished(false); traverseGraph(start); getContextFromStack().setCanBeFinished(canBeFinsihed); outgoing = subProcess.getOutgoing(); } else if (startAt instanceof Event) { outgoing = ((Event) startAt).getOutgoing(); } else if (startAt instanceof Activity) { outgoing = ((Activity) startAt).getOutgoing(); } else if (startAt instanceof EndEvent) { outgoing = ((EndEvent) startAt).getOutgoing(); } else if (startAt instanceof Gateway) { Gateway gateway = ((Gateway) startAt); outgoing = gateway.getOutgoing(); } if (outgoing != null && !outgoing.isEmpty()) { if (startAt instanceof Gateway) { Gateway gateway = ((Gateway) startAt); if (gateway.getGatewayDirection() == GatewayDirection.DIVERGING) { if (gateway instanceof ExclusiveGateway) { handleExclusiveGateway(outgoing); } else if (gateway instanceof ParallelGateway) { handleParallelGateway(outgoing); } else if (gateway instanceof InclusiveGateway) { handleInclusiveGateway(outgoing); } } else { handleSimpleNode(outgoing); } } else if (startAt instanceof Activity) { handleBoundaryEvent(startAt); } else { handleSimpleNode(outgoing); } } else { List<EventDefinition> throwDefinitions = getEventDefinitions(startAt); if (throwDefinitions != null && throwDefinitions.size() > 0) { for (EventDefinition def : throwDefinitions) { String key = ""; if (def instanceof SignalEventDefinition) { key = ((SignalEventDefinition) def).getSignalRef(); } else if (def instanceof MessageEventDefinition) { key = ((MessageEventDefinition) def).getMessageRef() .getId(); } else if (def instanceof LinkEventDefinition) { key = ((LinkEventDefinition) def).getName(); } else if (def instanceof CompensateEventDefinition) { key = ((CompensateEventDefinition) def) .getActivityRef().getId(); } FlowElement catchEvent = this.catchingEvents.get(key); if (catchEvent != null) { traverseGraph(catchEvent); } else { // not supported event definition finalizePath(); } } } else { finalizePath(); } } } protected List<EventDefinition> getEventDefinitions(FlowElement startAt) { List<EventDefinition> throwDefinitions = null; if (startAt instanceof IntermediateThrowEvent) { throwDefinitions = ((IntermediateThrowEvent) startAt) .getEventDefinitions(); } else if (startAt instanceof EndEvent) { EndEvent end = (EndEvent) startAt; throwDefinitions = end.getEventDefinitions(); } return throwDefinitions; } protected void addToPath(FlowElement element, PathContext context) { if (context.getType() == Type.ROOT) { context.addPathElement(element); } else { // add nodes to all active contexts for (PathContext ctx : this.paths) { if (ctx.getType() != PathContext.Type.ROOT) { ctx.addPathElement(element); } } } } protected PathContext getContextFromStack() { if (this.paths.isEmpty()) { this.paths.push(new PathContext()); } return this.paths.peek(); } protected void finalizePath() { PathContext context = getContextFromStack(); if (context.isCanBeFinished() /* * && context.getType() != * PathContext.Type.ROOT */) { // no outgoing sequence flow means end of path PathContext completePath = this.paths.pop(); this.completePaths.add(completePath); } } public List<PathContext> getCompletePaths() { return completePaths; } protected void handleExclusiveGateway(List<SequenceFlow> outgoing) { List<PathContext> locked = new ArrayList<PathContext>(); PathContext context = getContextFromStack(); for (SequenceFlow seqFlow : outgoing) { FlowElement target = seqFlow.getTargetRef(); PathContext separatePath = context.cloneGiven(context); this.paths.push(separatePath); addToPath(seqFlow, separatePath); traverseGraph(target); separatePath.setLocked(true); locked.add(separatePath); } // unlock for (PathContext ctx : locked) { ctx.setLocked(false); } } protected void handleSimpleNode(List<SequenceFlow> outgoing) { for (SequenceFlow seqFlow : outgoing) { FlowElement target = seqFlow.getTargetRef(); addToPath(seqFlow, getContextFromStack()); traverseGraph(target); } } protected void handleInclusiveGateway(List<SequenceFlow> outgoing) { // firstly cover simple xor based - number of paths is equal to number // of outgoing handleExclusiveGateway(outgoing); // next cover all combinations of paths if (outgoing.size() > 2) { List<SequenceFlow> copy = new ArrayList<SequenceFlow>(outgoing); List<SequenceFlow> andCombination = null; for (SequenceFlow flow : outgoing) { // first remove one that we currently processing as that is not // a combination copy.remove(flow); for (SequenceFlow copyFlow : copy) { PathContext separatePath = getContextFromStack() .cloneCurrent(); this.paths.push(separatePath); andCombination = new ArrayList<SequenceFlow>(); andCombination.add(flow); andCombination.add(copyFlow); handleParallelGateway(andCombination); } } } // lastly cover and based - is single path that goes through all at the // same time handleParallelGateway(outgoing); } protected void handleParallelGateway(List<SequenceFlow> outgoing) { PathContext context = getContextFromStack(); context.setCanBeFinished(false); int counter = 0; for (SequenceFlow seqFlow : outgoing) { counter++; FlowElement target = seqFlow.getTargetRef(); if (counter == outgoing.size()) { context.setCanBeFinished(true); } addToPath(seqFlow, context); traverseGraph(target); } } private void handleBoundaryEvent(FlowElement startAt) { PathContext context = getContextFromStack(); List<SequenceFlow> outgoing = ((Activity) startAt).getOutgoing(); List<BoundaryEvent> bEvents = ((Activity) startAt) .getBoundaryEventRefs(); if (bEvents != null && bEvents.size() > 0) { for (BoundaryEvent bEvent : bEvents) { addToPath(bEvent, context); outgoing.addAll(bEvent.getOutgoing()); } handleInclusiveGateway(outgoing); } else { handleSimpleNode(outgoing); } } public Definitions getDefinitions(String xml) { try { ResourceSet resourceSet = new ResourceSetImpl(); resourceSet .getResourceFactoryRegistry() .getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new JBPMBpmn2ResourceFactoryImpl()); resourceSet.getPackageRegistry().put( "http: Bpmn2Package.eINSTANCE); JBPMBpmn2ResourceImpl resource = (JBPMBpmn2ResourceImpl) resourceSet .createResource(URI .createURI("inputStream://dummyUriWithValidSuffix.xml")); resource.getDefaultLoadOptions().put( JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); resource.setEncoding("UTF-8"); Map<String, Object> options = new HashMap<String, Object>(); options.put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); resource.load(is, options); EList<Diagnostic> warnings = resource.getWarnings(); if (warnings != null && !warnings.isEmpty()) { for (Diagnostic diagnostic : warnings) { System.out.println("Warning: " + diagnostic.getMessage()); } } EList<Diagnostic> errors = resource.getErrors(); if (errors != null && !errors.isEmpty()) { for (Diagnostic diagnostic : errors) { System.out.println("Error: " + diagnostic.getMessage()); } throw new IllegalStateException( "Error parsing process definition"); } return ((DocumentRoot) resource.getContents().get(0)) .getDefinitions(); } catch (Throwable t) { t.printStackTrace(); return null; } } private static boolean isAdHocProcess(Process process) { Iterator<FeatureMap.Entry> iter = process.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("adHoc")) { return Boolean.parseBoolean(((String)entry.getValue()).trim()); } } return false; } private static String streamToString(InputStream is) { try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); return sb.toString(); } catch (Exception e) { return ""; } } }
/* * $Log$ * Revision 1.2 1999/12/21 13:54:33 apr * BugFix: get intValue() * * Revision 1.1 1999/12/21 12:15:09 apr * Added ReliableSequencer * */ package uy.com.cs.jpos.core; import java.io.*; import java.util.*; import uy.com.cs.jpos.iso.Loggeable; import com.sun.jini.reliableLog.ReliableLog; import com.sun.jini.reliableLog.LogException; import com.sun.jini.reliableLog.LogHandler; /** * @author apr@cs.com.uy * @version $Id$ * @since jPOS 1.1 * * A production grade Sequencer based on com.sun.jini.reliableLog * (you'll need a copy of sun-util.jar in your classpath in order * to use it) * */ public class ReliableSequencer extends LogHandler implements Sequencer, Loggeable { private Map map; private ReliableLog log; public static final int MAXLOGSIZE = 200000; private ReliableSequencer () { map = new HashMap(); log = null; } /** * constructs and setup a ReliableSequencer object */ public static ReliableSequencer createInstance (String dir) throws IOException { ReliableSequencer seq = new ReliableSequencer(); ReliableLog log = new ReliableLog (dir, seq); log.recover(); log.snapshot(); seq.setReliableLog (log); return seq; } /** * @param counterName * @param add increment * @return counterName's value + add */ synchronized public int get (String counterName, int add) { int i = 0; Integer I = (Integer) map.get (counterName); if (I != null) i = I.intValue(); I = new Integer (i + add); map.put (counterName, I); try { log.update (new LogEntry (counterName, I), true); if (log.logSize() > MAXLOGSIZE) log.snapshot(); } catch (LogException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return I.intValue(); } /** * @param counterName * @return counterName's value + 1 */ public int get (String counterName) { return get (counterName, 1); } /** * @param counterName * @param newValue * @return oldValue */ synchronized public int set (String counterName, int newValue) { Integer I = new Integer (newValue); Integer oldValue = (Integer) map.put (counterName, I); try { log.update (new LogEntry (counterName, I), true); if (log.logSize() > MAXLOGSIZE) log.snapshot(); } catch (LogException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return oldValue == null ? 0 : oldValue.intValue(); } /** * @param log an already recovered - ready to use ReliableLog */ public void setReliableLog (ReliableLog log) { this.log = log; } public void snapshot(OutputStream out) throws Exception { ObjectOutputStream stream = new ObjectOutputStream(out); stream.writeUTF(this.getClass().getName()); stream.writeObject(map); stream.writeObject(null); stream.flush(); } public void recover(InputStream in) throws Exception { ObjectInputStream stream = new ObjectInputStream(in); if (!this.getClass().getName().equals(stream.readUTF())) throw new IOException("log from wrong implementation"); map = (Map) stream.readObject(); } public void applyUpdate(Object update) throws Exception { if (!(update instanceof LogEntry)) throw new Exception ("not a LogEntry"); LogEntry entry = (LogEntry) update; map.put (entry.key, entry.value); } public static class LogEntry implements Serializable { public Object key, value; public LogEntry (Object key, Object value) { this.key = key; this.value = value; } } public void dump (PrintStream p, String indent) { String inner = indent + " "; p.println (indent + "<ReliableSequencer>"); Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry) i.next(); p.println (inner + "<seq name=\""+e.getKey() +"\" value=\""+e.getValue()+"\"/>" ); } p.println (indent + "</ReliableSequencer>"); } public static int usage () { System.out.println ("Usage: ReliableLog logdir counterName intValue"); return 1; } public static void main (String args[]) { if (args.length < 3) System.exit (usage()); String dir = args[0]; String key = args[1]; int val = Integer.parseInt (args[2]); try { ReliableSequencer seq = ReliableSequencer.createInstance(dir); System.out.println (key + " was " + seq.set (key, val)); } catch (Exception e) { e.printStackTrace(); } } }
package org.jmxtrans.agent; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.Map; import java.util.logging.Level; import org.jmxtrans.agent.util.ConfigurationUtils; public class StatsDOutputWriter extends AbstractOutputWriter implements OutputWriter { private final static String SETTING_HOST = "host"; private final static String SETTING_PORT = "port"; private final static String SETTING_ROOT_PREFIX = "metricName"; private final static String SETTING_BUFFER_SIZE = "bufferSize"; private final static int SETTING_DEFAULT_BUFFER_SIZE = 1024; private final static String PATTERN = "%s.%s:%s|c\n"; private ByteBuffer sendBuffer; private String metricNamePrefix; private InetSocketAddress address; private DatagramChannel channel; @Override public void postConstruct(Map<String, String> settings) { super.postConstruct(settings); String host = ConfigurationUtils.getString(settings, SETTING_HOST); Integer port = ConfigurationUtils.getInt(settings, SETTING_PORT); metricNamePrefix = getMetricNameOrDefaultValue(settings); if (port == null || nullOrEmpty(host)) { throw new RuntimeException("Host and/or port cannot be null"); } int bufferSize = ConfigurationUtils.getInt(settings, SETTING_BUFFER_SIZE, SETTING_DEFAULT_BUFFER_SIZE); sendBuffer = ByteBuffer.allocate(bufferSize); try { address = new InetSocketAddress(host, port); channel = DatagramChannel.open(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to open channel"); throw new RuntimeException(e); } logger.info(String.format("StatsDOutputWriter[host=%s, port=%d, metricNamePrefix=%s]", host, port, metricNamePrefix)); } private String getMetricNameOrDefaultValue(Map<String, String> settings) { String metricName = ConfigurationUtils.getString(settings, SETTING_ROOT_PREFIX); if (nullOrEmpty(metricName)) { return getHostName().replaceAll("\\.", "_"); } else { return metricName; } } private String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e1) { return "unknown.host"; } } } private boolean nullOrEmpty(String value) { return value == null || value.trim().isEmpty(); } @Override public void postCollect() throws IOException { // Ensure data flush flush(); } @Override public void writeInvocationResult(String invocationName, Object value) throws IOException { writeQueryResult(invocationName, null, value); } @Override public void writeQueryResult(String metricName, String metricType, Object value) throws IOException { String stats = String.format(PATTERN, metricNamePrefix, metricName, value); logger.log(getDebugLevel(), "Sending msg: " + stats); doSend(stats); } private synchronized boolean doSend(String stat) { try { final byte[] data = stat.getBytes("utf-8"); // If we're going to go past the threshold of the buffer then flush. // the +1 is for the potential '\n' in multi_metrics below if (sendBuffer.remaining() < (data.length + 1)) { flush(); } sendBuffer.put(data); // append the data return true; } catch (IOException e) { logger.log(Level.SEVERE, String.format( "Could not send stat %s to host %s:%d", sendBuffer.toString(), address.getHostName(), address.getPort()), e); return false; } } public synchronized boolean flush() { try { final int sizeOfBuffer = sendBuffer.position(); if (sizeOfBuffer <= 0) { return false; } // empty buffer // send and reset the buffer sendBuffer.flip(); final int nbSentBytes = channel.send(sendBuffer, address); sendBuffer.limit(sendBuffer.capacity()); sendBuffer.rewind(); if (sizeOfBuffer == nbSentBytes) { return true; } else { logger.log(Level.SEVERE, String.format( "Could not send entirely stat %s to host %s:%d. Only sent %d bytes out of %d bytes", sendBuffer.toString(), address.getHostName(), address.getPort(), nbSentBytes, sizeOfBuffer)); return false; } } catch (IOException e) { logger.log(Level.SEVERE, String.format("Could not send stat %s to host %s:%d", sendBuffer.toString(), address.getHostName(), address.getPort()), e); return false; } } }
package org.jpos.core; import org.jpos.util.Loggeable; import org.yaml.snakeyaml.Yaml; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Environment implements Loggeable { private static final String SYSTEM_PREFIX = "sys"; private static final String ENVIRONMENT_PREFIX = "env"; private static Pattern valuePattern = Pattern.compile("^(\\$*)(\\$)([\\w\\W]*)?\\{([\\w\\W]+)\\}([\\w\\W]*)$" ); private static Pattern verbPattern = Pattern.compile("^\\$verb\\{([\\w\\W]+)\\}$"); private static Environment INSTANCE; private String name; private AtomicReference<Properties> propRef = new AtomicReference<>(new Properties()); static { try { INSTANCE = new Environment(); } catch (Throwable e) { e.printStackTrace(); throw new RuntimeException(e); } } private Environment() throws IOException { name = System.getProperty ("jpos.env"); name = name == null ? "default" : name; readConfig (); } public String getName() { return name; } public static Environment reload() throws IOException { return (INSTANCE = new Environment()); } public static Environment getEnvironment() { return INSTANCE; } public String getProperty (String p, String def) { String s = getProperty (p); return s != null ? s : def; } public String getProperty (String s) { String r = s; if (s != null) { Matcher m = verbPattern.matcher(s); if (m.matches()) { return m.group(1); } m = valuePattern.matcher(s); while (m != null && m.matches()) { String g3 = m.group(3); String g4 = m.group(4); g3 = g3 != null ? g3 : ""; switch (g3) { case SYSTEM_PREFIX: r = System.getProperty(g4); r = r == null ? propRef.get().getProperty(g4) : r; break; case ENVIRONMENT_PREFIX: r = System.getenv(g4); break; default: if (g3.length() == 0) { r = System.getProperty(g4); r = r == null ? propRef.get().getProperty(g4) : r; r = r == null ? System.getenv(g4) : r; } else { return s; // do nothing } } if (r != null) { if (m.group(1) != null) { r = m.group(1) + r; } if (m.group(5) != null) r = r + m.group(5); m = valuePattern.matcher(r); } else m = null; } } return r; } @SuppressWarnings("unchecked") private void readConfig () throws IOException { if (name != null) { if (!readYAML()) readCfg(); } } private boolean readYAML () throws IOException { File f = new File("cfg/" + name + ".yml"); if (f.exists() && f.canRead()) { Properties properties = new Properties(); try (InputStream fis = new FileInputStream(f)) { Yaml yaml = new Yaml(); Iterable<Object> document = yaml.loadAll(fis); document.forEach(d -> { flat(properties, null, (Map<String,Object>) d); }); propRef.set(properties); return true; } catch (IOException e) { throw e; } } return false; } private boolean readCfg () throws IOException { File f = new File("cfg/" + name + ".cfg"); if (f.exists() && f.canRead()) { Properties properties = new Properties(); try (InputStream fis = new FileInputStream(f)) { properties.load(new BufferedInputStream(fis)); propRef.set(properties); return true; } catch (IOException e) { throw e; } } return false; } @SuppressWarnings("unchecked") private void flat (Properties properties, String prefix, Map<String,Object> c) { for (Object o : c.entrySet()) { Map.Entry<String,Object> entry = (Map.Entry<String,Object>) o; String p = prefix == null ? entry.getKey() : (prefix + "." + entry.getKey()); if (entry.getValue() instanceof Map) { flat(properties, p, (Map) entry.getValue()); } else { properties.put (p, "" + entry.getValue()); } } } @Override public void dump(final PrintStream p, String indent) { p.printf ("%s<environment name='%s'>%n", indent, name); Properties properties = propRef.get(); properties.stringPropertyNames().stream(). forEachOrdered(prop -> { p.printf ("%s %s=%s%n", indent, prop, properties.getProperty(prop)); }); p.printf ("%s</environment>%n", indent); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (name != null) { sb.append(String.format("jpos.env=%s%n", name)); Properties properties = propRef.get(); properties.stringPropertyNames().stream(). forEachOrdered(prop -> { sb.append(String.format (" %s=%s%n", prop, properties.getProperty(prop))); }); } return sb.toString(); } }
package org.komamitsu.fluency.flusher; import org.komamitsu.fluency.buffer.Buffer; import org.komamitsu.fluency.sender.Sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; public abstract class Flusher<C extends Flusher.Config> implements Flushable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(Flusher.class); protected final Buffer buffer; protected final Sender sender; protected final C flusherConfig; public Flusher(Buffer buffer, Sender sender, C flusherConfig) { this.buffer = buffer; this.sender = sender; this.flusherConfig = flusherConfig; } public Buffer getBuffer() { return buffer; } protected abstract void flushInternal(boolean force) throws IOException; protected abstract void closeInternal() throws IOException; public void onUpdate() throws IOException { flushInternal(false); } @Override public void flush() throws IOException { flushInternal(true); } @Override public void close() throws IOException { try { closeInternal(); } finally { sender.close(); } } protected void closeBuffer() { LOG.trace("closeBuffer(): closing buffer"); try { buffer.close(sender); } catch (IOException e) { LOG.warn("Interrupted during closing buffer"); } LOG.trace("closeBuffer(): closed buffer"); } public abstract static class Config<T extends Flusher, C extends Config> { private int flushIntervalMillis = 600; public int getFlushIntervalMillis() { return flushIntervalMillis; } public C setFlushIntervalMillis(int flushIntervalMillis) { this.flushIntervalMillis = flushIntervalMillis; return (C)this; } public abstract T createInstance(Buffer buffer, Sender sender); } }
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static final byte BYTE_DEF = 0; private static final boolean BOOLEAN_DEF = Boolean.FALSE; private static final char CHAR_DEF = '\u0000'; private static final short SHORT_DEF = 0; private static final int INT_DEF = 0; private static final long LONG_DEF = 0L; private static final float FLOAT_DEF = 0F; private static final double DOUBLE_DEF = 0D; // default value for modifier private static final int DEFAULT_MODIFIER = 0; // Lock to modify accessible mode of AccessibleObject instances private static final Lock ACCESSOR_LOCK = new ReentrantLock(); private static boolean notAccessible(AccessibleObject accessibleObject) { return ObjectUtils.notTrue(accessibleObject.isAccessible()); } /** * Modifies passed {@link AccessibleObject} as accessible * * @param accessibleObject * @return <code>boolean</code> */ private static boolean makeAccessible(AccessibleObject accessibleObject) { boolean locked = ObjectUtils.tryLock(ACCESSOR_LOCK); if (locked) { try { if (notAccessible(accessibleObject)) { accessibleObject.setAccessible(Boolean.TRUE); } } finally { ObjectUtils.unlock(ACCESSOR_LOCK); } } return locked; } /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked)) { locked = makeAccessible(accessibleObject); } } } /** * Modifies passed {@link AccessibleObject} as not accessible * * @param accessibleObject * @return <code>boolean</code> */ private static boolean makeInaccessible(AccessibleObject accessibleObject) { boolean locked = ObjectUtils.tryLock(ACCESSOR_LOCK); if (locked) { try { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(Boolean.FALSE); } } finally { ObjectUtils.unlock(ACCESSOR_LOCK); } } return locked; } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked) && accessibleObject.isAccessible()) { locked = makeInaccessible(accessibleObject); } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = BYTE_DEF; } else if (clazz.equals(boolean.class)) { value = BOOLEAN_DEF; } else if (clazz.equals(char.class)) { value = CHAR_DEF; } else if (clazz.equals(short.class)) { value = SHORT_DEF; } else if (clazz.equals(int.class)) { value = INT_DEF; } else if (clazz.equals(long.class)) { value = LONG_DEF; } else if (clazz.equals(float.class)) { value = FLOAT_DEF; } else if (clazz.equals(double.class)) { value = DOUBLE_DEF; } else { value = null; } } else { value = null; } return value; } }
package org.apereo.cas.web.flow; import org.apereo.cas.config.CasCoreAuthenticationConfiguration; import org.apereo.cas.config.CasCoreConfiguration; import org.apereo.cas.config.CasCoreServicesConfiguration; import org.apereo.cas.config.CasCoreTicketsConfiguration; import org.apereo.cas.config.CasCoreWebConfiguration; import org.apereo.cas.config.CasPersonDirectoryAttributeRepositoryConfiguration; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.logout.config.CasCoreLogoutConfiguration; import org.apereo.cas.web.config.CasCookieConfiguration; import org.apereo.cas.web.config.CasSupportActionsConfiguration; import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration; import org.apereo.cas.web.support.WebUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.ConfigFileApplicationContextInitializer; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.execution.Action; import org.springframework.webflow.execution.Event; import org.springframework.webflow.test.MockRequestContext; import static org.junit.Assert.*; /** * @author Scott Battaglia * @since 3.0.0 */ @RunWith(SpringJUnit4ClassRunner.class) @EnableConfigurationProperties(CasConfigurationProperties.class) @SpringApplicationConfiguration( classes = {CasSupportActionsConfiguration.class, CasCoreWebflowConfiguration.class, CasCoreWebConfiguration.class, CasCoreConfiguration.class, CasCoreTicketsConfiguration.class, CasCoreLogoutConfiguration.class, CasCoreAuthenticationConfiguration.class, CasPersonDirectoryAttributeRepositoryConfiguration.class, CasCookieConfiguration.class, RefreshAutoConfiguration.class, CasCoreServicesConfiguration.class}, locations = { "classpath:/core-context.xml" }, initializers = ConfigFileApplicationContextInitializer.class) @TestPropertySource(properties = "spring.aop.proxy-target-class=true") public class InitialFlowSetupActionTests { @Autowired @Qualifier("initialFlowSetupAction") private Action action; @Test public void verifyNoServiceFound() throws Exception { final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext(new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse())); final Event event = this.action.execute(context); assertNull(WebUtils.getService(context)); assertEquals("success", event.getId()); } @Test public void verifyServiceFound() throws Exception { final MockRequestContext context = new MockRequestContext(); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "test"); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); final Event event = this.action.execute(context); assertEquals("test", WebUtils.getService(context).getId()); assertNotNull(WebUtils.getRegisteredService(context)); assertEquals("success", event.getId()); } }
package org.mafagafogigante.dungeon.io; import org.mafagafogigante.dungeon.game.DungeonString; import org.mafagafogigante.dungeon.game.Game; import org.mafagafogigante.dungeon.game.GameState; import org.mafagafogigante.dungeon.logging.DungeonLogger; import org.mafagafogigante.dungeon.util.Messenger; import org.mafagafogigante.dungeon.util.StopWatch; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.swing.JOptionPane; /** * Loader class that handles saving and loading the game. */ public final class Loader { private static final File SAVES_FOLDER = new File("saves/"); private static final String SAVE_EXTENSION = ".dungeon"; private static final String DEFAULT_SAVE_NAME = "default" + SAVE_EXTENSION; private static final String SAVE_CONFIRM = "Do you want to save the game?"; private static final String LOAD_CONFIRM = "Do you want to load the game?"; private Loader() { // Ensure that this class cannot be instantiated. throw new AssertionError(); } /** * Evaluates if a File is a save file by checking that it is a file and ends with the save extension. * * @param file a File object * @return true if the specified File is not {@code null} and has the properties of a save file */ private static boolean isSaveFile(File file) { return file != null && file.getName().endsWith(SAVE_EXTENSION) && file.isFile(); } /** * Checks if any file in the saves folder ends with the save extension. */ public static boolean checkForSave() { return !getSavedFiles().isEmpty(); } /** * Prompts the user to confirm an operation using a dialog window. */ private static boolean confirmOperation(String confirmation) { int result = JOptionPane.showConfirmDialog(Game.getGameWindow(), confirmation, null, JOptionPane.YES_NO_OPTION); Game.getGameWindow().requestFocusOnTextField(); return result == JOptionPane.YES_OPTION; } /** * Appends the save file extension to a file name it if it does not ends with it already. * * @param name a file name * @return a String ending with the file extension */ private static String ensureSaveEndsWithExtension(String name) { return name.endsWith(SAVE_EXTENSION) ? name : name + SAVE_EXTENSION; } /** * Generates a new GameState and returns it. */ public static GameState newGame() { GameState gameState = new GameState(); DungeonString string = new DungeonString(); string.append("Created a new game.\n\n"); string.append(gameState.getPreface()); string.append("\n"); Writer.write(string); Game.getGameWindow().requestFocusOnTextField(); return gameState; } /** * Loads the newest save file if there is a save file. Otherwise, returns {@code null}. * * <p>Note that if the user does not confirm the operation in the dialog that pops up, this method return {@code * null}. * * @param requireConfirmation whether or not this method should require confirmation from the user * @return a GameState or null */ public static GameState loadGame(boolean requireConfirmation) { if (checkForSave()) { if (!requireConfirmation || confirmOperation(LOAD_CONFIRM)) { return loadFile(getMostRecentlySavedFile()); } } return null; } /** * Attempts to load the save file indicated by the first argument of the "load" command. * * <p>If the filename was provided but didn't match any files, a message about this is written. * * <p>If the load command was issued without arguments, this method delegates save loading to {@code * Loader.loadGame(false)}. * * <p>If no save file could be found, a message is written. * * <p>This method guarantees that the if null is returned, something is written to the screen. */ public static GameState parseLoadCommand(String[] arguments) { if (arguments.length != 0) { // A save name was provided. String argument = arguments[0]; argument = ensureSaveEndsWithExtension(argument); File save = createFileFromName(argument); if (isSaveFile(save)) { return loadFile(save); } else { Writer.write(save.getName() + " does not exist or is not a file."); return null; } } else { GameState loadResult = loadGame(false); // Don't ask for confirmation. Typing load is not an easy mistake. if (loadResult == null) { Writer.write("No saved game could be found."); } return loadResult; } } /** * Saves the specified GameState to the default save file. */ public static void saveGame(GameState gameState) { saveGame(gameState, null); } /** * Saves the specified GameState, using the default save file or the one defined in the IssuedCommand. * * <p>Only asks for confirmation if there already is a save file with the name. */ public static void saveGame(GameState gameState, String[] arguments) { String saveName = DEFAULT_SAVE_NAME; if (arguments != null && arguments.length != 0) { saveName = arguments[0]; } if (saveFileDoesNotExist(saveName) || confirmOperation(SAVE_CONFIRM)) { saveFile(gameState, saveName); } } /** * Tests whether the save file corresponding to the provided name does not exist. * * @param name the provided filename * @return true if the corresponding file does not exist */ private static boolean saveFileDoesNotExist(String name) { return !createFileFromName(name).exists(); } /** * Returns a File object for the corresponding save file for a specified name. * * @param name the provided filename * @return a File object */ private static File createFileFromName(String name) { return new File(SAVES_FOLDER, ensureSaveEndsWithExtension(name)); } /** * Attempts to load a GameState from a file. * * @param file a File object * @return a GameState or {@code null} if something goes wrong. */ private static GameState loadFile(File file) { StopWatch stopWatch = new StopWatch(); try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) { GameState loadedGameState = (GameState) objectInputStream.readObject(); loadedGameState.setSaved(true); // It is saved, we just loaded it (needed as it now defaults to false). String sizeString = Converter.bytesToHuman(file.length()); DungeonLogger.info(String.format("Loaded %s in %s.", sizeString, stopWatch.toString())); Writer.write(String.format("Successfully loaded the game (read %s from %s).", sizeString, file.getName())); return loadedGameState; } catch (FileNotFoundException bad) { // The filed was moved or deleted. Writer.write("Could not find the specified saved game."); return null; } catch (ClassNotFoundException | IOException exception) { Writer.write("Could not load the saved game."); DungeonLogger.logSevere(exception); return null; } } /** * Serializes the specified {@code GameState} state to a file. * * @param state a GameState * @param name the name of the file */ private static void saveFile(GameState state, String name) { StopWatch stopWatch = new StopWatch(); File file = createFileFromName(name); ensureSavesFolderExists(); try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) { objectOutputStream.writeObject(state); state.setSaved(true); String sizeString = Converter.bytesToHuman(file.length()); DungeonLogger.info(String.format("Saved %s in %s.", sizeString, stopWatch.toString())); Writer.write(String.format("Successfully saved the game (wrote %s to %s).", sizeString, file.getName())); } catch (IOException exception) { Writer.write("Could not save the game."); DungeonLogger.logSevere(exception); } } private static void ensureSavesFolderExists() { if (!SAVES_FOLDER.exists()) { if (!SAVES_FOLDER.mkdir()) { Messenger.printFailedToCreateDirectoryMessage(SAVES_FOLDER.getName()); } } } /** * Returns a list of abstract pathnames denoting the files in the saves folder that end with a valid extension sorted * in natural order. */ @NotNull public static List<File> getSavedFiles() { File[] fileArray = SAVES_FOLDER.listFiles(DungeonFilenameFilters.getExtensionFilter()); if (fileArray == null) { fileArray = new File[0]; } List<File> fileList = new ArrayList<>(Arrays.asList(fileArray)); for (Iterator<File> fileIterator = fileList.iterator(); fileIterator.hasNext(); ) { File file = fileIterator.next(); if (!file.isFile()) { fileIterator.remove(); } } Collections.sort(fileList, new FileLastModifiedComparator()); return fileList; } /** * Returns the most recently saved file. As a precondition, there must be at least one save file. */ private static File getMostRecentlySavedFile() { List<File> fileList = getSavedFiles(); if (fileList.isEmpty()) { throw new IllegalStateException("called getMostRecentlySavedFile() but there are no save files."); } return fileList.get(0); } }
package org.minimalj.model.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Number of decimal places for BigDecimal */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Decimal { int value(); }
package com.cirruslink.sparkplug.message.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; /** * A class representing a Sparkplug B payload */ public class SparkplugBPayload { private Date timestamp; private List<Metric> metrics; private long seq = -1; private String uuid; private byte[] body; public SparkplugBPayload(Date timestamp, List<Metric> metrics, long seq, String uuid, byte[] body) { this.timestamp = timestamp; this.metrics = metrics; this.seq = seq; this.uuid = uuid; this.body = body; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public void addMetric(Metric metric) { metrics.add(metric); } public void addMetric(int index, Metric metric) { metrics.add(index, metric); } public void addMetrics(List<Metric> metrics) { this.metrics.addAll(metrics); } public Metric removeMetric(int index) { return metrics.remove(index); } public boolean removeMetric(Metric metric) { return metrics.remove(metric); } public List<Metric> getMetrics() { return metrics; } public Integer getMetricCount() { return metrics.size(); } public void setMetrics(List<Metric> metrics) { this.metrics = metrics; } public long getSeq() { return seq; } public void setSeq(long seq) { this.seq = seq; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } @Override public String toString() { return "SparkplugBPayload [timestamp=" + timestamp + ", metrics=" + metrics + ", seq=" + seq + ", uuid=" + uuid + ", body=" + Arrays.toString(body) + "]"; } /** * A builder for creating a {@link SparkplugBPayload} instance. */ public static class SparkplugBPayloadBuilder { private Date timestamp; private List<Metric> metrics; private long seq = -1; private String uuid; private byte[] body; public SparkplugBPayloadBuilder(long sequenceNumber) { this.seq = sequenceNumber; metrics = new ArrayList<Metric>(); } public SparkplugBPayloadBuilder() { metrics = new ArrayList<Metric>(); } public SparkplugBPayloadBuilder addMetric(Metric metric) { this.metrics.add(metric); return this; } public SparkplugBPayloadBuilder addMetrics(Collection<Metric> metrics) { this.metrics.addAll(metrics); return this; } public SparkplugBPayloadBuilder setTimestamp(Date timestamp) { this.timestamp = timestamp; return this; } public SparkplugBPayloadBuilder setSeq(long seq) { this.seq = seq; return this; } public SparkplugBPayloadBuilder setUuid(String uuid) { this.uuid = uuid; return this; } public SparkplugBPayloadBuilder setBody(byte[] body) { this.body = body; return this; } public SparkplugBPayload createPayload() { return new SparkplugBPayload(timestamp, metrics, seq, uuid, body); } } }
package org.mitre.synthea.export; import freemarker.template.Configuration; import freemarker.template.SimpleNumber; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateMethodModelEx; import java.io.StringWriter; import java.util.List; import java.util.UUID; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.concepts.HealthRecord.Encounter; import org.mitre.synthea.world.concepts.RaceAndEthnicity; /** * Export C-CDA R2.1 files using Apache FreeMarker templates. */ public class CCDAExporter { private static final Configuration TEMPLATES = templateConfiguration(); /** * This is a dummy object for FreeMarker, because the library cannot access static class methods * such as UUID.randomUUID() */ private static final Object UUID_GEN = new Object() { public String toString() { return UUID.randomUUID().toString(); } }; /** * Generates a random DICOM UID for a study, instance, or series * in a CCDA template. */ private static class RandomDicomUidMethod implements TemplateMethodModelEx { public Object exec(List args) { Number seriesNo = ((SimpleNumber) args.get(0)).getAsNumber(); Number instanceNo = ((SimpleNumber) args.get(1)).getAsNumber(); return Utilities.randomDicomUid(seriesNo.intValue(), instanceNo.intValue()); } }; private static Configuration templateConfiguration() { Configuration configuration = new Configuration(Configuration.VERSION_2_3_26); configuration.setDefaultEncoding("UTF-8"); configuration.setLogTemplateExceptions(false); try { configuration.setSetting("object_wrapper", "DefaultObjectWrapper(2.3.26, forceLegacyNonListCollections=false, " + "iterableSupport=true, exposeFields=true)"); } catch (TemplateException e) { e.printStackTrace(); } configuration.setAPIBuiltinEnabled(true); configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "templates/ccda"); return configuration; } /** * Export a CCDA R2.1 document for a Person at a given time. * * @param person * Person to export. * @param time * Time the record should be generated. Any content in the record AFTER this time will * not be included. * @return String of CCDA R2.1 XML. */ public static String export(Person person, long time) { // create a super encounter... this makes it easier to access // all the Allergies (for example) in the export templates, // instead of having to iterate through all the encounters. Encounter superEncounter = person.record.new Encounter(time, "super"); for (Encounter encounter : person.record.encounters) { if (encounter.start <= time) { superEncounter.observations.addAll(encounter.observations); superEncounter.reports.addAll(encounter.reports); superEncounter.conditions.addAll(encounter.conditions); superEncounter.allergies.addAll(encounter.allergies); superEncounter.procedures.addAll(encounter.procedures); superEncounter.immunizations.addAll(encounter.immunizations); superEncounter.medications.addAll(encounter.medications); superEncounter.careplans.addAll(encounter.careplans); superEncounter.imagingStudies.addAll(encounter.imagingStudies); } else { break; } } // The export templates fill in the record by accessing the attributes // of the Person, so we add a few attributes just for the purposes of export. person.attributes.put("UUID", UUID_GEN); person.attributes.put("randomDicomUid", new RandomDicomUidMethod()); person.attributes.put("ehr_encounters", person.record.encounters); person.attributes.put("ehr_observations", superEncounter.observations); person.attributes.put("ehr_reports", superEncounter.reports); person.attributes.put("ehr_conditions", superEncounter.conditions); person.attributes.put("ehr_allergies", superEncounter.allergies); person.attributes.put("ehr_procedures", superEncounter.procedures); person.attributes.put("ehr_immunizations", superEncounter.immunizations); person.attributes.put("ehr_medications", superEncounter.medications); person.attributes.put("ehr_careplans", superEncounter.careplans); person.attributes.put("ehr_imaging_studies", superEncounter.imagingStudies); person.attributes.put("time", time); person.attributes.put("race_lookup", RaceAndEthnicity.LOOK_UP_CDC_RACE); person.attributes.put("ethnicity_lookup", RaceAndEthnicity.LOOK_UP_CDC_ETHNICITY_CODE); person.attributes.put("ethnicity_display_lookup", RaceAndEthnicity.LOOK_UP_CDC_ETHNICITY_DISPLAY); StringWriter writer = new StringWriter(); try { Template template = TEMPLATES.getTemplate("ccda.ftl"); template.process(person.attributes, writer); } catch (Exception e) { e.printStackTrace(); } return writer.toString(); } }
package org.opencloudb.stat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.log4j.Logger; import org.opencloudb.server.parser.ServerParse; import org.opencloudb.util.StringUtil; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLDeleteStatement; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.ast.statement.SQLInsertStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlReplaceStatement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter; import com.alibaba.druid.sql.parser.SQLParserUtils; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.sql.visitor.SQLASTVisitorAdapter; import com.alibaba.druid.util.JdbcConstants; /** * SQL * * @author zhuam * */ public class TableStatAnalyzer implements QueryResultListener { private static final Logger LOGGER = Logger.getLogger(TableStatAnalyzer.class); private LinkedHashMap<String, TableStat> tableStatMap = new LinkedHashMap<String, TableStat>(); private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); //SQL private SQLParser sqlParser = new SQLParser(); private final static TableStatAnalyzer instance = new TableStatAnalyzer(); private TableStatAnalyzer() {} public static TableStatAnalyzer getInstance() { return instance; } @Override public void onQuery(QueryResult query) { int sqlType = query.getSqlType(); String sql = query.getSql(); switch(sqlType) { case ServerParse.SELECT: case ServerParse.UPDATE: case ServerParse.INSERT: case ServerParse.DELETE: case ServerParse.REPLACE: String masterTable = null; List<String> relaTables = new ArrayList<String>(); List<String> tables = sqlParser.parseTableNames(sql); for(int i = 0; i < tables.size(); i++) { String table = tables.get(i); if ( i == 0 ) { masterTable = table; } else { relaTables.add( table ); } } if ( masterTable != null ) { TableStat tableStat = getTableStat( masterTable ); tableStat.update(sqlType, sql, query.getStartTime(), query.getEndTime(), relaTables); } break; } } private TableStat getTableStat(String tableName) { lock.writeLock().lock(); try { TableStat userStat = tableStatMap.get(tableName); if (userStat == null) { userStat = new TableStat(tableName); tableStatMap.put(tableName, userStat); } return userStat; } finally { lock.writeLock().unlock(); } } public Map<String, TableStat> getTableStatMap() { Map<String, TableStat> map = new LinkedHashMap<String, TableStat>(tableStatMap.size()); lock.readLock().lock(); try { map.putAll(tableStatMap); } finally { lock.readLock().unlock(); } return map; } /** * table */ public List<Map.Entry<String, TableStat>> getTableStats() { List<Map.Entry<String, TableStat>> list = null; lock.readLock().lock(); try { list = this.sortTableStats(tableStatMap , false ); } finally { lock.readLock().unlock(); } //ClearTable();// table return list; } public void ClearTable() { tableStatMap.clear(); } private List<Map.Entry<String, TableStat>> sortTableStats(HashMap<String, TableStat> map, final boolean bAsc) { List<Map.Entry<String, TableStat>> list = new ArrayList<Map.Entry<String, TableStat>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, TableStat>>() { public int compare(Map.Entry<String, TableStat> o1, Map.Entry<String, TableStat> o2) { if (!bAsc) { return o2.getValue().getCount() - o1.getValue().getCount(); } else { return o1.getValue().getCount() - o2.getValue().getCount(); } } }); return list; } /** * table name */ class SQLParser { private SQLStatement parseStmt(String sql) { SQLStatementParser statParser = SQLParserUtils.createSQLStatementParser(sql, "mysql"); SQLStatement stmt = statParser.parseStatement(); return stmt; } /** * `` * @param tableName * @return */ private String fixName(String tableName) { if ( tableName != null ) { tableName = tableName.replace("`", ""); int dotIdx = tableName.indexOf("."); if ( dotIdx > 0 ) { tableName = tableName.substring(1 + dotIdx).trim(); } } return tableName; } /** * SQL table name */ public List<String> parseTableNames(String sql) { final List<String> tables = new ArrayList<String>(); try{ SQLStatement stmt = parseStmt(sql); if (stmt instanceof MySqlReplaceStatement ) { String table = ((MySqlReplaceStatement)stmt).getTableName().getSimpleName(); tables.add( fixName( table ) ); } else if (stmt instanceof SQLInsertStatement ) { String table = ((SQLInsertStatement)stmt).getTableName().getSimpleName(); tables.add( fixName( table ) ); } else if (stmt instanceof SQLUpdateStatement ) { String table = ((SQLUpdateStatement)stmt).getTableName().getSimpleName(); tables.add( fixName( table ) ); } else if (stmt instanceof SQLDeleteStatement ) { String table = ((SQLDeleteStatement)stmt).getTableName().getSimpleName(); tables.add( fixName( table ) ); } else if (stmt instanceof SQLSelectStatement ) { //TODO: modify by owenludong String dbType = ((SQLSelectStatement) stmt).getDbType(); if( !StringUtil.isEmpty(dbType) && JdbcConstants.MYSQL.equals(dbType) ){ stmt.accept(new MySqlASTVisitorAdapter() { public boolean visit(SQLExprTableSource x){ tables.add( fixName( x.toString() ) ); return super.visit(x); } }); } else { stmt.accept(new SQLASTVisitorAdapter() { public boolean visit(SQLExprTableSource x){ tables.add( fixName( x.toString() ) ); return super.visit(x); } }); } } } catch (Exception e) { LOGGER.error("TableStatAnalyzer err:"+ e.toString()); } return tables; } } /* public static void main(String[] args) { List<String> sqls = new ArrayList<String>(); sqls.add( "SELECT id, name, age FROM v1select1 a LEFT OUTER JOIN v1select2 b ON a.id = b.id WHERE a.name = 12 "); sqls.add( "insert into v1user_insert(id, name) values(1,3)"); sqls.add( "delete from v1user_delete where id= 2"); sqls.add( "update v1user_update set id=2 where id=3"); sqls.add( "select ename,deptno,sal from v1user_subquery1 where deptno=(select deptno from v1user_subquery2 where loc='NEW YORK')"); sqls.add( "replace into v1user_insert(id, name) values(1,3)"); sqls.add( "select * from v1xx where id=3 group by zz"); sqls.add( "select * from v1yy where xx=3 limit 0,3"); sqls.add( "SELECT * FROM (SELECT * FROM posts ORDER BY dateline DESC) GROUP BY tid ORDER BY dateline DESC LIMIT 10"); for(String sql: sqls) { List<String> tables = TableStatAnalyzer.getInstance().sqlParser.parseTableNames(sql); for(String t: tables) { System.out.println( t ); } } } */ }
package net.bolbat.kit.lucene; import static net.bolbat.utils.lang.StringUtils.isEmpty; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.Version; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; /** * {@link LuceneStore} in-memory implementation. * * @author Alexandr Bolbat * * @param <S> * storable bean type */ public class LuceneStoreInMemoryImpl<S extends Storable> implements LuceneStore<S> { /** * Lucene document field name for serialized bean data. */ private static final String DOCUMENT_DATA_FIELD_NAME = "BEAN_DATA"; /** * {@link Version} instance. */ private final Version version; /** * In-memory {@link Directory} instance. */ private final Directory directory; /** * {@link Analyzer} instance. */ private final Analyzer analyzer; /** * {@link IndexWriterConfig} instance. */ private final IndexWriterConfig indexWriterConfig; /** * {@link IndexWriter} instance. */ private final IndexWriter writer; /** * {@link IndexReader} instance. */ private volatile IndexReader reader; /** * {@link IndexSearcher} instance; */ private volatile IndexSearcher searcher; /** * Bean type. */ private final Class<S> beanType; /** * {@link ObjectMapper} instance. */ private final ObjectMapper mapper; /** * Synchronization lock for {@link IndexReader} or {@link IndexSearcher} initialization after {@link IndexWriter} process. */ private final Object lock = new Object(); /** * Protected constructor. * * @param aBeanType * bean type */ protected LuceneStoreInMemoryImpl(final Class<S> aBeanType) { if (aBeanType == null) throw new IllegalArgumentException("aBeanType argument is null"); try { // TODO everything should be configurable this.version = Version.LUCENE_47; this.directory = new RAMDirectory(); this.analyzer = new StandardAnalyzer(version); this.indexWriterConfig = new IndexWriterConfig(version, analyzer); this.writer = new IndexWriter(directory, indexWriterConfig); writer.commit(); this.beanType = aBeanType; this.mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } @Override public Collection<S> getAll() { try { final Bits liveDocs = MultiFields.getLiveDocs(getReader()); final List<S> result = new ArrayList<S>(); for (int i = 0; i < getReader().maxDoc(); i++) { if (liveDocs != null && !liveDocs.get(i)) continue; final Document doc = getReader().document(i); result.add(mapper.readValue(doc.get(DOCUMENT_DATA_FIELD_NAME), beanType)); } return result; } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } @Override public S get(final String fieldName, final String fieldValue) { if (isEmpty(fieldName)) throw new IllegalArgumentException("fieldName argument is empty"); if (isEmpty(fieldValue)) throw new IllegalArgumentException("fieldValue argument is empty"); try { final BooleanQuery query = new BooleanQuery(); query.add(new TermQuery(new Term(fieldName, fieldValue)), BooleanClause.Occur.MUST); final TopDocs topDocs = getSearcher().search(query, 1); if (topDocs.scoreDocs.length == 0) return null; final Document doc = getSearcher().doc(topDocs.scoreDocs[0].doc); return mapper.readValue(doc.get(DOCUMENT_DATA_FIELD_NAME), beanType); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } @Override public void add(final S toAdd) { if (toAdd == null) throw new IllegalArgumentException("toAdd argument is null"); if (isEmpty(toAdd.idFieldName())) throw new IllegalArgumentException("toAdd.idFieldName argument is empty"); if (isEmpty(toAdd.idFieldValue())) throw new IllegalArgumentException("toAdd.idFieldValue argument is empty"); try { final Document doc = toAdd.toDocument(); doc.add(new TextField(DOCUMENT_DATA_FIELD_NAME, mapper.writeValueAsString(toAdd), Field.Store.YES)); writer.addDocument(doc); writer.commit(); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public void update(final S toUpdate) { if (toUpdate == null) throw new IllegalArgumentException("toUpdate argument is null"); if (isEmpty(toUpdate.idFieldName())) throw new IllegalArgumentException("toRemove.idFieldName argument is empty"); if (isEmpty(toUpdate.idFieldValue())) throw new IllegalArgumentException("toUpdate.idFieldValue argument is empty"); try { final Document doc = toUpdate.toDocument(); doc.add(new TextField(DOCUMENT_DATA_FIELD_NAME, mapper.writeValueAsString(toUpdate), Field.Store.YES)); writer.updateDocument(new Term(toUpdate.idFieldName(), toUpdate.idFieldValue()), doc); writer.commit(); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public void remove(final S toRemove) { if (toRemove == null) throw new IllegalArgumentException("toRemove argument is null"); if (isEmpty(toRemove.idFieldName())) throw new IllegalArgumentException("toRemove.idFieldName argument is empty"); if (isEmpty(toRemove.idFieldValue())) throw new IllegalArgumentException("toRemove.idFieldValue argument is empty"); try { writer.deleteDocuments(new Term(toRemove.idFieldName(), toRemove.idFieldValue())); writer.commit(); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public void add(final Collection<S> toAdd) { if (toAdd == null) throw new IllegalArgumentException("toAdd argument is null"); if (toAdd.isEmpty()) return; try { final List<Document> docs = new ArrayList<Document>(); for (final S bean : toAdd) { if (bean == null || isEmpty(bean.idFieldName()) || isEmpty(bean.idFieldValue())) continue; final Document doc = bean.toDocument(); doc.add(new TextField(DOCUMENT_DATA_FIELD_NAME, mapper.writeValueAsString(bean), Field.Store.YES)); docs.add(doc); } writer.addDocuments(docs); writer.commit(); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public void update(final Collection<S> toUpdate) { if (toUpdate == null) throw new IllegalArgumentException("toUpdate argument is null"); if (toUpdate.isEmpty()) return; try { for (final S bean : toUpdate) { if (bean == null || isEmpty(bean.idFieldName()) || isEmpty(bean.idFieldValue())) continue; final Document doc = bean.toDocument(); doc.add(new TextField(DOCUMENT_DATA_FIELD_NAME, mapper.writeValueAsString(bean), Field.Store.YES)); writer.updateDocument(new Term(bean.idFieldName(), bean.idFieldValue()), doc); writer.commit(); } } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public void remove(final Collection<S> toRemove) { if (toRemove == null) throw new IllegalArgumentException("toRemove argument is null"); if (toRemove.isEmpty()) return; try { for (final S bean : toRemove) { if (bean == null || isEmpty(bean.idFieldName()) || isEmpty(bean.idFieldValue())) continue; writer.deleteDocuments(new Term(bean.idFieldName(), bean.idFieldValue())); writer.commit(); } } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { cleanAfterCommit(); } } @Override public int count() { return getReader().numDocs(); } @Override public int count(final Query query) { if (query == null) throw new IllegalArgumentException("query argument is null"); try { return getSearcher().search(query, Integer.MAX_VALUE).scoreDocs.length; } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } @Override public Collection<S> get(final Query query) { if (query == null) throw new IllegalArgumentException("query argument is null"); return get(query, Integer.MAX_VALUE); } @Override public Collection<S> get(final Query query, final int limit) { if (query == null) throw new IllegalArgumentException("query argument is null"); if (limit < 1) return Collections.emptyList(); try { final TopDocs topDocs = getSearcher().search(query, limit); final List<S> result = new ArrayList<S>(); for (final ScoreDoc scoreDoc : topDocs.scoreDocs) { final Document doc = getSearcher().doc(scoreDoc.doc); result.add(mapper.readValue(doc.get(DOCUMENT_DATA_FIELD_NAME), beanType)); } return result; } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } @Override public synchronized void cleanUp() { try { writer.deleteAll(); writer.commit(); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } finally { LuceneUtils.close(reader); LuceneUtils.close(analyzer); LuceneUtils.close(writer); LuceneUtils.close(directory); } } /** * Get {@link IndexReader} instance (with lazy initialization). * * @return {@link IndexReader} */ private IndexReader getReader() { if (reader == null) synchronized (lock) { if (reader == null) { try { reader = DirectoryReader.open(directory); } catch (final IOException e) { throw new LuceneStoreRuntimeException(e); } } } return reader; } /** * Get {@link IndexSearcher} instance (with lazy initialization). * * @return {@link IndexSearcher} */ private IndexSearcher getSearcher() { if (searcher == null) synchronized (lock) { if (searcher == null) searcher = new IndexSearcher(getReader()); } return searcher; } /** * This method used for clean up {@link IndexReader} and {@link IndexSearcher} after any commit to the {@link Directory}.<br> * This action required for {@link IndexReader} and {@link IndexSearcher} lazy re-initialization to use new data after {@link IndexWriter} commit. */ private void cleanAfterCommit() { synchronized (lock) { LuceneUtils.close(reader); reader = null; searcher = null; } } }
package net.devrieze.chatterbox.server; import java.util.Iterator; import javax.jdo.JDOObjectNotFoundException; import javax.jdo.PersistenceManager; import com.google.appengine.api.channel.ChannelFailureException; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelService; import com.google.appengine.api.channel.ChannelServiceFactory; public class ChannelManager { private ChannelService channelService; public ChannelManager() { this.channelService = ChannelServiceFactory.getChannelService(); } /** * Create a new channel for the client and connect the client to it. * @param greetingServiceImpl TODO * @return The text needed to retrieve the token by the client. */ String createChannel() { String token; String clientid; PersistenceManager pm = ChatterboxServlet.getPMF().getPersistenceManager(); try { TokenList tokens = getTokenList(pm); clientid=tokens.getClientId();; token = channelService.createChannel(clientid); tokens.add(clientid); // System.out.println("Channel token: \""+token+"\" key:\""+clientid+"\""); } finally { pm.close(); } return "<channel>" + token + "</channel>"; } Message sendMessageToChannels(String messageBody) { TokenList tokens; PersistenceManager pm = ChatterboxServlet.getPMF().getPersistenceManager(); try { Box box = getDefaultBox(pm); Message message = box.addMessage(messageBody); tokens = getTokenList(pm); if (tokens !=null) { Iterator<String> it= tokens.iterator(); while (it.hasNext()) { String clientid = it.next(); try { // System.out.println("Sending message to: \""+clientid+"\""); channelService.sendMessage(new ChannelMessage(clientid, "<messages>"+message.toXML()+"</messages>")); } catch (ChannelFailureException e) { // System.out.println("Invalidating channel: "+clientid); it.remove(); } } } return message; } finally { pm.close(); } } private Box getDefaultBox(PersistenceManager pm) { try { return pm.getObjectById(Box.class, "defaultBox"); } catch (JDOObjectNotFoundException e) { return pm.makePersistent(new Box("defaultBox")); } } private TokenList getTokenList(PersistenceManager pm) { try { return pm.getObjectById(TokenList.class, TokenList.DEFAULTKEY); } catch (JDOObjectNotFoundException e) { TokenList tokens = new TokenList(); return pm.makePersistent(tokens); } } }
package org.sagebionetworks.bridge.sdk; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Properties; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.sagebionetworks.bridge.sdk.models.subpopulations.SubpopulationGuid; import org.sagebionetworks.bridge.sdk.models.users.SignInCredentials; import com.google.common.base.Joiner; import com.google.common.collect.Lists; public final class Config { private static final String CONFIG_FILE = "/bridge-sdk.properties"; private static final String USER_CONFIG_FILE = System.getProperty("user.home") + "/bridge-sdk.properties"; public static enum Props { ACCOUNT_EMAIL, ACCOUNT_PASSWORD, ADMIN_EMAIL, ADMIN_PASSWORD, DEV_NAME, ENV, LOG_LEVEL, SDK_VERSION, STUDY_IDENTIFIER, V3_ACTIVITIES, V3_AUTH_REQUESTRESETPASSWORD, V3_AUTH_RESENDEMAILVERIFICATION, V3_AUTH_RESETPASSWORD, V3_AUTH_SIGNIN, V3_AUTH_SIGNOUT, V3_AUTH_SIGNUP, V3_AUTH_VERIFYEMAIL, V3_BACKFILL_NAME, V3_BACKFILL_NAME_START, V3_CACHE, V3_CACHE_CACHEKEY, V3_PARTICIPANT, V3_PARTICIPANTS, V3_SCHEDULEPLANS, V3_SCHEDULEPLANS_GUID, V3_STUDIES, V3_STUDIES_IDENTIFIER, V3_STUDIES_SELF, V3_SUBPOPULATION, V3_SUBPOPULATIONS, V3_SUBPOPULATIONS_CONSENTS, V3_SUBPOPULATIONS_CONSENTS_PUBLISHED, V3_SUBPOPULATIONS_CONSENTS_RECENT, V3_SUBPOPULATIONS_CONSENTS_SIGNATURE, V3_SUBPOPULATIONS_CONSENTS_SIGNATURE_EMAIL, V3_SUBPOPULATIONS_CONSENTS_SIGNATURE_WITHDRAW, V3_SUBPOPULATIONS_CONSENTS_TIMESTAMP, V3_SUBPOPULATIONS_CONSENTS_TIMESTAMP_PUBLISH, V3_SURVEYRESPONSES, V3_SURVEYRESPONSES_IDENTIFIER, V3_SURVEYS, V3_SURVEYS_PUBLISHED, V3_SURVEYS_RECENT, V3_SURVEYS_SURVEYGUID_REVISIONS, V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON, V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_PHYSICAL_TRUE, V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_PUBLISH, V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_VERSION, V3_SURVEYS_SURVEYGUID_REVISIONS_PUBLISHED, V3_SURVEYS_SURVEYGUID_REVISIONS_RECENT, V3_UPLOADS, V3_UPLOADSCHEMAS, V3_UPLOADSCHEMAS_SCHEMAID, V3_UPLOADSCHEMAS_SCHEMAID_RECENT, V3_UPLOADSCHEMAS_SCHEMAID_REVISIONS_REV, V3_UPLOADSTATUSES_UPLOADID, V3_UPLOADS_UPLOADID_COMPLETE, V3_USERS, V3_USERS_SIGNOUT, V3_USERS_EMAILPARTICIPANTROSTER, V3_USERS_SELF, V3_USERS_SELF_DATAGROUPS, V3_USERS_SELF_DATASHARING, V3_USERS_SELF_EMAILDATA, V3_USERS_SELF_EXTERNALID, V3_USERS_SELF_UNSUBSCRIBEEMAIL, V4_SCHEDULES; public String getPropertyName() { return this.name().replace("_", ".").toLowerCase(); } } private Properties config; private Environment environment; Config() { config = new Properties(); // Load from default configuration file try (InputStream in = this.getClass().getResourceAsStream(CONFIG_FILE)) { config.load(in); } catch (IOException e) { throw new RuntimeException(e); } // Overwrite from user's local file loadProperties(USER_CONFIG_FILE, config); // Finally, overwrite from environment variables and system properties for (Props key : Props.values()) { String value = System.getenv(key.name()); if (value == null) { value = System.getProperty(key.name()); } if (value != null) { config.setProperty(key.getPropertyName(), value); } } String envName = config.getProperty("env"); if (envName != null) { environment = Environment.valueOf(envName.toUpperCase()); } checkNotNull(environment); } private void loadProperties(final String fileName, final Properties properties) { File file = new File(fileName); if (file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Method to reset any of the default values that are defined in the bridge-sdk.properties configuration file. * * @param property * @param value */ public void set(Props property, String value) { checkNotNull(property, "Must specify a property"); checkNotNull(value, "Must specify a value"); config.setProperty(property.getPropertyName(), value); } /** * Method to set the environment of the SDK. * * @param env */ public void set(Environment env) { this.environment = env; } public SignInCredentials getAccountCredentials() { return new SignInCredentials(getStudyIdentifier(), getAccountEmail(), getAccountPassword()); } public SignInCredentials getAdminCredentials() { return new SignInCredentials(getStudyIdentifier(), getAdminEmail(), getAdminPassword()); } public String getAccountEmail() { return val(Props.ACCOUNT_EMAIL); } public String getAccountPassword() { return val(Props.ACCOUNT_PASSWORD); } public String getAdminEmail() { return val(Props.ADMIN_EMAIL); } public String getAdminPassword() { return val(Props.ADMIN_PASSWORD); } public String getCacheApi() { return val(Props.V3_CACHE); } public String getCacheApi(String key) { checkNotNull(key); return String.format(val(Props.V3_CACHE_CACHEKEY), key); } public String getDevName() { return val(Props.DEV_NAME); } public Environment getEnvironment() { return environment; } public String getLogLevel() { return val(Props.LOG_LEVEL); } public String getResendEmailVerificationApi() { return val(Props.V3_AUTH_RESENDEMAILVERIFICATION); } public String getSignUpApi() { return val(Props.V3_AUTH_SIGNUP); } public String getSignInApi() { return val(Props.V3_AUTH_SIGNIN); } public String getSignOutApi() { return val(Props.V3_AUTH_SIGNOUT); } public String getVerifyEmailApi() { return val(Props.V3_AUTH_VERIFYEMAIL); } public String getRequestResetPasswordApi() { return val(Props.V3_AUTH_REQUESTRESETPASSWORD); } public String getResetPasswordApi() { return val(Props.V3_AUTH_RESETPASSWORD); } public String getSetExternalIdApi() { return val(Props.V3_USERS_SELF_EXTERNALID); } public String getProfileApi() { return val(Props.V3_USERS_SELF); } public String getDataGroupsApi() { return val(Props.V3_USERS_SELF_DATAGROUPS); } public String getSetDataSharingApi() { return val(Props.V3_USERS_SELF_DATASHARING); } public String getConsentsApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS), subpopGuid.getGuid()); } public String getConsentApi(SubpopulationGuid subpopGuid, DateTime timestamp) { checkNotNull(subpopGuid); checkNotNull(timestamp); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_TIMESTAMP), subpopGuid.getGuid(), timestamp.toString(ISODateTimeFormat.dateTime())); } public String getConsentSignatureApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_SIGNATURE), subpopGuid.getGuid()); } public String getEmailConsentSignatureApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_SIGNATURE_EMAIL), subpopGuid.getGuid()); } public String getWithdrawConsentSignatureApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_SIGNATURE_WITHDRAW), subpopGuid.getGuid()); } public String getStudyIdentifier() { return val(Props.STUDY_IDENTIFIER); } public String getPublishedStudyConsentApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_PUBLISHED), subpopGuid.getGuid()); } public String getMostRecentStudyConsentApi(SubpopulationGuid subpopGuid) { checkNotNull(subpopGuid); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_RECENT), subpopGuid.getGuid()); } public String getPublishStudyConsentApi(SubpopulationGuid subpopGuid, DateTime timestamp) { checkNotNull(subpopGuid); checkNotNull(timestamp); return String.format(val(Props.V3_SUBPOPULATIONS_CONSENTS_TIMESTAMP_PUBLISH), subpopGuid.getGuid(), timestamp.toString(ISODateTimeFormat.dateTime())); } public String getUploadsApi() { return val(Props.V3_UPLOADS); } public String getCompleteUploadApi(String uploadId) { return String.format(val(Props.V3_UPLOADS_UPLOADID_COMPLETE), uploadId); } public String getUploadStatusApi(String uploadId) { return String.format(val(Props.V3_UPLOADSTATUSES_UPLOADID), uploadId); } public String getUsersApi() { return val(Props.V3_USERS); } public String getUsersSignOutApi() { return val(Props.V3_USERS_SIGNOUT); } public String getSchedulesApi() { return val(Props.V4_SCHEDULES); } public String getSurveysApi() { return val(Props.V3_SURVEYS); } public String getRecentSurveysApi() { return val(Props.V3_SURVEYS_RECENT); } public String getPublishedSurveysApi() { return val(Props.V3_SURVEYS_PUBLISHED); } public String getSurveyApi(String guid, DateTime createdOn) { checkNotNull(createdOn); return getSurveyApi(guid, createdOn.toString(ISODateTimeFormat.dateTime())); } public String getSurveyApi(String guid, String createdOn) { checkArgument(isNotBlank(guid)); checkNotNull(createdOn); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON), guid, createdOn); } public String getDeleteSurveyPermanentlyApi(String guid, DateTime createdOn) { checkArgument(isNotBlank(guid)); checkNotNull(createdOn); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_PHYSICAL_TRUE), guid, createdOn.toString(ISODateTimeFormat.dateTime())); } public String getMostRecentlyPublishedSurveyRevisionApi(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_PUBLISHED), guid); } public String getMostRecentSurveyRevisionApi(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_RECENT), guid); } public String getSurveyAllRevisionsApi(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS), guid); } public String getVersionSurveyApi(String guid, DateTime createdOn) { checkArgument(isNotBlank(guid)); checkNotNull(createdOn); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_VERSION), guid, createdOn.toString(ISODateTimeFormat.dateTime())); } public String getPublishSurveyApi(String guid, DateTime createdOn) { checkArgument(isNotBlank(guid)); checkNotNull(createdOn); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_CREATEDON_PUBLISH), guid, createdOn.toString(ISODateTimeFormat.dateTime())); } public String getRecentlyPublishedSurveyForUserApi(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SURVEYS_SURVEYGUID_REVISIONS_PUBLISHED), guid); } public String getSurveyResponsesApi() { return val(Props.V3_SURVEYRESPONSES); } public String getSurveyResponseApi(String identifier) { checkArgument(isNotBlank(identifier)); return String.format(val(Props.V3_SURVEYRESPONSES_IDENTIFIER), identifier); } public String getSchedulePlansApi() { return val(Props.V3_SCHEDULEPLANS); } public String getSchedulePlanApi(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SCHEDULEPLANS_GUID), guid); } public String getScheduledActivitiesApi() { return val(Props.V3_ACTIVITIES); } public String getUploadSchemasApi() { return val(Props.V3_UPLOADSCHEMAS); } public String getUploadSchemaAllRevisionsApi(String schemaId) { checkArgument(isNotBlank(schemaId)); return String.format(val(Props.V3_UPLOADSCHEMAS_SCHEMAID), schemaId); } public String getMostRecentUploadSchemaApi(String schemaId) { checkArgument(isNotBlank(schemaId)); return String.format(val(Props.V3_UPLOADSCHEMAS_SCHEMAID_RECENT), schemaId); } public String getUploadSchemaApi(String schemaId, int revision) { checkArgument(isNotBlank(schemaId)); checkArgument(revision != 0); return String.format(val(Props.V3_UPLOADSCHEMAS_SCHEMAID_REVISIONS_REV), schemaId, revision); } public String getCurrentStudyApi() { return val(Props.V3_STUDIES_SELF); } public String getStudiesApi() { return val(Props.V3_STUDIES); } public String getStudyApi(String identifier) { checkArgument(isNotBlank(identifier)); return String.format(val(Props.V3_STUDIES_IDENTIFIER), identifier); } public String getSdkVersion() { return val(Props.SDK_VERSION); } public String getEmailParticipantRosterApi() { return val(Props.V3_USERS_EMAILPARTICIPANTROSTER); } public String getSubpopulations() { return val(Props.V3_SUBPOPULATIONS); } public String getSubpopulation(String guid) { checkArgument(isNotBlank(guid)); return String.format(val(Props.V3_SUBPOPULATION), guid); } public String getParticipantsApi(int offsetBy, int pageSize) { checkArgument(offsetBy >= 0); checkArgument(pageSize >= 5); return String.format(val(Props.V3_PARTICIPANTS), offsetBy, pageSize); } public String getParticipant(String email) { checkArgument(isNotBlank(email)); try { String encodedEmail = URLEncoder.encode(email, "UTF-8"); return String.format(val(Props.V3_PARTICIPANT), encodedEmail); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private String val(Props prop) { String value = config.getProperty(prop.getPropertyName()); checkNotNull(value, "The property '" + prop.getPropertyName() + "' has not been set."); return value; } @Override public String toString() { List<String> list = Lists.newArrayList(); for (int i = 0; i < Props.values().length; i++) { String property = Props.values()[i].getPropertyName(); String value = property.contains("password") ? "******" : config.getProperty(property); list.add(property + "=" + value); } return "Config[" + Joiner.on(", ").join(list) + "]"; } }
package net.furfurylic.chionographis; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.net.URI; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; import java.util.Optional; import java.util.WeakHashMap; import java.util.function.Consumer; import java.util.function.Function; /** * A class for caching objects identified by URIs. * * The cached objects are held by soft references. * Objects of this class are thread-safe. * * @param <T> * the class of the cached objects. */ final class NetResourceCache<T> { private final Object LOCK = new Object(); /** A synchronized canonicalization mapping for URIs. */ private Map<URI, WeakReference<URI>> canonURIs_ = null; /** A possibly identity-based synchronized map. */ private SoftReference<Map<URI, Optional<T>>> cache_ = null; /** Sole constructor. */ public NetResourceCache() { } /** * Fetches an object from the cache. If no objects are bound to the specified URI, * an object for the URI is created and cached. * * @param uri * a URI. * @param listenStored * a listener invoked when an object is about to be cached. * @param listenHit * a listener invoked when an object is fetched from the cache. * @param factory * a factory function which make an object from a URI, which can return {@code null} * in case of errors. * * @return * a possibly-{@code null} resolved object. */ public T get(URI uri, Consumer<URI> listenStored, Consumer<URI> listenHit, Function<URI, ? extends T> factory) { assert uri != null; assert uri.isAbsolute(); Map<URI, Optional<T>> strongOne = null; synchronized (LOCK) { if (cache_ == null) { canonURIs_ = new WeakHashMap<>(); } else { strongOne = cache_.get(); } if (strongOne == null) { strongOne = Collections.synchronizedMap(new IdentityHashMap<>()); cache_ = new SoftReference<>(strongOne); } } // Get the privately-canonicalized form. URI canonicalizedURI = canonicalizeURI(uri); // From here uri shall NOT be in the canonicalized form. if (canonicalizedURI == uri) { uri = URI.create(uri.toString()); } // Lock with privately-canonicalized form // in order to minimize granularity of locks. synchronized (canonicalizedURI) { Optional<T> cached = strongOne.get(canonicalizedURI); if (cached != null) { if (!cached.isPresent()) { // Means that an error occurred in the previous try. return null; } else { // Cache hit. listenHit.accept(uri); } } else { cached = Optional.ofNullable(factory.apply(uri)); if (cached.isPresent()) { listenStored.accept(uri); } strongOne.put(canonicalizedURI, cached); } return cached.get(); } } /** * Canonicalizes a URI so that URIs which have the same logical content are one same object. * * @param uri * a URI to canonicalize, which must not come from this method. * * @return * the canonicalized form of the URI, * which is different object from the parameter {@code uri} * only if it has been the first object for its logical content. */ private URI canonicalizeURI(URI uri) { assert uri != null; synchronized (canonURIs_) { WeakReference<URI> ref = canonURIs_.get(uri); if (ref == null) { ref = new WeakReference<>(uri); canonURIs_.put(uri, ref); return uri; } else { assert ref.get() != null; return ref.get(); } } } }
package org.sidif.triple.impl; import java.util.ArrayList; import java.util.List; import org.sidif.triple.Triple; import org.sidif.triple.TripleQuery; import org.sidif.triple.TripleStore; import org.sidif.triple.TripleStore.TripleContainer; /** * TripleQuery * * @author wf * */ public class TripleQueryImpl implements TripleQuery { public static enum TopicType { subject, predicate, object }; TripleStore tripleStore; public Triple triple; TopicType topicType; protected List<Triple> triples; /** * create a TripleQuery from the given tripleStore * @param tripleStore */ public TripleQueryImpl(TripleStore tripleStore) { this.tripleStore=tripleStore; this.topicType=TopicType.subject; setTriples(tripleStore.getTriples()); } /** * create a new TripleQuery based on an existing one * @param tripleQuery */ public TripleQueryImpl(TripleQueryImpl tripleQuery) { this.tripleStore=tripleQuery.tripleStore; this.topicType=tripleQuery.topicType; this.triples=tripleQuery.triples; this.triple=tripleQuery.triple; } /** * change the query topic * @param topicType * @return the query */ public TripleQueryImpl queryTopic(TopicType topicType) { TripleQueryImpl result = new TripleQueryImpl(this); result.topicType=topicType; return result; } /** * get the TripleContainer * @return the tripleContainer of the current topic type */ public TripleContainer getTripleContainer() { TripleContainer result; switch (topicType) { case subject: result = tripleStore.bySubject; break; case predicate: result = tripleStore.byPredicate; break; case object: result = tripleStore.bySubject; break; default: throw new IllegalArgumentException("unknown topic Type: "+topicType); } return result; } /** * get the Topic for the current topic type subject predicate or object * @return the object */ public Object getTopic() { Object topic=null; if (triple!=null) { switch (topicType) { case subject: topic=triple.getSubject(); break; case predicate: topic=triple.getPredicate(); break; case object: topic=triple.getObject(); break; } } return topic; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#select(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public List<Triple> select(Object subject, Object predicate, Object object) { TripleQueryImpl tripleQuery = this.query(subject, predicate, object); List<Triple> result = tripleQuery.triples; return result; } /** * select the triples for the given "template" triple * * @param select * @return the selected list of triples */ public List<Triple> select(Triple select) { TripleQueryImpl tripleQuery = this.queryTriple(select); List<Triple> result = tripleQuery.triples; return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#same(java.lang.Object, java.lang.Object) */ @Override public boolean same(Object object, Object other) { boolean result = false; if ((object == null) && (other == null)) result = true; if ((object != null) && (other != null)) result = object.equals(other); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#query(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public TripleQueryImpl query(Object subject, Object predicate, Object object) { TripleImpl select = new TripleImpl(subject, predicate, object); TripleQueryImpl result = queryTriple(select); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#selectSingle(java.lang.Object, java.lang.Object, java.lang.Object) */ @Override public Triple selectSingle(Object subject, Object predicate, Object object) { List<Triple> triples = this.select(subject, predicate, object); if (triples.size() > 1) { String msg="selectSingle subject='"+subject +"' predicate='"+predicate +"' object='"+object+"' returned "+triples.size()+" triples but there should be only one!"; // we'll show the first (upto) 10 culprits for (int i=1;i<=Math.min(triples.size(), 10);i++) { Triple triple=triples.get(i-1); msg+="\n\t"+i+":"+triple.toString(); } throw new IllegalStateException(msg); } else if (triples.size()==0) { return null; } return triples.get(0); } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#queryTriple(org.sidif.triple.Triple) */ @Override public TripleQueryImpl queryTriple(Triple select) { TripleQueryImpl result=new TripleQueryImpl(this); result.triples = new ArrayList<Triple>(); // FIXME - this is inefficient for (Triple triple : this.getTriples()) { boolean subjectOk = select.getSubject() == null || same(triple.getSubject(), select.getSubject()); boolean predicateOk = select.getPredicate() == null || same(triple.getPredicate(), select.getPredicate()); boolean objectOk = select.getObject() == null || same(triple.getObject(), select.getObject()); if (subjectOk && predicateOk && objectOk) { result.add(triple); } } result.setTriple(); return result; } /** * add the given Triple to my triples * @param triple */ private void add(Triple triple) { if (!triples.contains(triple)) { triples.add(triple); } } /** * set my triples * @param pTriples - the triples to use */ public void setTriples(List<Triple> pTriples) { triples=pTriples; setTriple(); } /** * set my triple (head triple pointer ...) */ public void setTriple() { if (triples.size()>0) triple=triples.get(0); else triple=null; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#union(org.sidif.triple.TripleQueryImpl) */ @Override public TripleQuery union(TripleQuery other) { TripleQueryImpl result=new TripleQueryImpl(this); List<Triple> triples = new ArrayList<Triple>(); triples.addAll(this.getTriples()); triples.addAll(other.getTriples()); result.setTriples(triples); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#intersect(org.sidif.triple.TripleQueryI) */ @Override public TripleQuery intersect(TripleQuery otherQuery) { TripleQueryImpl result=new TripleQueryImpl(this); result.triples=new ArrayList<Triple>(); // FIXME this is ineffecient quadratic O(this.size x otherQuery.size) ... for (Triple triple:this.getTriples()) { for (Triple otherTriple:otherQuery.getTriples()) { if (same(triple,otherTriple)) { result.add(triple); } } } result.setTriple(); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#complement(org.sidif.triple.TripleQueryI) */ @Override public TripleQuery complement(TripleQuery otherQuery) { TripleQueryImpl result=new TripleQueryImpl(this); result.triples=new ArrayList<Triple>(); // FIXME this is ineffecient quadratic O(this.size x otherQuery.size) ... for (Triple triple:this.getTriples()) { for (Triple otherTriple:otherQuery.getTriples()) { if (!same(triple,otherTriple)) { result.add(triple); } } } result.setTriple(); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#size() */ @Override public int size() { int result=this.triples.size(); return result; } /* (non-Javadoc) * @see org.sidif.triple.TripleQueryI#getTriples() */ @Override public List<Triple> getTriples() { return triples; } }
package de.sebhn.algorithm.excercise2; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Calculates from any double array the smallest product * * @author Phi Long Tran <191624> & Manuel Wessner <191711> */ public class MinProduct { private static int indexStart = 0; private static int indexEnd = 0; public static void main(String[] args) throws Exception { double[] someRandomArray; if (args.length == 0) { someRandomArray = someRandomArray(); } else { someRandomArray = new double[args.length]; for (int i = 0; i < args.length; i++) { someRandomArray[i] = Double.valueOf(args[i]); } } calculateMinProduct(someRandomArray); } /** * Calculates from any double array the smallest product * * @param someRandomArray * @return smallest product */ public static double calculateMinProduct(double[] someRandomArray) throws Exception { System.out.println("Array: " + Arrays.toString(someRandomArray)); if (someRandomArray.length == 0) { throw new Exception("Please fill array"); } double firstEntry = someRandomArray[0]; double current_min_prod = firstEntry; double current_max_prod = firstEntry; double previous_min_prod = firstEntry; double previous_max_prod = firstEntry; double result = firstEntry; for (int i = 1; i < someRandomArray.length; i++) { double myDouble = someRandomArray[i]; // System.out.println("calc min " + previous_min_prod + "*" + myDouble); // System.out.println("calc max " + previous_max_prod + "*" + myDouble); double temporaryMax = previous_max_prod * myDouble; double temporaryMin = previous_min_prod * myDouble; current_max_prod = Math.max(Math.max(temporaryMax, temporaryMin), myDouble); current_min_prod = Math.min(Math.min(temporaryMax, temporaryMin), myDouble); // System.out.println("new min " + current_min_prod + " new max " + current_max_prod); if (current_min_prod > 1) { current_min_prod = 1; indexEnd = i - 1; } result = Math.min(result, current_min_prod); if (current_min_prod <= result) { indexEnd = i; } previous_max_prod = current_max_prod; previous_min_prod = current_min_prod; } indexStart = determineIndexStart(someRandomArray, indexEnd, result); String factors = IntStream.range(indexStart, indexEnd + 1) // start from indexFrom .mapToObj(i -> String.valueOf(Double.valueOf(someRandomArray[i]))) // assign value to String .collect(Collectors.joining("*", " calculated from ", "")); System.out.println("result: " + result + factors); return result; } /** * Goes the arrays back from a given index to find the startIndex by comparing the result * * @throws Exception */ private static int determineIndexStart(double[] someRandomArray, int indexEnd, double result) throws Exception { double newResult = 1; for (int i = indexEnd; i >= 0; i newResult *= someRandomArray[i]; if (newResult == result) { return i; } } throw new Exception("Shouldnt come here"); } public static double[] someRandomArray() { double[] randomArray = new double[10]; randomArray[0] = 1; randomArray[1] = -13; randomArray[2] = 4.5; randomArray[3] = 7; randomArray[4] = 98; randomArray[5] = -33.5; randomArray[6] = 3; randomArray[7] = 64; randomArray[8] = 8; randomArray[9] = -2; return randomArray; } }
package net.localizethat.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import net.localizethat.Main; import net.localizethat.gui.tabpanels.ProductManager; /** * Opens a tab with the product manager in the main window * @author rpalomares */ public class ProductManagerAction extends AbstractAction { private static final String TITLE = "Product Manager"; private static final String DESCRIPTION = "Opens " + TITLE; private static final int MNEMONIC = java.awt.event.KeyEvent.VK_P; private ProductManager productGuiMgr; /** * Action representing the launching of LocaleManager panel as a tab in main window */ public ProductManagerAction() { super(TITLE); putValue(SHORT_DESCRIPTION, DESCRIPTION); putValue(MNEMONIC_KEY, MNEMONIC); putValue(ACCELERATOR_KEY, javax.swing.KeyStroke.getKeyStroke(MNEMONIC, java.awt.event.InputEvent.CTRL_MASK)); } @Override public void actionPerformed(ActionEvent e) { Main.mainWindow.getStatusBar().setInfoText("Creating window, please wait..."); if (productGuiMgr == null) { productGuiMgr = new ProductManager(); } Main.mainWindow.addTab(productGuiMgr, TITLE); } }
package org.testng.internal; import org.testng.IClass; import org.testng.IInstanceInfo; import org.testng.ITestContext; import org.testng.ITestObjectFactory; import org.testng.TestNGException; import org.testng.annotations.IAnnotation; import org.testng.collections.Lists; import org.testng.collections.Maps; import org.testng.internal.annotations.AnnotationHelper; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.xml.XmlClass; import org.testng.xml.XmlTest; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; import java.util.Set; /** * This class creates an ITestClass from a test class. * * @author <a href="mailto:cedric@beust.com">Cedric Beust</a> */ public class TestNGClassFinder extends BaseClassFinder { private ITestContext m_testContext = null; private Map<Class, List<Object>> m_instanceMap = Maps.newHashMap(); public TestNGClassFinder(ClassInfoMap cim, Map<Class, List<Object>> instanceMap, XmlTest xmlTest, IConfiguration configuration, ITestContext testContext) { m_testContext = testContext; if(null == instanceMap) { instanceMap= Maps.newHashMap(); } IAnnotationFinder annotationFinder = configuration.getAnnotationFinder(); ITestObjectFactory objectFactory = configuration.getObjectFactory(); // Find all the new classes and their corresponding instances Set<Class<?>> allClasses= cim.getClasses(); //very first pass is to find ObjectFactory, can't create anything else until then if(objectFactory == null) { objectFactory = new ObjectFactoryImpl(); outer: for (Class cls : allClasses) { try { if (null != cls) { for (Method m : cls.getMethods()) { IAnnotation a = annotationFinder.findAnnotation(m, org.testng.annotations.IObjectFactoryAnnotation.class); if (null != a) { if (!ITestObjectFactory.class.isAssignableFrom(m.getReturnType())) { throw new TestNGException("Return type of " + m + " is not IObjectFactory"); } try { Object instance = cls.newInstance(); if (m.getParameterTypes().length > 0 && m.getParameterTypes()[0].equals(ITestContext.class)) { objectFactory = (ITestObjectFactory) m.invoke(instance, testContext); } else { objectFactory = (ITestObjectFactory) m.invoke(instance); } break outer; } catch (Exception ex) { throw new TestNGException("Error creating object factory: " + cls, ex); } } } } } catch (NoClassDefFoundError e) { Utils.log("[TestNGClassFinder]", 1, "Unable to read methods on class " + cls.getName() + " - unable to resolve class reference " + e.getMessage()); for (XmlClass xmlClass : xmlTest.getXmlClasses()) { if (xmlClass.loadClasses() && xmlClass.getName().equals(cls.getName())) { throw e; } } } } } for(Class cls : allClasses) { if((null == cls)) { ppp("FOUND NULL CLASS IN FOLLOWING ARRAY:"); int i= 0; for(Class c : allClasses) { ppp(" " + i + ": " + c); } continue; } if(isTestNGClass(cls, annotationFinder)) { List allInstances= instanceMap.get(cls); Object thisInstance= (null != allInstances) ? allInstances.get(0) : null; // If annotation class and instances are abstract, skip them if ((null == thisInstance) && Modifier.isAbstract(cls.getModifiers())) { Utils.log("", 5, "[WARN] Found an abstract class with no valid instance attached: " + cls); continue; } IClass ic= findOrCreateIClass(m_testContext, cls, cim.getXmlClass(cls), thisInstance, xmlTest, annotationFinder, objectFactory); if(null != ic) { Object[] theseInstances = ic.getInstances(false); if (theseInstances.length == 0) { theseInstances = ic.getInstances(true); } Object instance= theseInstances[0]; putIClass(cls, ic); ConstructorOrMethod factoryMethod = ClassHelper.findDeclaredFactoryMethod(cls, annotationFinder); if (factoryMethod != null && factoryMethod.getEnabled()) { FactoryMethod fm = new FactoryMethod( /* cls, */ factoryMethod, instance, xmlTest, annotationFinder, m_testContext); ClassInfoMap moreClasses = new ClassInfoMap(); { // ppp("INVOKING FACTORY " + fm + " " + this.hashCode()); Object[] instances= fm.invoke(); // If the factory returned IInstanceInfo, get the class from it, // otherwise, just call getClass() on the returned instances if (instances.length > 0) { if (instances[0] != null) { Class elementClass = instances[0].getClass(); if(IInstanceInfo.class.isAssignableFrom(elementClass)) { for(Object o : instances) { IInstanceInfo ii = (IInstanceInfo) o; addInstance(ii.getInstanceClass(), ii.getInstance()); moreClasses.addClass(ii.getInstanceClass()); } } else { for (int i = 0; i < instances.length; i++) { Object o = instances[i]; if (o == null) { throw new TestNGException("The factory " + fm + " returned a null instance" + "at index " + i); } else { addInstance(o.getClass(), o); if(!classExists(o.getClass())) { moreClasses.addClass(o.getClass()); } } } } } } } if(moreClasses.getSize() > 0) { TestNGClassFinder finder= new TestNGClassFinder(moreClasses, m_instanceMap, xmlTest, configuration, m_testContext); IClass[] moreIClasses= finder.findTestClasses(); for(IClass ic2 : moreIClasses) { putIClass(ic2.getRealClass(), ic2); } } // if moreClasses.size() > 0 } } // null != ic } // if not TestNG class else { Utils.log("TestNGClassFinder", 3, "SKIPPING CLASS " + cls + " no TestNG annotations found"); } } // for // Add all the instances we found to their respective IClasses for(Class c : m_instanceMap.keySet()) { List<Object> instances= m_instanceMap.get(c); for(Object instance : instances) { IClass ic= getIClass(c); if(null != ic) { ic.addInstance(instance); } } } } /** * @returns true if this class contains TestNG annotations (either on itself * or on a superclass). */ public static boolean isTestNGClass(Class c, IAnnotationFinder annotationFinder) { Class[] allAnnotations= AnnotationHelper.getAllAnnotations(); Class cls = c; try { for(Class annotation : allAnnotations) { for (cls = c; cls != null; cls = cls.getSuperclass()) { // Try on the methods for (Method m : cls.getMethods()) { IAnnotation ma= annotationFinder.findAnnotation(m, annotation); if(null != ma) { return true; } } // Try on the class IAnnotation a= annotationFinder.findAnnotation(cls, annotation); if(null != a) { return true; } // Try on the constructors for (Constructor ctor : cls.getConstructors()) { IAnnotation ca= annotationFinder.findAnnotation(ctor, annotation); if(null != ca) { return true; } } } } return false; } catch (NoClassDefFoundError e) { Utils.log("[TestNGClassFinder]", 1, "Unable to read methods on class " + cls.getName() + " - unable to resolve class reference " + e.getMessage()); return false; } } private void addInstance(Class clazz, Object o) { List<Object> list= m_instanceMap.get(clazz); if(null == list) { list= Lists.newArrayList(); m_instanceMap.put(clazz, list); } list.add(o); } public static void ppp(String s) { System.out.println("[TestNGClassFinder] " + s); } }
package de.st_ddt.crazyutil; import java.lang.reflect.InvocationTargetException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import de.st_ddt.crazyplugin.CrazyLightPluginInterface; public class ObjectSaveLoadHelper { private static DateFormat OLDDATETIMEFORMAT = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); protected ObjectSaveLoadHelper() { super(); } // Location public static Location loadLocation(final ConfigurationSection config, World world) { if (config == null) return null; if (world == null) { world = Bukkit.getWorld(config.getString("world", "")); if (world == null) return null; } return new Location(world, config.getDouble("x"), config.getDouble("y"), config.getDouble("z"), (float) config.getDouble("yaw", 0d), (float) config.getDouble("pitch", 0d)); } public static void saveLocation(final ConfigurationSection config, final String path, final Location location) { saveLocation(config, path, location, false, true); } public static void saveLocation(final ConfigurationSection config, final String path, final Location location, final boolean saveRotation) { saveLocation(config, path, location, false, saveRotation); } public static void saveLocation(final ConfigurationSection config, final String path, final Location location, final boolean saveWorld, final boolean saveRotation) { config.set(path + "x", location.getX()); config.set(path + "y", location.getY()); config.set(path + "z", location.getZ()); if (saveRotation) { config.set(path + "yaw", location.getYaw()); config.set(path + "pitch", location.getPitch()); } if (saveWorld) if (location.getWorld() != null) config.set(path + "world", location.getWorld().getName()); } // Date public static Date StringToDate(final String date, final Date defaultDate) { if (date == null) return defaultDate; try { return CrazyLightPluginInterface.DATETIMEFORMAT.parse(date); } catch (final ParseException e) { try { return OLDDATETIMEFORMAT.parse(date); } catch (final ParseException e1) { return defaultDate; } } } public static String DateToString(final Date date) { return CrazyLightPluginInterface.DATETIMEFORMAT.format(date); } // ItemStack public static Map<Integer, ItemStack> loadInventory(final ConfigurationSection config, Inventory inventory) { final Set<String> entries = config.getKeys(false); final Map<Integer, ItemStack> res = new HashMap<Integer, ItemStack>(entries.size()); for (final String key : entries) try { inventory.setItem(Integer.parseInt(key), loadItemStack(config.getConfigurationSection(key))); } catch (final NumberFormatException e) { System.err.println("Failed to read Inventory Index Key. Fix your config! " + config.getCurrentPath() + "." + key); e.printStackTrace(); } return res; } public static Map<Integer, ItemStack> loadInventory(final ConfigurationSection config) { final Set<String> entries = config.getKeys(false); final Map<Integer, ItemStack> res = new HashMap<Integer, ItemStack>(entries.size()); for (final String key : entries) try { res.put(Integer.parseInt(key), loadItemStack(config.getConfigurationSection(key))); } catch (final NumberFormatException e) { System.err.println("Failed to read Inventory Index Key. Fix your config! " + config.getCurrentPath() + "." + key); e.printStackTrace(); } return res; } public static void saveInventory(final ConfigurationSection config, final String path, final Inventory inventory) { for (int i = 0; i < inventory.getSize(); i++) saveItemStack(config, path + i + ".", inventory.getItem(i)); } public static void saveInventory(final ConfigurationSection config, final String path, final Map<Integer, ItemStack> items) { for (final Entry<Integer, ItemStack> entry : items.entrySet()) saveItemStack(config, path + entry.getKey().toString() + ".", entry.getValue()); } public static ArrayList<ItemStack> loadItemStacks(final ConfigurationSection config) { if (config == null) return new ArrayList<ItemStack>(0); final Set<String> entries = config.getKeys(false); final ArrayList<ItemStack> res = new ArrayList<ItemStack>(entries.size()); for (final String key : entries) res.add(loadItemStack(config.getConfigurationSection(key))); return res; } public static void saveItemStacks(final ConfigurationSection config, final String path, final Collection<ItemStack> items) { int i = 0; for (final ItemStack item : items) saveItemStack(config, path + i++ + ".", item); } public static ItemStack loadItemStack(final ConfigurationSection config) { return ItemStack.deserialize(config.getValues(true)); } public static void saveItemStack(final ConfigurationSection config, final String path, final ItemStack item) { if (item == null) return; config.set(path, item.serialize()); } /* Load Objects */ /* * Load a list of Objects */ public static <T> List<T> loadList(final ConfigurationSection config, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects, final String alternativePackage) { final ArrayList<T> list = new ArrayList<T>(); if (config == null) return list; for (final String key : config.getKeys(false)) list.add(load(config.getConfigurationSection(key), parentClazz, paraClazzes, paraObjects, alternativePackage)); return list; } public static <T> List<T> loadList(final ConfigurationSection config, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects) { return loadList(config, parentClazz, paraClazzes, paraObjects, null); } public static <T> T load(final ConfigurationSection config, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects) { return load(config, parentClazz, paraClazzes, paraObjects, null); } public static <T> T load(final ConfigurationSection config, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects, final String alternativePackage) { final String clazzName = config.getString("type", "-1"); if (clazzName.equals("-1")) { System.err.println("No class defined!"); return null; } return load(clazzName, parentClazz, paraClazzes, paraObjects, alternativePackage); } public static <T> T load(final String clazzname, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects) { return load(clazzname, parentClazz, paraClazzes, paraObjects, null); } public static <T> T load(final String clazzname, final Class<T> parentClazz, final Class<?>[] paraClazzes, final Object[] paraObjects, final String alternativePackage) { Class<? extends T> clazz = null; try { clazz = Class.forName(clazzname).asSubclass(parentClazz); } catch (final ClassNotFoundException e) { if (alternativePackage == null) { e.printStackTrace(); return null; } try { clazz = Class.forName(alternativePackage + "." + clazzname).asSubclass(parentClazz); } catch (final ClassNotFoundException e2) { e.printStackTrace(); return null; } } return load(clazz, paraClazzes, paraObjects); } public static <T> T load(final Class<? extends T> clazz, final Class<?>[] paraClazzes, final Object[] paraObjects) { try { return clazz.getConstructor(paraClazzes).newInstance(paraObjects); } catch (final InvocationTargetException e) { ChatHelper.shortPrintStackTrace(e, e.getCause(), "ObjectSaveLoadHelper (" + clazz.getName() + ")"); } catch (final Exception e) { e.printStackTrace(); } return null; } }
package nu.validator.checker; import com.cybozu.labs.langdetect.LangDetectException; import com.ibm.icu.util.ULocale; import org.apache.stanbol.enhancer.engines.langdetect.LanguageIdentifier; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; public final class LanguageDetectingChecker extends Checker { private StringBuilder elementContent; private StringBuilder documentContent; private String langAttrValue; private String xmlLangAttrValue; private boolean hasLang; private boolean hasXmlLang; private LanguageIdentifier languageIdentifier; private boolean inBody; private boolean collectingCharacters; private int characterCount; private LocatorImpl htmlLocator; private int MAX_CHARS = 35840; private int MIN_CHARS = 512; @Override public void reset() { inBody = false; collectingCharacters = false; characterCount = 0; elementContent = new StringBuilder(); documentContent = new StringBuilder(); hasLang = false; hasXmlLang = false; langAttrValue = ""; xmlLangAttrValue = ""; try { languageIdentifier = new LanguageIdentifier(); } catch (LangDetectException e) { e.printStackTrace(); } } /** * @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (characterCount > MAX_CHARS) { return; } if (collectingCharacters) { characterCount += length; elementContent.append(ch, start, length); } } /** * @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (characterCount > MAX_CHARS) { return; } documentContent.append(elementContent); elementContent.setLength(0); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if ("html".equals(localName)) { for (int i = 0; i < atts.getLength(); i++) { if ("lang".equals(atts.getLocalName(i))) { hasLang = true; langAttrValue = atts.getValue(i); } else if ("xml:lang".equals(atts.getLocalName(i))) { hasXmlLang = true; xmlLangAttrValue = atts.getValue(i); } } Locator documentLocator = getDocumentLocator(); htmlLocator = new LocatorImpl(documentLocator); htmlLocator.setLineNumber(documentLocator.getLineNumber()); htmlLocator.setColumnNumber(documentLocator.getColumnNumber()); } else if (characterCount > MAX_CHARS) { return; } else if ("body".equals(localName)) { inBody = true; } collectingCharacters = false; if (inBody && !"script".equals(localName) && !"style".equals(localName)) { collectingCharacters = true; } } /** * @throws SAXException * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { if (characterCount < MIN_CHARS) { return; } try { String textContent = documentContent.toString(); String language = languageIdentifier.getLanguage(textContent); String detectedLanguageName = ""; String preferredLanguageCode = ""; ULocale locale = new ULocale(language); String detectedLanguageCode = locale.getLanguage(); if ("zh-cn".equals(language)) { detectedLanguageName = "Simplified Chinese"; preferredLanguageCode = "zh-Hans"; } else if ("zh-tw".equals(language)) { detectedLanguageName = "Traditional Chinese"; preferredLanguageCode = "zh-Hant"; } else { detectedLanguageName = locale.getDisplayName(); preferredLanguageCode = detectedLanguageCode; } if ("".equals(langAttrValue) && "".equals(xmlLangAttrValue)) { warn(String.format( "This document appears to be written in %s." + " Consider adding \u201Clang=\"%s\"\u201D" + " (or variant) to the \u201Chtml\u201D element" + " start tag.", detectedLanguageName, preferredLanguageCode), htmlLocator); } String message = "This document appears to be written in %s but the" + " \u201Chtml\u201D element start tag has %s" + " \u201C%s\u201D attribute with the value \u201C%s\u201D." + " Consider changing the \u201C%s\u201D value to" + " \u201C%s\u201D (or variant) instead."; if (hasLang && !(new ULocale(langAttrValue).getLanguage()).equals( detectedLanguageCode)) { warn(String.format(message, detectedLanguageName, "a", "lang", langAttrValue, "lang", preferredLanguageCode), htmlLocator); } if (hasXmlLang && !(new ULocale(xmlLangAttrValue).getLanguage()).equals( detectedLanguageCode)) { warn(String.format(message, detectedLanguageName, "an", "xml:lang", xmlLangAttrValue, "xml:lang", preferredLanguageCode), htmlLocator); } reset(); } catch (LangDetectException e) { e.printStackTrace(); } } }
package com.exedio.cope; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import com.exedio.cope.util.ReactivationConstructorDummy; public final class Type implements Selectable { private static final HashMap<Class<? extends Item>, Type> typesByClass = new HashMap<Class<? extends Item>, Type>(); final Class<? extends Item> javaClass; final String id; private final Type supertype; private final List<Feature> declaredFeatures; private final List<Feature> features; private final HashMap<String, Feature> declaredFeaturesByName; private final HashMap<String, Feature> featuresByName; private final List<Attribute> declaredAttributes; private final List<Attribute> attributes; final List<UniqueConstraint> declaredUniqueConstraints; private final List<UniqueConstraint> uniqueConstraints; private ArrayList<Type> subTypes = null; private ArrayList<ItemAttribute> references = null; private Model model; private ArrayList<Type> typesOfInstances; private Type onlyPossibleTypeOfInstances; private String[] typesOfInstancesColumnValues; private Table table; private PkSource pkSource; private final Constructor creationConstructor; private final Constructor reactivationConstructor; /** * This number uniquely identifies a type within its model. * However, this number is not stable across JVM restarts. * So never put this number into any persistent storage, * nor otherwise make this number accessible outside the library. */ int transientNumber = -1; /** * @throws RuntimeException if there is no type for the given java class. */ public static final Type findByJavaClass(final Class<? extends Item> javaClass) { final Type result = typesByClass.get(javaClass); if(result==null) throw new RuntimeException("there is no type for "+javaClass); return result; } private ArrayList<Feature> featuresWhileConstruction; private static final String classToId(final Class javaClass) { final String className = javaClass.getName(); final int pos = className.lastIndexOf('.'); return className.substring(pos+1).intern(); } public Type(final Class<? extends Item> javaClass) { this(javaClass, classToId(javaClass)); } public Type(final Class<? extends Item> javaClass, final String id) { this.javaClass = javaClass; this.id = id; if(javaClass.equals(Item.class)) throw new IllegalArgumentException("Cannot make a type for " + javaClass + " itself, but only for subclasses."); typesByClass.put(javaClass, this); // supertype final Class superClass = javaClass.getSuperclass(); if(superClass.equals(Item.class)) supertype = null; else { supertype = findByJavaClass(castSuperType(superClass)); supertype.registerSubType(this); } // declared features final Field[] fields = javaClass.getDeclaredFields(); this.featuresWhileConstruction = new ArrayList<Feature>(fields.length); final int expectedModifier = Modifier.STATIC | Modifier.FINAL; try { for(final Field field : fields) { if((field.getModifiers()&expectedModifier)==expectedModifier) { final Class fieldType = field.getType(); if(Feature.class.isAssignableFrom(fieldType)) { field.setAccessible(true); final Feature feature = (Feature)field.get(null); if(feature==null) throw new RuntimeException(field.getName()); feature.initialize(this, field.getName(), field.getGenericType()); } } } } catch(IllegalAccessException e) { throw new RuntimeException(e); } featuresWhileConstruction.trimToSize(); this.declaredFeatures = Collections.unmodifiableList(featuresWhileConstruction); // make sure, method registerInitialization fails from now on this.featuresWhileConstruction = null; // declared attributes / unique constraints { final ArrayList<Attribute> declaredAttributes = new ArrayList<Attribute>(declaredFeatures.size()); final ArrayList<UniqueConstraint> declaredUniqueConstraints = new ArrayList<UniqueConstraint>(declaredFeatures.size()); final HashMap<String, Feature> declaredFeaturesByName = new HashMap<String, Feature>(); for(final Feature feature : declaredFeatures) { if(feature instanceof Attribute) declaredAttributes.add((Attribute)feature); if(feature instanceof UniqueConstraint) declaredUniqueConstraints.add((UniqueConstraint)feature); if(declaredFeaturesByName.put(feature.getName(), feature)!=null) throw new RuntimeException("duplicate feature "+feature.getName()+" for type "+javaClass.getName()); } declaredAttributes.trimToSize(); declaredUniqueConstraints.trimToSize(); this.declaredAttributes = Collections.unmodifiableList(declaredAttributes); this.declaredUniqueConstraints = Collections.unmodifiableList(declaredUniqueConstraints); this.declaredFeaturesByName = declaredFeaturesByName; } // inherit features / attributes if(supertype==null) { this.features = this.declaredFeatures; this.featuresByName = this.declaredFeaturesByName; this.attributes = this.declaredAttributes; this.uniqueConstraints = this.declaredUniqueConstraints; } else { this.features = inherit(supertype.getFeatures(), this.declaredFeatures); { final HashMap<String, Feature> inherited = supertype.featuresByName; final HashMap<String, Feature> own = this.declaredFeaturesByName; if(own.isEmpty()) this.featuresByName = inherited; else { final HashMap<String, Feature> result = new HashMap<String, Feature>(inherited); for(final Feature f : own.values()) { if(result.put(f.getName(), f)!=null) throw new RuntimeException("cannot override inherited feature "+f.getName()+" in type "+id); } this.featuresByName = result; } } this.attributes = inherit(supertype.getAttributes(), this.declaredAttributes); this.uniqueConstraints = inherit(supertype.getUniqueConstraints(), this.declaredUniqueConstraints); } // IMPLEMENTATION NOTE // Here we don't precompute the constructor parameters // because they are needed in the initialization phase // only. this.creationConstructor = getConstructor(new Class[]{(new SetValue[0]).getClass()}, "creation"); this.reactivationConstructor = getConstructor(new Class[]{ReactivationConstructorDummy.class, int.class}, "reactivation"); } @SuppressWarnings("unchecked") private static final Class<Item> castSuperType(final Class o) { return (Class<Item>)o; } private static final <F extends Feature> List<F> inherit(final List<F> inherited, final List<F> own) { assert inherited!=null; if(own.isEmpty()) return inherited; else if(inherited.isEmpty()) return own; else { final ArrayList<F> result = new ArrayList<F>(inherited); result.addAll(own); result.trimToSize(); return Collections.<F>unmodifiableList(result); } } private Constructor getConstructor(final Class[] params, final String name) { try { final Constructor result = javaClass.getDeclaredConstructor(params); result.setAccessible(true); return result; } catch(NoSuchMethodException e) { throw new RuntimeException(javaClass.getName() + " does not have a " + name + " constructor", e); } } void registerInitialization(final Feature feature) { featuresWhileConstruction.add(feature); } void registerSubType(final Type subType) { assert subType!=null : id; if(this.model!=null) throw new RuntimeException(id+'-'+subType.id); if(subTypes==null) subTypes = new ArrayList<Type>(); subTypes.add(subType); } void registerReference(final ItemAttribute reference) { if(this.model==null) throw new RuntimeException(); if(references==null) references = new ArrayList<ItemAttribute>(); references.add(reference); } void initialize(final Model model, final int transientNumber) { if(model==null) throw new RuntimeException(); assert (transientNumber<0) == isAbstract(); if(this.model!=null) throw new RuntimeException(); if(this.typesOfInstances!=null) throw new RuntimeException(); if(this.onlyPossibleTypeOfInstances!=null) throw new RuntimeException(); if(this.typesOfInstancesColumnValues!=null) throw new RuntimeException(); if(this.table!=null) throw new RuntimeException(); if(this.pkSource!=null) throw new RuntimeException(); if(this.transientNumber>=0) throw new RuntimeException(); this.model = model; this.transientNumber = transientNumber; typesOfInstances = new ArrayList<Type>(); collectTypesOfInstances(typesOfInstances, 15); switch(typesOfInstances.size()) { case 0: throw new RuntimeException("type " + id + " is abstract and has no non-abstract (even indirect) subtypes"); case 1: onlyPossibleTypeOfInstances = typesOfInstances.iterator().next(); break; default: typesOfInstancesColumnValues = new String[typesOfInstances.size()]; int i = 0; for(final Type t : typesOfInstances) typesOfInstancesColumnValues[i++] = t.id; break; } } private void collectTypesOfInstances(final ArrayList<Type> result, int levelLimit) { if(levelLimit<=0) throw new RuntimeException(result.toString()); levelLimit if(!isAbstract()) result.add(this); for(final Type t : getSubTypes()) t.collectTypesOfInstances(result, levelLimit); } void materialize(final Database database) { if(database==null) throw new RuntimeException(); if(this.model==null) throw new RuntimeException(); if(this.table!=null) throw new RuntimeException(); if(this.pkSource!=null) throw new RuntimeException(); this.table = new Table(database, id, supertype, typesOfInstancesColumnValues); if(supertype!=null) pkSource = supertype.getPkSource(); else pkSource = database.makePkSource(table); for(final Attribute a : declaredAttributes) a.materialize(table); for(final UniqueConstraint uc : declaredUniqueConstraints) uc.materialize(database); this.table.setUniqueConstraints(this.declaredUniqueConstraints); this.table.finish(); } public Class<? extends Item> getJavaClass() { return javaClass; } public String getID() { return id; } public Model getModel() { if(model==null) throw new RuntimeException("model not set for type " + id + ", probably you forgot to put this type into the model."); return model; } /** * Returns a list of types, * that instances (items) of this type can have. * These are all subtypes of this type, * including indirect subtypes, * and including this type itself, * which are not abstract. */ List<Type> getTypesOfInstances() { if(typesOfInstances==null) throw new RuntimeException(); return Collections.unmodifiableList(typesOfInstances); } Type getOnlyPossibleTypeOfInstances() { if(typesOfInstances==null) throw new RuntimeException(); return onlyPossibleTypeOfInstances; } String[] getTypesOfInstancesColumnValues() { if(typesOfInstances==null) throw new RuntimeException(); if(typesOfInstancesColumnValues==null) return null; else { final String[] result = new String[typesOfInstancesColumnValues.length]; System.arraycopy(typesOfInstancesColumnValues, 0, result, 0, result.length); return result; } } Table getTable() { if(model==null) throw new RuntimeException(); return table; } /** * Returns the name of database table for this type - use with care! * <p> * This information is needed only, if you want to access * the database without cope. * In this case you should really know, what you are doing. * Please note, that this string may vary, * if a cope model is configured for different databases. * * @see Attribute#getColumnName() */ public String getTableName() { return table.id; } /** * Returns the type representing the {@link Class#getSuperclass() superclass} * of this type's {@link #getJavaClass() java class}. * If this type has no super type * (i.e. the superclass of this type's java class is {@link Item}), * then null is returned. */ public Type getSupertype() { return supertype; } public List<Type> getSubTypes() { return subTypes==null ? Collections.<Type>emptyList() : Collections.unmodifiableList(subTypes); } public boolean isAssignableFrom(final Type type) { return javaClass.isAssignableFrom(type.javaClass); } public boolean isAbstract() { return ( javaClass.getModifiers() & Modifier.ABSTRACT ) > 0; } public List<ItemAttribute> getReferences() { return references==null ? Collections.<ItemAttribute>emptyList() : Collections.unmodifiableList(references); } /** * Returns the list of persistent attributes declared by the this type. * This excludes inherited attributes. * The elements in the list returned are ordered by their occurance in the source code. * This method returns an empty list if the type declares no attributes. * <p> * If you want to get all persistent attributes of this type, * including attributes inherited from super types, * use {@link #getAttributes}. * <p> * Naming of this method is inspired by Java Reflection API * method {@link Class#getDeclaredFields() getDeclaredFields}. */ public List<Attribute> getDeclaredAttributes() { return declaredAttributes; } /** * Returns the list of accessible persistent attributes of this type. * This includes inherited attributes. * The elements in the list returned are ordered by their type, * with types higher in type hierarchy coming first, * and within each type by their occurance in the source code. * This method returns an empty list if the type has no accessible attributes. * <p> * If you want to get persistent attributes declared by this type only, * excluding attributes inherited from super types, * use {@link #getDeclaredAttributes}. */ public List<Attribute> getAttributes() { return attributes; } public List<Feature> getDeclaredFeatures() { return declaredFeatures; } public List<Feature> getFeatures() { return features; } public Feature getDeclaredFeature(final String name) { return declaredFeaturesByName.get(name); } public Feature getFeature(final String name) { return featuresByName.get(name); } public List<UniqueConstraint> getDeclaredUniqueConstraints() { return declaredUniqueConstraints; } public List<UniqueConstraint> getUniqueConstraints() { return uniqueConstraints; } private static final SetValue[] EMPTY_SET_VALUES = new SetValue[]{}; public Item newItem(final SetValue[] setValues) throws ConstraintViolationException { final Item result; try { result = (Item)creationConstructor.newInstance( new Object[]{ setValues!=null ? setValues : EMPTY_SET_VALUES } ); } catch(InstantiationException e) { throw new RuntimeException(e); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch(InvocationTargetException e) { final Throwable t = e.getCause(); if(t instanceof RuntimeException) throw (RuntimeException)t; else throw new RuntimeException(e); } return result; } /** * Searches for items of this type, that match the given condition. * <p> * Returns an unmodifiable collection. * Any attempts to modify the returned collection, whether direct or via its iterator, * result in an <tt>UnsupportedOperationException</tt>. * @param condition the condition the searched items must match. */ public Collection<? extends Object> search(final Condition condition) { return new Query(this, condition).search(); } public Collection<? extends Object> search(final Condition condition, final Function orderBy, final boolean ascending) { final Query query = new Query(this, condition); query.setOrderBy(orderBy, ascending); return query.search(); } /** * Searches equivalently to {@link #search(Condition)}, * but assumes that the condition forces the search result to have at most one element. * <p> * Returns null, if the search result is {@link Collection#isEmpty() empty}, * returns the only element of the search result, if the result {@link Collection#size() size} is exactly one. * @throws RuntimeException if the search result size is greater than one. */ public Item searchUnique(final Condition condition) { final Iterator searchResult = search(condition).iterator(); if(searchResult.hasNext()) { final Item result = (Item)searchResult.next(); if(searchResult.hasNext()) throw new RuntimeException(condition.toString()); else return result; } else return null; } public String toString() { return id; } PkSource getPkSource() { if(pkSource==null) throw new RuntimeException("no primary key source in " + id + "; maybe you have to initialize the model first"); return pkSource; } void onDropTable() { getPkSource().flushPK(); } static final ReactivationConstructorDummy REACTIVATION_DUMMY = new ReactivationConstructorDummy(); Item getItemObject(final int pk) { final Entity entity = getModel().getCurrentTransaction().getEntityIfActive(this, pk); if(entity!=null) return entity.getItem(); try { return (Item)reactivationConstructor.newInstance( new Object[]{ REACTIVATION_DUMMY, Integer.valueOf(pk) } ); } catch(InstantiationException e) { throw new RuntimeException(id, e); } catch(IllegalAccessException e) { throw new RuntimeException(id, e); } catch(InvocationTargetException e) { throw new RuntimeException(id, e); } } static final int NOT_A_PK = Integer.MIN_VALUE; }
package org.ubercraft.statsd; import static org.ubercraft.statsd.StatsdStatType.COUNTER; import static org.ubercraft.statsd.StatsdStatType.TIMER; import java.io.ObjectStreamException; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.Marker; /** * This class provides a statsd/slf4j-like interface for logging statsd stats. Each instance wraps a given * {@link Logger} instance; * <p/> * For any instance of this class, the name of the logger corresponds to the statsd key that will be logged by it. Use * the <code>xxxCount(...)</code>, <code>xxxTime(...)</code> and <code>xxxStat(...)</code> methods to log stats as * desired. * <p/> * This class has three <code>statXxx(...)</code> methods, which can be overridden in order to customise exactly how the * log message is constructed prior to being logged. The expectation is that the message logged will be understandable * by whatever appender has been attached to this logger. * * @see StatsdLoggerFactory */ public class StatsdLoggerImpl implements StatsdLogger, Serializable { private static final long serialVersionUID = 6548797032077199054L; protected final Logger logger; public StatsdLoggerImpl(Logger logger) { this.logger = logger; } public String getName() { return logger.getName(); } @Override public String toString() { return "StatsdLoggerImpl[" + getName() + "]"; } // deserialization protected Object readResolve() throws ObjectStreamException { return StatsdLoggerFactory.getLogger(getName()); } // Info level @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public void infoCount() { infoCount(1); } @Override public void infoCount(int count) { infoCount(count, 1.0D); } @Override public void infoCount(double sampleRate) { infoCount(1, sampleRate); } @Override public void infoCount(int count, double sampleRate) { infoStat(COUNTER, count, sampleRate); } @Override public void infoTime(int millis) { infoTime(millis, 1.0); } @Override public void infoTime(int millis, double sampleRate) { infoStat(TIMER, millis, sampleRate); } @Override public void infoStat(StatsdStatType type, int value, double sampleRate) { if (isInfoEnabled()) logger.info( statMarker(type, value, sampleRate), statMessage(type, value, sampleRate), statArgs(type, value, sampleRate)); } // Debug level @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public void debugCount() { debugCount(1); } @Override public void debugCount(int count) { debugCount(count, 1.0D); } @Override public void debugCount(double sampleRate) { debugCount(1, sampleRate); } @Override public void debugCount(int count, double sampleRate) { debugStat(COUNTER, count, sampleRate); } @Override public void debugTime(int millis) { debugTime(millis, 1.0); } @Override public void debugTime(int millis, double sampleRate) { debugStat(TIMER, millis, sampleRate); } @Override public void debugStat(StatsdStatType type, int value, double sampleRate) { if (isDebugEnabled()) logger.debug( statMarker(type, value, sampleRate), statMessage(type, value, sampleRate), statArgs(type, value, sampleRate)); } // Trace level @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void traceCount() { traceCount(1); } @Override public void traceCount(int count) { traceCount(count, 1.0D); } @Override public void traceCount(double sampleRate) { traceCount(1, sampleRate); } @Override public void traceCount(int count, double sampleRate) { traceStat(COUNTER, count, sampleRate); } @Override public void traceTime(int millis) { traceTime(millis, 1.0); } @Override public void traceTime(int millis, double sampleRate) { traceStat(TIMER, millis, sampleRate); } @Override public void traceStat(StatsdStatType type, int value, double sampleRate) { if (isTraceEnabled()) logger.trace( statMarker(type, value, sampleRate), statMessage(type, value, sampleRate), statArgs(type, value, sampleRate)); } // override-able methods for creating the actual parameters used to call the underlying logger with // (the default behaviour suits logback) protected Marker statMarker(StatsdStatType type, int value, double sampleRate) { return null; } protected String statMessage(StatsdStatType type, int value, double sampleRate) { return null; } protected Object[] statArgs(StatsdStatType type, int value, double sampleRate) { return new Object[] { type, value, sampleRate }; } }
package com.exedio.cope; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.exedio.cope.search.ExtremumAggregate; import com.exedio.cope.util.ReactivationConstructorDummy; public final class Type<C extends Item> { private static final HashMap<Class<? extends Item>, Type<? extends Item>> typesByClass = new HashMap<Class<? extends Item>, Type<? extends Item>>(); final Class<C> javaClass; private final boolean withoutJavaClass; final String id; final boolean isAbstract; final Type<? super C> supertype; final This<C> thisFunction = new This<C>(this); private final List<Feature> declaredFeatures; private final List<Feature> features; private final HashMap<String, Feature> declaredFeaturesByName; private final HashMap<String, Feature> featuresByName; private final List<Attribute> declaredAttributes; private final List<Attribute> attributes; final List<UniqueConstraint> declaredUniqueConstraints; private final List<UniqueConstraint> uniqueConstraints; private ArrayList<Type<? extends C>> subTypes = null; private ArrayList<ItemAttribute<C>> referencesWhileInitialization = new ArrayList<ItemAttribute<C>>(); private List<ItemAttribute<C>> declaredReferences = null; private List<ItemAttribute> references = null; private Model model; private ArrayList<Type<? extends C>> subTypesTransitively; private ArrayList<Type<? extends C>> typesOfInstances; private HashMap<String, Type<? extends C>> typesOfInstancesMap; private Type<? extends C> onlyPossibleTypeOfInstances; private String[] typesOfInstancesColumnValues; private Table table; private PkSource pkSource; private final Constructor<C> creationConstructor; private final Constructor<C> reactivationConstructor; /** * This number uniquely identifies a type within its model. * However, this number is not stable across JVM restarts. * So never put this number into any persistent storage, * nor otherwise make this number accessible outside the library. * <p> * This number is negative for abstract types and positive * (including zero) for non-abstract types. */ int transientNumber = -1; /** * @throws RuntimeException if there is no type for the given java class. */ public static final <X extends Item> Type<X> findByJavaClass(final Class<X> javaClass) { return findByJavaClassUnchecked(javaClass).castType(javaClass); } @SuppressWarnings("unchecked") // OK: unchecked cast is checked manually using runtime type information public <X extends Item> Type<X> castType(final Class<X> clazz) { if(javaClass!=clazz) throw new ClassCastException("expected " + clazz.getName() + ", but was " + javaClass.getName()); return (Type<X>)this; } /** * @throws RuntimeException if there is no type for the given java class. */ public static final Type<?> findByJavaClassUnchecked(final Class<?> javaClass) { final Type<? extends Item> result = typesByClass.get(javaClass); if(result==null) throw new RuntimeException("there is no type for " + javaClass); return result; } private ArrayList<Feature> featuresWhileConstruction; Type(final Class<C> javaClass) { this(javaClass, javaClass.getSimpleName()); } Type(final Class<C> javaClass, final String id) { this(javaClass, id, getFeatureMap(javaClass)); } private static final LinkedHashMap<String, Feature> getFeatureMap(final Class<?> javaClass) { final LinkedHashMap<String, Feature> result = new LinkedHashMap<String, Feature>(); final Field[] fields = javaClass.getDeclaredFields(); final int expectedModifier = Modifier.STATIC | Modifier.FINAL; try { for(final Field field : fields) { if((field.getModifiers()&expectedModifier)==expectedModifier) { final Class fieldType = field.getType(); if(Feature.class.isAssignableFrom(fieldType)) { field.setAccessible(true); final Feature feature = (Feature)field.get(null); if(feature==null) throw new RuntimeException(field.getName()); result.put(field.getName(), feature); } } } } catch(IllegalAccessException e) { throw new RuntimeException(e); } return result; } Type(final Class<C> javaClass, final String id, final LinkedHashMap<String, Feature> featureMap) { this.javaClass = javaClass; this.withoutJavaClass = (javaClass==ItemWithoutJavaClass.class); this.id = id; this.isAbstract = ( javaClass.getModifiers() & Modifier.ABSTRACT ) > 0; if(!Item.class.isAssignableFrom(javaClass)) throw new IllegalArgumentException(javaClass + " is not a subclass of Item"); if(javaClass.equals(Item.class)) throw new IllegalArgumentException("Cannot make a type for " + javaClass + " itself, but only for subclasses."); if(!withoutJavaClass) typesByClass.put(javaClass, this); // supertype final Class superClass = javaClass.getSuperclass(); if(superClass.equals(Item.class)) supertype = null; else { supertype = findByJavaClass(castSuperType(superClass)); supertype.registerSubType(this); } // declared features this.featuresWhileConstruction = new ArrayList<Feature>(featureMap.size() + 1); thisFunction.initialize(this, This.NAME); for(final Map.Entry<String, Feature> entry : featureMap.entrySet()) entry.getValue().initialize(this, entry.getKey()); featuresWhileConstruction.trimToSize(); this.declaredFeatures = Collections.unmodifiableList(featuresWhileConstruction); // make sure, method registerInitialization fails from now on this.featuresWhileConstruction = null; // declared attributes / unique constraints { final ArrayList<Attribute> declaredAttributes = new ArrayList<Attribute>(declaredFeatures.size()); final ArrayList<UniqueConstraint> declaredUniqueConstraints = new ArrayList<UniqueConstraint>(declaredFeatures.size()); final HashMap<String, Feature> declaredFeaturesByName = new HashMap<String, Feature>(); for(final Feature feature : declaredFeatures) { if(feature instanceof Attribute) declaredAttributes.add((Attribute)feature); if(feature instanceof UniqueConstraint) declaredUniqueConstraints.add((UniqueConstraint)feature); if(declaredFeaturesByName.put(feature.getName(), feature)!=null) throw new RuntimeException("duplicate feature "+feature.getName()+" for type "+javaClass.getName()); } declaredAttributes.trimToSize(); declaredUniqueConstraints.trimToSize(); this.declaredAttributes = Collections.unmodifiableList(declaredAttributes); this.declaredUniqueConstraints = Collections.unmodifiableList(declaredUniqueConstraints); this.declaredFeaturesByName = declaredFeaturesByName; } // inherit features / attributes if(supertype==null) { this.features = this.declaredFeatures; this.featuresByName = this.declaredFeaturesByName; this.attributes = this.declaredAttributes; this.uniqueConstraints = this.declaredUniqueConstraints; } else { { final ArrayList<Feature> features = new ArrayList<Feature>(); features.add(thisFunction); final List<Feature> superFeatures = supertype.getFeatures(); features.addAll(superFeatures.subList(1, superFeatures.size())); features.addAll(this.declaredFeatures.subList(1, this.declaredFeatures.size())); features.trimToSize(); this.features = Collections.unmodifiableList(features); } { final HashMap<String, Feature> inherited = supertype.featuresByName; final HashMap<String, Feature> declared = this.declaredFeaturesByName; final HashMap<String, Feature> result = new HashMap<String, Feature>(inherited); for(final Feature f : declared.values()) { if(result.put(f.getName(), f)!=null && !(f instanceof This)) System.out.println("hiding inherited feature " + f.getName() + " in type " + id); } this.featuresByName = result; } this.attributes = inherit(supertype.getAttributes(), this.declaredAttributes); this.uniqueConstraints = inherit(supertype.getUniqueConstraints(), this.declaredUniqueConstraints); } // IMPLEMENTATION NOTE // Here we don't precompute the constructor parameters // because they are needed in the initialization phase // only. this.creationConstructor = getConstructor(new Class[]{SetValue[].class}, "creation"); this.reactivationConstructor = getConstructor(new Class[]{ReactivationConstructorDummy.class, int.class}, "reactivation"); } @SuppressWarnings("unchecked") // OK: Class.getSuperclass() does not support generics private static final Class<Item> castSuperType(final Class o) { return (Class<Item>)o; } private static final <F extends Feature> List<F> inherit(final List<F> inherited, final List<F> declared) { assert inherited!=null; if(declared.isEmpty()) return inherited; else if(inherited.isEmpty()) return declared; else { final ArrayList<F> result = new ArrayList<F>(inherited); result.addAll(declared); result.trimToSize(); return Collections.<F>unmodifiableList(result); } } private Constructor<C> getConstructor(final Class[] params, final String name) { if(withoutJavaClass) return null; try { final Constructor<C> result = javaClass.getDeclaredConstructor(params); result.setAccessible(true); return result; } catch(NoSuchMethodException e) { throw new RuntimeException(javaClass.getName() + " does not have a " + name + " constructor", e); } } void registerInitialization(final Feature feature) { featuresWhileConstruction.add(feature); } void registerSubType(final Type subType) { assert subType!=null : id; if(this.model!=null) throw new RuntimeException(id+'-'+subType.id); if(subTypes==null) subTypes = new ArrayList<Type<? extends C>>(); subTypes.add(castTypeInstance(subType)); } @SuppressWarnings("unchecked") private Type<? extends C> castTypeInstance(final Type t) { return t; } void registerReference(final ItemAttribute<C> reference) { referencesWhileInitialization.add(reference); } void initialize(final Model model, final int transientNumber) { if(model==null) throw new RuntimeException(); assert (transientNumber<0) == isAbstract; if(this.model!=null) throw new RuntimeException(); if(this.subTypesTransitively!=null) throw new RuntimeException(); if(this.typesOfInstances!=null) throw new RuntimeException(); if(this.typesOfInstancesMap!=null) throw new RuntimeException(); if(this.onlyPossibleTypeOfInstances!=null) throw new RuntimeException(); if(this.typesOfInstancesColumnValues!=null) throw new RuntimeException(); if(this.table!=null) throw new RuntimeException(); if(this.pkSource!=null) throw new RuntimeException(); if(this.transientNumber>=0) throw new RuntimeException(); this.model = model; this.transientNumber = transientNumber; final ArrayList<Type> subTypesTransitively = new ArrayList<Type>(); final ArrayList<Type> typesOfInstances = new ArrayList<Type>(); collectSubTypes(subTypesTransitively, typesOfInstances, 15); switch(typesOfInstances.size()) { case 0: throw new RuntimeException("type " + id + " is abstract and has no non-abstract (even indirect) subtypes"); case 1: onlyPossibleTypeOfInstances = castTypeInstance(typesOfInstances.iterator().next()); break; default: final HashMap<String, Type> typesOfInstancesMap = new HashMap<String, Type>(); typesOfInstancesColumnValues = new String[typesOfInstances.size()]; int i = 0; for(final Type t : typesOfInstances) { if(typesOfInstancesMap.put(t.id, t)!=null) throw new RuntimeException(t.id); typesOfInstancesColumnValues[i++] = t.id; } this.typesOfInstancesMap = castTypeInstanceHasMap(typesOfInstancesMap); break; } this.subTypesTransitively = castTypeInstanceArrayList(subTypesTransitively); this.typesOfInstances = castTypeInstanceArrayList(typesOfInstances); for(final Attribute a : declaredAttributes) if(a instanceof ItemAttribute) ((ItemAttribute)a).postInitialize(); } @SuppressWarnings("unchecked") private ArrayList<Type<? extends C>> castTypeInstanceArrayList(final ArrayList l) { return l; } @SuppressWarnings("unchecked") private HashMap<String, Type<? extends C>> castTypeInstanceHasMap(final HashMap m) { return m; } private void collectSubTypes(final ArrayList<Type> all, final ArrayList<Type> concrete, int levelLimit) { if(levelLimit<=0) throw new RuntimeException(all.toString()); levelLimit all.add(this); if(!isAbstract) concrete.add(this); for(final Type<? extends C> t : getSubTypes()) t.collectSubTypes(all, concrete, levelLimit); } void postInitialize() { assert referencesWhileInitialization!=null; assert declaredReferences==null; assert references==null; referencesWhileInitialization.trimToSize(); this.declaredReferences = Collections.unmodifiableList(referencesWhileInitialization); this.referencesWhileInitialization = null; if(supertype!=null) { final List<ItemAttribute> inherited = supertype.getReferences(); final List<ItemAttribute<C>> declared = declaredReferences; if(declared.isEmpty()) this.references = inherited; else if(inherited.isEmpty()) this.references = castReferences(declared); else { final ArrayList<ItemAttribute> result = new ArrayList<ItemAttribute>(inherited); result.addAll(declared); result.trimToSize(); this.references = Collections.unmodifiableList(result); } } else { this.references = castReferences(declaredReferences); } } @SuppressWarnings("unchecked") private List<ItemAttribute> castReferences(final List l) { return (List<ItemAttribute>)l; } void materialize(final Database database) { if(database==null) throw new RuntimeException(); if(this.model==null) throw new RuntimeException(); if(this.table!=null) throw new RuntimeException(); if(this.pkSource!=null) throw new RuntimeException(); this.table = new Table(database, id, supertype, typesOfInstancesColumnValues); if(supertype!=null) pkSource = supertype.getPkSource(); else pkSource = database.makePkSource(table); for(final Attribute a : declaredAttributes) a.materialize(table); for(final UniqueConstraint uc : declaredUniqueConstraints) uc.materialize(database); this.table.setUniqueConstraints(this.declaredUniqueConstraints); this.table.finish(); } public Class<C> getJavaClass() { return javaClass; } /** * @see Model#findTypeByID(String) */ public String getID() { return id; } public Model getModel() { if(model==null) throw new RuntimeException("model not set for type " + id + ", probably you forgot to put this type into the model."); return model; } /** * Returns a list of types, * that instances (items) of this type can have. * These are all subtypes of this type, * including indirect subtypes, * and including this type itself, * which are not abstract. */ public List<Type<? extends C>> getTypesOfInstances() { if(typesOfInstances==null) throw new RuntimeException(); return Collections.unmodifiableList(typesOfInstances); } Type<? extends C> getTypeOfInstance(final String id) { return typesOfInstancesMap.get(id); } Type<? extends C> getOnlyPossibleTypeOfInstances() { if(typesOfInstances==null) throw new RuntimeException(); return onlyPossibleTypeOfInstances; } String[] getTypesOfInstancesColumnValues() { if(typesOfInstances==null) throw new RuntimeException(); if(typesOfInstancesColumnValues==null) return null; else { final String[] result = new String[typesOfInstancesColumnValues.length]; System.arraycopy(typesOfInstancesColumnValues, 0, result, 0, result.length); return result; } } Table getTable() { if(model==null) throw new RuntimeException(); return table; } public int[] getPrimaryKeyInfo() { return getPkSource().getPrimaryKeyInfo(); } /** * Returns the name of database table for this type * - <b>use with care!</b> * <p> * This information is needed only, if you want to access * the database without cope. * In this case you should really know, what you are doing. * Any INSERT/UPDATE/DELETE on the database bypassing cope * may lead to inconsistent caches. * Please note, that this string may vary, * if a cope model is configured for different databases. * * @see #getPrimaryKeyColumnName() * @see #getTypeColumnName() * @see Attribute#getColumnName() * @see ItemAttribute#getTypeColumnName() */ public String getTableName() { return table.id; } /** * Returns the name of primary key column in the database for this type * - <b>use with care!</b> * <p> * This information is needed only, if you want to access * the database without cope. * In this case you should really know, what you are doing. * Any INSERT/UPDATE/DELETE on the database bypassing cope * may lead to inconsistent caches. * Please note, that this string may vary, * if a cope model is configured for different databases. * * @see #getTableName() * @see #getTypeColumnName() * @see Attribute#getColumnName() */ public String getPrimaryKeyColumnName() { return table.primaryKey.id; } /** * Returns the name of type column in the database for this type * - <b>use with care!</b> * <p> * This information is needed only, if you want to access * the database without cope. * In this case you should really know, what you are doing. * Any INSERT/UPDATE/DELETE on the database bypassing cope * may lead to inconsistent caches. * Please note, that this string may vary, * if a cope model is configured for different databases. * * @throws RuntimeException * if there is no type column for this type, * because <code>{@link Type#getTypesOfInstances()}</code> * contains one type only. * @see #getTableName() * @see #getPrimaryKeyColumnName() * @see Attribute#getColumnName() * @see ItemAttribute#getTypeColumnName() */ public String getTypeColumnName() { if(table.typeColumn==null) throw new RuntimeException("no type column for " + this); return table.typeColumn.id; } /** * Returns the type representing the {@link Class#getSuperclass() superclass} * of this type's {@link #getJavaClass() java class}. * If this type has no super type * (i.e. the superclass of this type's java class is {@link Item}), * then null is returned. */ public Type<? super C> getSupertype() { return supertype; } /** * @see #getSubTypesTransitively() */ public List<Type<? extends C>> getSubTypes() { return subTypes==null ? Collections.<Type<? extends C>>emptyList() : Collections.unmodifiableList(subTypes); } /** * @see #getSubTypes() */ public List<Type<? extends C>> getSubTypesTransitively() { if(subTypesTransitively==null) throw new RuntimeException(); return Collections.unmodifiableList(subTypesTransitively); } public boolean isAssignableFrom(final Type type) { return javaClass.isAssignableFrom(type.javaClass); } public boolean isAbstract() { return isAbstract; } public This<C> getThis() { return thisFunction; } /** * Returns all {@link ItemAttribute}s of the model this type belongs to, * which {@link ItemAttribute#getValueType value type} equals this type. * @see #getReferences() */ public List<ItemAttribute<C>> getDeclaredReferences() { assert declaredReferences!=null; return declaredReferences; } /** * Returns all {@link ItemAttribute}s of the model this type belongs to, * which {@link ItemAttribute#getValueType value type} equals this type * or any of it's super types. * @see #getDeclaredReferences() */ public List<ItemAttribute> getReferences() { assert references!=null; return references; } /** * Returns the list of persistent attributes declared by the this type. * This excludes inherited attributes. * The elements in the list returned are ordered by their occurance in the source code. * This method returns an empty list if the type declares no attributes. * <p> * If you want to get all persistent attributes of this type, * including attributes inherited from super types, * use {@link #getAttributes}. * <p> * Naming of this method is inspired by Java Reflection API * method {@link Class#getDeclaredFields() getDeclaredFields}. */ public List<Attribute> getDeclaredAttributes() { return declaredAttributes; } /** * Returns the list of accessible persistent attributes of this type. * This includes inherited attributes. * The elements in the list returned are ordered by their type, * with types higher in type hierarchy coming first, * and within each type by their occurance in the source code. * This method returns an empty list if the type has no accessible attributes. * <p> * If you want to get persistent attributes declared by this type only, * excluding attributes inherited from super types, * use {@link #getDeclaredAttributes}. */ public List<Attribute> getAttributes() { return attributes; } public List<Feature> getDeclaredFeatures() { return declaredFeatures; } public List<Feature> getFeatures() { return features; } public Feature getDeclaredFeature(final String name) { return declaredFeaturesByName.get(name); } public Feature getFeature(final String name) { return featuresByName.get(name); } public List<UniqueConstraint> getDeclaredUniqueConstraints() { return declaredUniqueConstraints; } public List<UniqueConstraint> getUniqueConstraints() { return uniqueConstraints; } private static final SetValue[] EMPTY_SET_VALUES = {}; public C newItem(final SetValue[] setValues) throws ConstraintViolationException { if(withoutJavaClass) return cast(new ItemWithoutJavaClass(setValues, this)); try { return creationConstructor.newInstance( new Object[]{ setValues!=null ? setValues : EMPTY_SET_VALUES } ); } catch(InstantiationException e) { throw new RuntimeException(e); } catch(IllegalAccessException e) { throw new RuntimeException(e); } catch(InvocationTargetException e) { final Throwable t = e.getCause(); if(t instanceof RuntimeException) throw (RuntimeException)t; else throw new RuntimeException(e); } } public C cast(final Item item) { return Cope.verboseCast(javaClass, item); } /** * Searches for items of this type, that match the given condition. * <p> * Returns an unmodifiable collection. * Any attempts to modify the returned collection, whether direct or via its iterator, * result in an <tt>UnsupportedOperationException</tt>. * @param condition the condition the searched items must match. */ public List<C> search(final Condition condition) { return newQuery(condition).search(); } public List<C> search(final Condition condition, final Function orderBy, final boolean ascending) { final Query<C> query = newQuery(condition); query.setOrderBy(orderBy, ascending); return query.search(); } /** * Searches equivalently to {@link #search(Condition)}, * but assumes that the condition forces the search result to have at most one element. * <p> * Returns null, if the search result is {@link Collection#isEmpty() empty}, * returns the only element of the search result, if the result {@link Collection#size() size} is exactly one. * @throws RuntimeException if the search result size is greater than one. * @see Query#searchSingleton() */ public C searchSingleton(final Condition condition) { return newQuery(condition).searchSingleton(); } /** * @deprecated renamed to {@link #searchSingleton(Condition)}. */ @Deprecated public C searchUnique(final Condition condition) { return searchSingleton(condition); } public Query<C> newQuery(final Condition condition) { return new Query<C>(thisFunction, this, condition); } @Override public String toString() { return id; } PkSource getPkSource() { if(pkSource==null) throw new RuntimeException("no primary key source in " + id + "; maybe you have to initialize the model first"); return pkSource; } void onDropTable() { getPkSource().flushPK(); } static final ReactivationConstructorDummy REACTIVATION_DUMMY = new ReactivationConstructorDummy(); C getItemObject(final int pk) { final Entity entity = getModel().getCurrentTransaction().getEntityIfActive(this, pk); if(entity!=null) return cast(entity.getItem()); else return createItemObject(pk); } C createItemObject(final int pk) { if(withoutJavaClass) return cast(new ItemWithoutJavaClass(pk, this)); try { return reactivationConstructor.newInstance( new Object[]{ REACTIVATION_DUMMY, Integer.valueOf(pk) } ); } catch(InstantiationException e) { throw new RuntimeException(id, e); } catch(IllegalAccessException e) { throw new RuntimeException(id, e); } catch(InvocationTargetException e) { throw new RuntimeException(id, e); } } static final int MIN_PK = Integer.MIN_VALUE + 1; static final int MAX_PK = Integer.MAX_VALUE; static final int NOT_A_PK = Integer.MIN_VALUE; public static final class This<E extends Item> extends Feature implements Function<E>, ItemFunction<E> { private static final String NAME = "this"; final Type<E> type; private This(final Type<E> type) { assert type!=null; this.type = type; } @Override void initialize(final Type<? extends Item> type, final String name) { super.initialize(type, name); assert this.type == type; assert NAME.equals(name); } public E get(final Item item) { return type.cast(item); } public Class<E> getValueClass() { return type.javaClass; } public void append(final Statement bf, final Join join) { bf.appendPK(type, join); } public void appendType(final Statement bf, final Join join) { bf.append(Statement.assertTypeColumn(type.getTable().typeColumn, type), join); } public final int getTypeForDefiningColumn() { return IntegerColumn.JDBC_TYPE_INT; } public void appendParameter(final Statement bf, final E value) { bf.appendParameter(value.pk); } public Type<E> getValueType() { return type; } public boolean needsCheckTypeColumn() { return type.supertype!=null && type.supertype.getTable().typeColumn!=null; } public int checkTypeColumn() { if(!needsCheckTypeColumn()) throw new RuntimeException("no check for type column needed for " + this); return type.table.database.checkTypeColumn(type.getModel().getCurrentTransaction().getConnection(), type); } public EqualCondition<E> equal(final E value) { return new EqualCondition<E>(this, value); } public EqualCondition<E> equal(final Join join, final E value) { return this.bind(join).equal(value); } public CompositeCondition in(final Collection<E> values) { return CompositeCondition.in(this, values); } public NotEqualCondition<E> notEqual(final E value) { return new NotEqualCondition<E>(this, value); } public EqualFunctionCondition<E> equal(final Function<E> right) { return new EqualFunctionCondition<E>(this, right); } public CompareCondition<E> less(final E value) { return new CompareCondition<E>(CompareCondition.Operator.Less, this, value); } public CompareCondition<E> lessOrEqual(final E value) { return new CompareCondition<E>(CompareCondition.Operator.LessEqual, this, value); } public CompareCondition<E> greater(final E value) { return new CompareCondition<E>(CompareCondition.Operator.Greater, this, value); } public CompareCondition<E> greaterOrEqual(final E value) { return new CompareCondition<E>(CompareCondition.Operator.GreaterEqual, this, value); } public ExtremumAggregate<E> min() { return new ExtremumAggregate<E>(this, true); } public ExtremumAggregate<E> max() { return new ExtremumAggregate<E>(this, false); } public final BindItemFunction<E> bind(final Join join) { return new BindItemFunction<E>(this, join); } public EqualFunctionCondition equalTarget() { return equal(getValueType().thisFunction); } public EqualFunctionCondition equalTarget(final Join targetJoin) { return equal(getValueType().thisFunction.bind(targetJoin)); } public TypeInCondition<E> typeIn(final Type<? extends E> type1) { return new TypeInCondition<E>(this, false, type1); } public TypeInCondition<E> typeIn(final Type<? extends E> type1, final Type<? extends E> type2) { return new TypeInCondition<E>(this, false, type1, type2); } public TypeInCondition<E> typeIn(final Type<? extends E> type1, final Type<? extends E> type2, final Type<? extends E> type3) { return new TypeInCondition<E>(this, false, type1, type2, type3); } public TypeInCondition<E> typeIn(final Type<? extends E> type1, final Type<? extends E> type2, final Type<? extends E> type3, final Type<E> type4) { return new TypeInCondition<E>(this, false, type1, type2, type3, type4); } public TypeInCondition<E> typeIn(final Type[] types) { return new TypeInCondition<E>(this, false, types); } public TypeInCondition<E> typeNotIn(final Type<? extends E> type1) { return new TypeInCondition<E>(this, true, type1); } public TypeInCondition<E> typeNotIn(final Type<? extends E> type1, final Type<? extends E> type2) { return new TypeInCondition<E>(this, true, type1, type2); } public TypeInCondition<E> typeNotIn(final Type<? extends E> type1, final Type<? extends E> type2, final Type<? extends E> type3) { return new TypeInCondition<E>(this, true, type1, type2, type3); } public TypeInCondition<E> typeNotIn(final Type<? extends E> type1, final Type<? extends E> type2, final Type<? extends E> type3, final Type<E> type4) { return new TypeInCondition<E>(this, true, type1, type2, type3, type4); } public TypeInCondition<E> typeNotIn(final Type[] types) { return new TypeInCondition<E>(this, true, types); } } }
package org.usc.check.in.task; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.usc.check.in.model.Account; /** * * @author Shunli */ @Component @ConfigurationProperties(prefix = "v2ex") public class V2exCheckInTask extends BaseTask { private static final Logger log = LoggerFactory.getLogger(V2exCheckInTask.class); private static final String LOGIN_URL = "https: private static final String CHECK_IN_URL = "https: private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36"; @Scheduled(cron = "0 0 9,18 * * ?") public void run() { for (Account account : getAccounts()) { try { RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build(); Executor executor = Executor.newInstance(client).use(new BasicCookieStore()); if (login(executor, account)) { checkIn(executor, account); } } catch (Exception e) { log.error("V2EX" + account.getUsername() + "", e); } } } private boolean login(Executor executor, Account account) throws ClientProtocolException, IOException, URISyntaxException { String usrename = account.getUsername(); // 1st get once Document checkLoginOnce = Jsoup.parse(executor.execute(appendTimeOuts(Request.Get(LOGIN_URL))).returnContent().asString()); String once = checkLoginOnce.getElementsByAttributeValue("name", "once").attr("value"); Elements elementsByClass = checkLoginOnce.getElementsByClass("sl"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair(elementsByClass.get(0).attr("name"), usrename)); formParams.add(new BasicNameValuePair(elementsByClass.get(1).attr("name"), account.getPassword())); formParams.add(new BasicNameValuePair("once", once)); formParams.add(new BasicNameValuePair("next", "/")); // login executor.execute(appendTimeOuts(Request.Post(LOGIN_URL)).bodyForm(formParams).userAgent(USER_AGENT).addHeader("Referer", "http://www/v2ex.com/signin")).discardContent(); // checkIn must load first page once String rtn = executor.execute(appendTimeOuts(Request.Get("http: if (StringUtils.contains(rtn, "signout")) { log.info("V2EX{}", usrename); return true; } log.info("V2EX{}", usrename); return false; } private boolean checkIn(Executor executor, Account account) throws ClientProtocolException, IOException, URISyntaxException, InterruptedException { String usrename = account.getUsername(); String rtn = executor.execute(appendTimeOuts(Request.Get(CHECK_IN_URL))).returnContent().asString(); if (StringUtils.contains(rtn, "fa-ok-sign")) { log.info("V2EX{}{}", usrename, getBalance(rtn)); return true; } Elements element = Jsoup.parse(rtn).getElementsByAttributeValueMatching("onclick", "/mission/daily/redeem"); String once = StringUtils.substringBetween(element.attr("onclick"), "'", "'"); if (StringUtils.isNotEmpty(once)) { String url = "http: String checkInRtn = executor.execute(appendTimeOuts(Request.Get(url)).userAgent(USER_AGENT).addHeader("Referer", CHECK_IN_URL)).returnContent().asString(); log.info("V2EX{}{}", usrename, getBalance(checkInRtn)); return true; } log.info("V2EX{}", usrename); return false; } private String getBalance(String rtn) { return Jsoup.parse(rtn).getElementsByClass("balance_area").text(); } }
package opendap.wcs.v2_0; import org.jdom.Document; import org.jdom.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; /** * * This class houses methods that return the wcs:Capabilities response for the service. * * */ public class CapabilitiesRequestProcessor { static Logger log = LoggerFactory.getLogger(CapabilitiesRequestProcessor.class); /** * Queries the CatalogWrapper for all of the components of the wcs:Capablitites response. * and returns the complete wcs:Capabilities document. * * @param serviceUrl The service URL of the WCS service. Used to build the service URLs that appear in the * OperationsMetadata section of the wcs:Capabilities response document. * @return The complete wcs:Capabilities document, suitable for serialization to a requesting client. * @throws WcsException When bad things happen. */ public static Document getFullCapabilitiesDocument(String serviceUrl, String[] cids) throws InterruptedException, WcsException { Element capabilities = new Element("Capabilities", WCS.WCS_NS); String updateSequence = getUpdateSequence(); capabilities.setAttribute("updateSequence", updateSequence); capabilities.addContent(CatalogWrapper.getServiceIdentificationElement()); capabilities.addContent(CatalogWrapper.getServiceProviderElement()); capabilities.addContent(CatalogWrapper.getOperationsMetadataElement(serviceUrl)); capabilities.addContent(ServerCapabilities.getServiceMetadata()); //XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); //log.debug(xmlo.outputString(capabilities)); capabilities.addContent(getContents(true,true,true,GetCapabilitiesRequest.DEFAULT_MAX_CONTENTS_SECTIONS_COUNT,cids)); return new Document(capabilities); } /** * Evaluates the passed GetCapabilitiesRequest object and builds the appropriate wcs:Capabilities document. * by query the CatalogWrapper for all the requestd components of the wcs:Capablitites response. * * * * @param req The client service request as a GetCapabilitiesRequest object * @param serviceUrl The service URL of the WCS service. Used to build the service URLs that appear in the * OperationsMetadata section of the wcs:Capabilities response document. * @return The wcs:Capabilities document with the componets requested by the client. * @throws WcsException When bad things happen. */ public static Document processGetCapabilitiesRequest(GetCapabilitiesRequest req, String serviceUrl) throws InterruptedException, WcsException { Element capabilities = new Element("Capabilities",WCS.WCS_NS); capabilities.addNamespaceDeclaration(WCS.WCS_NS); capabilities.addNamespaceDeclaration(WCS.OWS_NS); capabilities.addNamespaceDeclaration(WCS.XSI_NS); capabilities.addNamespaceDeclaration(WCS.WCSEO_NS); StringBuilder schemaLocation = new StringBuilder(); schemaLocation .append(WCS.OWS_NAMESPACE_STRING).append(" ") .append(WCS.OWS_SCHEMA_LOCATION_BASE).append("owsAll.xsd").append(" ") .append(WCS.WCS_NAMESPACE_STRING).append(" ") .append(WCS.WCS_SCHEMA_LOCATION_BASE).append("wcsAll.xsd") ; capabilities.setAttribute("schemaLocation",schemaLocation.toString(),WCS.XSI_NS); String updateSequence = getUpdateSequence(); capabilities.setAttribute("updateSequence",updateSequence); capabilities.setAttribute("version",WCS.CURRENT_VERSION); Element section; boolean all = false; if(!req.hasSectionsElement()) all = true; // Now the spec (OGC 06-121r3, section 7.3.3) says: "If no names are listed, the service // metadata returned may not contain any of the sections that could be listed." // If thats's the case then it would appear we are to return an empty document. // Basically they are just going to get the updateSequence attribute value. if(req.hasSection(GetCapabilitiesRequest.ALL)) all = true; if(all || req.hasSection(GetCapabilitiesRequest.SERVICE_IDENTIFICATION)){ capabilities.addContent(CatalogWrapper.getServiceIdentificationElement()); } if(all || req.hasSection(GetCapabilitiesRequest.SERVICE_PROVIDER)){ capabilities.addContent(CatalogWrapper.getServiceProviderElement()); } if(all || req.hasSection(GetCapabilitiesRequest.OPERATIONS_METADATA)){ capabilities.addContent(CatalogWrapper.getOperationsMetadataElement(serviceUrl)); } if(all || req.hasSection(GetCapabilitiesRequest.SERVICE_METADATA)){ capabilities.addContent(ServerCapabilities.getServiceMetadata()); } if(all || req.hasSection(GetCapabilitiesRequest.CONTENTS) || req.hasSection(GetCapabilitiesRequest.DATASET_SERIES_SUMMARY) || req.hasSection(GetCapabilitiesRequest.COVERAGE_SUMMARY)){ capabilities.addContent(getContents( all || req.hasSection(GetCapabilitiesRequest.CONTENTS), req.hasSection(GetCapabilitiesRequest.DATASET_SERIES_SUMMARY), req.hasSection(GetCapabilitiesRequest.COVERAGE_SUMMARY), req.getCount(),req.getRequestedCoverageIds())); } return new Document(capabilities); } /** * Returns the wcs:UpdateSequence for the catalog. This is currently taken to be the String representation of the * catalogs last modified time in seconds since 1/1/1970 * @return Returns the wcs:UpdateSequence for the catalog. This is currently taken to be the String representation of the * catalogs last modified time in seconds since 1/1/1970 */ public static String getUpdateSequence(){ return CatalogWrapper.getLastModified()+""; } /** * Returns the wcs:Contents section of the wcs:Capabilities response. * * @return Returns the wcs:Contents section of the wcs:Capabilities response. * @throws WcsException When bad things happen. * @throws InterruptedException */ public static Element getContents(boolean allContent, boolean dataset_series_summary, boolean coverage_summary, long maxContentsSectionsCount, String[] coverageIds) throws InterruptedException, WcsException { Element contentsElement = new Element("Contents",WCS.WCS_NS); long count = 0; if(allContent | coverage_summary){ if(coverageIds!=null && coverageIds.length>0){ log.info("getContents() Building contents from supplied list of coverageIds"); for(String coverageId:coverageIds) { Element coverageSummaryElement = CatalogWrapper.getCoverageSummaryElement(coverageId); log.debug("coverageId: {} coverageSummaryElement: {}",coverageId, coverageSummaryElement); if(coverageSummaryElement!=null){ contentsElement.addContent(coverageSummaryElement); } if( maxContentsSectionsCount < count++) break; } } else { log.info("getContents() Building contents from WcsCatalog API"); Iterator i = CatalogWrapper.getCoverageSummaryElements().iterator(); if (i.hasNext()) { Element cs; while (i.hasNext()) { cs = (Element) i.next(); count++; if (count < maxContentsSectionsCount) contentsElement.addContent(cs); } } } } if(count<maxContentsSectionsCount && (allContent | dataset_series_summary)) { Iterator i = CatalogWrapper.getDatasetSeriesSummaryElements().iterator(); if(i.hasNext()){ Element wcsExtensionElement = new Element("Extension",WCS.WCS_NS); Element dss; while(i.hasNext()){ dss = (Element) i.next(); count++; if(count<maxContentsSectionsCount) wcsExtensionElement.addContent(dss); } contentsElement.addContent(wcsExtensionElement); } } if(contentsElement.getChildren().isEmpty()){ Element os; os = new Element("OtherSource",WCS.WCS_NS); XLink xlink = new XLink(XLink.Type.SIMPLE,"http: os.setAttributes(xlink.getAttributes()); } return contentsElement; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.xtx.ut4converter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.xtx.ut4converter.UTGames.UnrealEngine; import org.xtx.ut4converter.t3d.*; /** * Tells which UT actor classes will be converted * * @author XtremeXp */ public class SupportedClasses { private static final boolean USE_CUSTOM = true; MapConverter mapConverter; /** * If in t3d */ protected HashMap<String, Class<? extends T3DActor>> classToUtActor = new HashMap<>(); /** * Actors that are no longer needed for output game. E.G: PathNodes in * Unreal Engine 4 which no longer exists (using some navigation volume to * border the "navigation area") Useful to avoid some spammy log message and * create notes in editor for unconverted actors info */ protected List<String> uneededActors = new ArrayList<>(); /** * * @param mapConverter */ public SupportedClasses(MapConverter mapConverter) { this.mapConverter = mapConverter; initialize(); } /** * * @param utxclass */ public void addClass(String utxclass) { classToUtActor.put(utxclass.toLowerCase(), null); } /** * * @param classNames * @param utActorClass */ public void putUtClass(Class<? extends T3DActor> utActorClass, String... classNames) { if (classNames == null) { return; } for (String className : classNames) { classToUtActor.put(className.toLowerCase(), utActorClass); } } /** * Tells * * @param utClassName * @return */ public boolean canBeConverted(String utClassName) { return classToUtActor.containsKey(utClassName.toLowerCase()); } /** * Get UT Actor class from t3d class name. Might return null if not special * convert class * * @param utClassName * @return */ public Class<? extends T3DActor> getConvertActorClass(String utClassName) { return classToUtActor.get(utClassName.toLowerCase()); } /** * * @param utClassName * @return */ public boolean noNotifyUnconverted(String utClassName) { return uneededActors.contains(utClassName); } private void addMatches(MapConverter mc) { HashMap<String, T3DMatch.Match> hm = mc.getActorClassMatch(); for (String c : hm.keySet()) { putUtClass(hm.get(c).t3dClass, c); } } /** * For testing purposes only. Converts only one actor so it's easier to * import it in map being converted * * @param actor * @param t3dClass */ public void setConvertOnly(String actor, Class<? extends T3DActor> t3dClass) { classToUtActor.clear(); classToUtActor.put(actor.toLowerCase(), t3dClass); mapConverter.setCreateNoteForUnconvertedActors(false); } /** * TODO split depending on UE12/UE3 input engine */ private void initialize() { // TODO move zones to match with T3DZoneInfo.class putUtClass(T3DBrush.class, "Brush", "LavaZone", "WaterZone", "SlimeZone", "NitrogenZone", "PressureZone", "VacuumZone", "BlockAll"); putUtClass(mapConverter.isFrom(UnrealEngine.UE1) ? T3DMover.class : T3DMoverSM.class, "Mover", "AttachMover", "AssertMover", "RotatingMover", "ElevatorMover", "MixMover", "GradualMover", "LoopMover", "InterpActor"); //putUtClass() putUtClass(T3DPlayerStart.class, "PlayerStart", "UTTeamPlayerStart", "UTWarfarePlayerStart"); putUtClass(T3DStaticMesh.class, "StaticMeshActor"); putUtClass(T3DTrigger.class, "Trigger", "TeamTrigger", "ZoneTrigger", "TimedTrigger", "Trigger_ASTeam"); for (T3DBrush.BrushClass brushClass : T3DBrush.BrushClass.values()) { // mover is special case because is dependant of staticmesh for UE2 // not brush (UE1) if (brushClass != T3DBrush.BrushClass.Mover) { putUtClass(T3DBrush.class, brushClass.name()); } } if (mapConverter.isFrom(UnrealEngine.UE1, UnrealEngine.UE2)) { for (T3DLight.UE12_LightActors ut99LightActor : T3DLight.UE12_LightActors.values()) { putUtClass(T3DLight.class, ut99LightActor.name()); } } else if (mapConverter.isFrom(UnrealEngine.UE3)) { putUtClass(T3DNote.class, "Note"); for (T3DSound.UE3_AmbientSoundActor ue3SoundActor : T3DSound.UE3_AmbientSoundActor.values()) { putUtClass(T3DSound.class, ue3SoundActor.name()); } for (T3DLight.UE3_LightActor ue4LightActor : T3DLight.UE3_LightActor.values()) { putUtClass(T3DLight.class, ue4LightActor.name()); } } putUtClass(T3DLevelInfo.class, "LevelInfo"); if (mapConverter.isTo(UTGames.UnrealEngine.UE3, UTGames.UnrealEngine.UE4)) { // disabled until working good putUtClass(T3DZoneInfo.class, "ZoneInfo"); } // terrain conversion disabled until working good if (mapConverter.isFrom(UTGames.UnrealEngine.UE2)) { putUtClass(T3DUE2Terrain.class, "TerrainInfo"); } for (T3DLight.UE4_LightActor ue34LightActor : T3DLight.UE4_LightActor.values()) { putUtClass(T3DLight.class, ue34LightActor.name()); } // UT99 Assault putUtClass(T3DASObjective.class, "FortStandard"); putUtClass(T3DASCinematicCamera.class, "SpectatorCam"); putUtClass(T3DASInfo.class, "AssaultInfo"); // UT2004, UT99 Dom putUtClass(DomPoint.class, "xDomPointA", "xDomPointB", "ControlPoint"); // UT3 putUtClass(DecalActor.class, "DecalActor"); putUtClass(HeightFog.class, "HeightFog"); putUtClass(T3DTeleporter.class, "Teleporter", "FavoritesTeleporter", "VisibleTeleporter", "UTTeleporter", "UTTeleporterCustomMesh"); putUtClass(T3DSound.class, "AmbientSound", "DynamicAmbientSound", "AmbientSoundSimple"); putUtClass(T3DLiftExit.class, "LiftExit", "UTJumpLiftExit"); putUtClass(T3DJumpPad.class, "Kicker", "Jumper", "BaseJumpPad_C", "U2Kicker", "U2KickReflector", "xKicker", "UTJumppad"); addMatches(mapConverter); uneededActors.add("PathNode"); uneededActors.add("InventorySpot"); uneededActors.add("TranslocDest"); uneededActors.add("AntiPortalActor"); // ut2004 uneededActors.add("Adrenaline"); // ut2004 uneededActors.add("ReachSpec"); // ut2004 uneededActors.add("ModelComponent"); // ut3 uneededActors.add("ForcedReachSpec"); // ut3 uneededActors.add("AdvancedReachSpec"); // ut3 if (USE_CUSTOM) { putUtClass(SpecialEvent.class, "SpecialEvent"); } } /** * Restrict convertible ut classes to the ones specified. Allows to convert * some specific actors (e.g: lights, playerstarts, ...) * * @param className * List of actor classes (e.g: * ['Brush','Light','PlayerStart',...]); */ public void setConvertOnly(String[] className) { if (mapConverter.getFilteredClasses() == null || mapConverter.getFilteredClasses().length == 0) { return; } HashMap<String, Class<? extends T3DActor>> classToUtActorNew = new HashMap<>(); mapConverter.setCreateNoteForUnconvertedActors(false); for (String classFilter : className) { if (classToUtActor.containsKey((classFilter.toLowerCase()))) { classToUtActorNew.put(classFilter.toLowerCase(), classToUtActor.get(classFilter.toLowerCase())); } } classToUtActor = classToUtActorNew; } }
package ru.ifmo.ctddev.gmwcs.solver; import ilog.concert.IloException; import ilog.concert.IloNumExpr; import ilog.concert.IloNumVar; import ilog.cplex.IloCplex; import ru.ifmo.ctddev.gmwcs.Pair; import ru.ifmo.ctddev.gmwcs.Signals; import ru.ifmo.ctddev.gmwcs.TimeLimit; import ru.ifmo.ctddev.gmwcs.graph.*; import java.util.*; public class RLTSolver implements RootedSolver { private static final double EPS = 0.01; private IloCplex cplex; private Map<Node, IloNumVar> y; private Map<Edge, IloNumVar> w; private Map<Edge, Pair<IloNumVar, IloNumVar>> x; private Map<Node, IloNumVar> d; private Map<Node, IloNumVar> x0; private TimeLimit tl; private int threads; private int logLevel; private Graph graph; private Node root; private boolean isSolvedToOptimality; private int maxToAddCuts; private int considerCuts; private AtomicDouble lb; private double externLB; private boolean isLBShared; private IloNumVar sum; private double edgePenalty; public RLTSolver() { tl = new TimeLimit(Double.POSITIVE_INFINITY); threads = 1; externLB = 0.0; maxToAddCuts = considerCuts = Integer.MAX_VALUE; edgePenalty = 0; } public void setMaxToAddCuts(int num) { maxToAddCuts = num; } public void setConsideringCuts(int num) { considerCuts = num; } @Override public TimeLimit getTimeLimit() { return tl; } public void setTimeLimit(TimeLimit tl) { this.tl = tl; } public void setThreadsNum(int threads) { if (threads < 1) { throw new IllegalArgumentException(); } this.threads = threads; } public void setEdgePenalty(double edgePenalty) { this.edgePenalty = edgePenalty; } public void setRoot(Node root) { this.root = root; } @Override public List<Unit> solve(Graph graph, Signals synonyms) throws SolverException { try { isSolvedToOptimality = false; if(!isLBShared){ lb = new AtomicDouble(externLB); } cplex = new IloCplex(); this.graph = graph; initVariables(); addConstraints(); addObjective(synonyms); if (edgePenalty <= 0) { maxSizeConstraints(); } if (root == null) { breakRootSymmetry(); } else { tighten(); } breakTreeSymmetries(); tuning(cplex); boolean solFound = cplex.solve(); if (cplex.getCplexStatus() != IloCplex.CplexStatus.AbortTimeLim) { isSolvedToOptimality = true; } if (solFound) { return getResult(); } return Collections.emptyList(); } catch (IloException e) { throw new SolverException(e.getMessage()); } finally { cplex.end(); } } private void breakTreeSymmetries() throws IloException { int n = graph.vertexSet().size(); for (Edge e : graph.edgeSet()) { Node from = graph.getEdgeSource(e); Node to = graph.getEdgeTarget(e); cplex.addLe(cplex.sum(d.get(from), cplex.prod(n - 1, w.get(e))), cplex.sum(n, d.get(to))); cplex.addLe(cplex.sum(d.get(to), cplex.prod(n - 1, w.get(e))), cplex.sum(n, d.get(from))); } } private void tighten() throws IloException { Blocks blocks = new Blocks(graph); if (!blocks.cutpoints().contains(root)) { throw new IllegalArgumentException(); } Separator separator = new Separator(y, w, cplex, graph, sum, lb); separator.setMaxToAdd(maxToAddCuts); separator.setMinToConsider(considerCuts); for (Set<Node> component : blocks.incidentBlocks(root)) { dfs(root, component, true, blocks, separator); } cplex.use(separator); } private void dfs(Node root, Set<Node> component, boolean fake, Blocks bs, Separator separator) throws IloException { separator.addComponent(graph.subgraph(component), root); if (!fake) { for (Node node : component) { cplex.addLe(cplex.diff(y.get(node), y.get(root)), 0); } } for (Edge e : graph.edgesOf(root)) { if (!component.contains(graph.getOppositeVertex(root, e))) { continue; } cplex.addEq(getX(e, root), 0); } for (Node cp : bs.cutpointsOf(component)) { if (root != cp) { for (Set<Node> comp : bs.incidentBlocks(cp)) { if (comp != component) { dfs(cp, comp, false, bs, separator); } } } } } public boolean isSolvedToOptimality() { return isSolvedToOptimality; } private List<Unit> getResult() throws IloException { List<Unit> result = new ArrayList<>(); for (Node node : graph.vertexSet()) { if (cplex.getValue(y.get(node)) > EPS) { result.add(node); } } for (Edge edge : graph.edgeSet()) { if (cplex.getValue(w.get(edge)) > EPS) { result.add(edge); } } return result; } private void initVariables() throws IloException { y = new LinkedHashMap<>(); w = new LinkedHashMap<>(); d = new LinkedHashMap<>(); x = new LinkedHashMap<>(); x0 = new LinkedHashMap<>(); for (Node node : graph.vertexSet()) { String nodeName = Integer.toString(node.getNum() + 1); d.put(node, cplex.numVar(0, Double.MAX_VALUE, "d" + nodeName)); y.put(node, cplex.boolVar("y" + nodeName)); x0.put(node, cplex.boolVar("x_0_" + (node.getNum() + 1))); } for (Edge edge : graph.edgeSet()) { Node from = graph.getEdgeSource(edge); Node to = graph.getEdgeTarget(edge); String edgeName = (from.getNum() + 1) + "_" + (to.getNum() + 1); w.put(edge, cplex.boolVar("w_" + edgeName)); IloNumVar in = cplex.boolVar("x_" + edgeName + "_in"); IloNumVar out = cplex.boolVar("x_" + edgeName + "_out"); x.put(edge, new Pair<>(in, out)); } } private void tuning(IloCplex cplex) throws IloException { if (logLevel < 2) { cplex.setOut(null); cplex.setWarning(null); } if (isLBShared) { cplex.use(new MIPCallback(logLevel == 0)); } cplex.setParam(IloCplex.IntParam.Threads, threads); cplex.setParam(IloCplex.IntParam.ParallelMode, -1); cplex.setParam(IloCplex.IntParam.MIPOrdType, 3); if (tl.getRemainingTime() <= 0) { cplex.setParam(IloCplex.DoubleParam.TiLim, EPS); } else if (tl.getRemainingTime() != Double.POSITIVE_INFINITY) { cplex.setParam(IloCplex.DoubleParam.TiLim, tl.getRemainingTime()); } } private void breakRootSymmetry() throws IloException { int n = graph.vertexSet().size(); PriorityQueue<Node> nodes = new PriorityQueue<>(); nodes.addAll(graph.vertexSet()); int k = n; IloNumExpr[] terms = new IloNumExpr[n]; IloNumExpr[] rs = new IloNumExpr[n]; while (!nodes.isEmpty()) { Node node = nodes.poll(); terms[k - 1] = cplex.prod(k, x0.get(node)); rs[k - 1] = cplex.prod(k, y.get(node)); k } IloNumVar sum = cplex.numVar(0, n, "prSum"); cplex.addEq(sum, cplex.sum(terms)); for (int i = 0; i < n; i++) { cplex.addGe(sum, rs[i]); } } private void addObjective(Signals synonyms) throws IloException { List<Double> ks = new ArrayList<>(); List<IloNumVar> vs = new ArrayList<>(); for (int i = 0; i < synonyms.size(); i++) { double weight = synonyms.weight(i); List<Unit> set = synonyms.set(i); if (set.size() == 0 || weight == 0.0) { continue; } ks.add(synonyms.weight(i)); if (set.size() == 1) { vs.add(getVar(set.get(0))); continue; } IloNumVar x = cplex.boolVar("s" + i); vs.add(x); IloNumExpr[] vars = set.stream().map(this::getVar).toArray(IloNumExpr[]::new); if (weight > 0) { cplex.addLe(x, cplex.sum(vars)); } else { cplex.addGe(cplex.prod(vars.length, x), cplex.sum(vars)); } } if (edgePenalty > 0) { IloNumVar numEdges = cplex.numVar(0, Double.MAX_VALUE); IloNumExpr edgesSum = cplex.sum(w.values().toArray(new IloNumVar[0])); ks.add(-edgePenalty); vs.add(numEdges); cplex.addEq(numEdges, edgesSum); } IloNumExpr sum = cplex.scalProd(ks.stream().mapToDouble(d -> d).toArray(), vs.toArray(new IloNumVar[vs.size()])); this.sum = cplex.numVar(-Double.MAX_VALUE, Double.MAX_VALUE); cplex.addGe(sum, lb.get()); cplex.addEq(this.sum, sum); cplex.addMaximize(sum); } private IloNumVar getVar(Unit unit) { return unit instanceof Node ? y.get(unit) : w.get(unit); } @Override public void setLogLevel(int logLevel) { this.logLevel = logLevel; } private void addConstraints() throws IloException { sumConstraints(); otherConstraints(); distanceConstraints(); } private void distanceConstraints() throws IloException { int n = graph.vertexSet().size(); for (Node v : graph.vertexSet()) { cplex.addLe(d.get(v), cplex.diff(n, cplex.prod(n, x0.get(v)))); } for (Edge e : graph.edgeSet()) { Node from = graph.getEdgeSource(e); Node to = graph.getEdgeTarget(e); addEdgeConstraints(e, from, to); addEdgeConstraints(e, to, from); } } private void addEdgeConstraints(Edge e, Node from, Node to) throws IloException { int n = graph.vertexSet().size(); IloNumVar z = getX(e, to); cplex.addGe(cplex.sum(n, d.get(to)), cplex.sum(d.get(from), cplex.prod(n + 1, z))); cplex.addLe(cplex.sum(d.get(to), cplex.prod(n - 1, z)), cplex.sum(d.get(from), n)); } private void maxSizeConstraints() throws IloException { for (Node v : graph.vertexSet()) { for (Node u : graph.neighborListOf(v)) { if (u.getWeight() >= 0) { Edge e = graph.getEdge(v, u); if (e != null && e.getWeight() >= 0) { cplex.addLe(y.get(v), w.get(e)); } } } } } private void otherConstraints() throws IloException { // (36), (39) for (Edge edge : graph.edgeSet()) { Pair<IloNumVar, IloNumVar> arcs = x.get(edge); Node from = graph.getEdgeSource(edge); Node to = graph.getEdgeTarget(edge); cplex.addLe(cplex.sum(arcs.first, arcs.second), w.get(edge)); cplex.addLe(w.get(edge), y.get(from)); cplex.addLe(w.get(edge), y.get(to)); } } private void sumConstraints() throws IloException { cplex.addLe(cplex.sum(graph.vertexSet().stream().map(x -> x0.get(x)).toArray(IloNumVar[]::new)), 1); if (root != null) { cplex.addEq(x0.get(root), 1); } for (Node node : graph.vertexSet()) { Set<Edge> edges = graph.edgesOf(node); IloNumVar xSum[] = new IloNumVar[edges.size() + 1]; int i = 0; for (Edge edge : edges) { xSum[i++] = getX(edge, node); } xSum[xSum.length - 1] = x0.get(node); cplex.addEq(cplex.sum(xSum), y.get(node)); } } private IloNumVar getX(Edge e, Node to) { if (graph.getEdgeSource(e) == to) { return x.get(e).first; } else { return x.get(e).second; } } public void setLB(double lb) { this.externLB = lb; } public void setSharedLB(AtomicDouble lb){ isLBShared = true; this.lb = lb; } private class MIPCallback extends IloCplex.IncumbentCallback { private boolean silence; public MIPCallback(boolean silence) { this.silence = silence; } @Override protected void main() throws IloException { while(true){ double currLB = lb.get(); if(currLB >= getObjValue()){ break; } if (lb.compareAndSet(currLB, getObjValue()) && !silence) { System.out.println("Found new solution: " + getObjValue()); } } } } }
package seedu.Tdoo.logic.commands; import seedu.Tdoo.commons.core.Messages; import seedu.Tdoo.commons.core.UnmodifiableObservableList; import seedu.Tdoo.model.task.ReadOnlyTask; import seedu.Tdoo.model.task.UniqueTaskList.TaskNotFoundException; /** * Selects a task identified using it's last displayed index from the TodoList. */ public class DoneCommand extends Command { public static final String COMMAND_WORD = "done"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Mark a Todo-task with given index number as done.\n" + "Parameters: TASK_TYPE INDEX_NUMBER(must be a positive integer)\n" + "Example: " + COMMAND_WORD + " todo 1\n" + "Example: " + COMMAND_WORD + " event 1\n" + "Example: " + COMMAND_WORD + " deadline 1"; public static final String MESSAGE_DONE_TASK_SUCCESS = "Completed task: %1$s"; public final String dataType; public final int targetIndex; //@@author A0139920A public DoneCommand(String dataType, int targetIndex) { this.dataType = dataType; this.targetIndex = targetIndex; } //@@author A0139920A @Override public CommandResult execute() { UnmodifiableObservableList<ReadOnlyTask> lastShownList = null; switch (dataType) { case "todo": lastShownList = model.getFilteredTodoList(); break; case "event": lastShownList = model.getFilteredEventList(); break; case "deadline": lastShownList = model.getFilteredDeadlineList(); break; } if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask taskToDone = lastShownList.get(targetIndex - 1); try { model.doneTask(taskToDone, dataType, targetIndex); } catch (TaskNotFoundException pnfe) { assert false : "The target task cannot be missing"; } return new CommandResult(String.format(MESSAGE_DONE_TASK_SUCCESS, taskToDone)); } }
package dr.app.beauti.tipdatepanel; import dr.app.beauti.BeautiFrame; import dr.app.beauti.BeautiPanel; import dr.app.beauti.components.TipDateSamplingComponentOptions; import dr.app.beauti.components.TipDateSamplingType; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.DateGuesser; import dr.app.beauti.util.PanelUtils; import dr.evolution.util.*; import dr.gui.table.DateCellEditor; import dr.gui.table.TableSorter; import org.virion.jam.framework.Exportable; import org.virion.jam.table.HeaderRenderer; import org.virion.jam.table.TableEditorStopper; import org.virion.jam.table.TableRenderer; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.BorderUIResource; import javax.swing.table.AbstractTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $ */ public class TipDatesPanel extends BeautiPanel implements Exportable { private static final long serialVersionUID = 5283922195494563924L; JScrollPane scrollPane = new JScrollPane(); JTable dataTable = null; DataTableModel dataTableModel = null; ClearDatesAction clearDatesAction = new ClearDatesAction(); GuessDatesAction guessDatesAction = new GuessDatesAction(); JCheckBox usingTipDates = new JCheckBox("Use tip dates"); JComboBox unitsCombo = new JComboBox(new String[]{"Years", "Months", "Days"}); JComboBox directionCombo = new JComboBox(new String[]{"Since some time in the past", "Before the present"}); JComboBox tipDateSamplingCombo = new JComboBox(TipDateSamplingType.values()); JComboBox tipDateTaxonSetCombo = new JComboBox(); BeautiFrame frame = null; BeautiOptions options = null; double[] heights = null; GuessDatesDialog guessDatesDialog = null; public TipDatesPanel(BeautiFrame parent) { this.frame = parent; dataTableModel = new DataTableModel(); TableSorter sorter = new TableSorter(dataTableModel); dataTable = new JTable(sorter); sorter.setTableHeader(dataTable.getTableHeader()); dataTable.getTableHeader().setReorderingAllowed(false); dataTable.getTableHeader().setDefaultRenderer( new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setCellRenderer( new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(0).setPreferredWidth(80); dataTable.getColumnModel().getColumn(1).setCellRenderer( new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(1).setPreferredWidth(80); dataTable.getColumnModel().getColumn(1).setCellEditor( new DateCellEditor()); dataTable.getColumnModel().getColumn(2).setCellRenderer( new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4))); dataTable.getColumnModel().getColumn(2).setPreferredWidth(80); TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable); dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { selectionChanged(); } }); scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setOpaque(false); PanelUtils.setupComponent(unitsCombo); PanelUtils.setupComponent(directionCombo); JToolBar toolBar1 = new JToolBar(); toolBar1.setFloatable(false); toolBar1.setOpaque(false); toolBar1.setLayout(new FlowLayout(java.awt.FlowLayout.LEFT, 0, 0)); JButton button = new JButton(guessDatesAction); PanelUtils.setupComponent(button); toolBar1.add(button); button = new JButton(clearDatesAction); PanelUtils.setupComponent(button); toolBar1.add(button); toolBar1.add(new JToolBar.Separator(new Dimension(12, 12))); final JLabel unitsLabel = new JLabel("Dates specified as "); toolBar1.add(unitsLabel); toolBar1.add(unitsCombo); toolBar1.add(directionCombo); JPanel panel1 = new JPanel(new BorderLayout(0, 0)); panel1.setOpaque(false); panel1.add(toolBar1, "North"); panel1.add(scrollPane, "Center"); JToolBar toolBar2 = new JToolBar(); toolBar2.setFloatable(false); toolBar2.setOpaque(false); toolBar2.setLayout(new FlowLayout(java.awt.FlowLayout.LEFT, 0, 0)); PanelUtils.setupComponent(tipDateSamplingCombo); tipDateSamplingCombo.setToolTipText("<html>Select whether to allow sampling<br>" + "of all or individual tip dates.</html>"); // substitutionRateField.setToolTipText("<html>Enter the substitution rate here.</html>"); // substitutionRateField.setEnabled(true); final JLabel tipDateSamplingLabel = new JLabel("Tip date sampling:"); toolBar2.add(tipDateSamplingLabel); toolBar2.add(tipDateSamplingCombo); final JLabel tipDateTaxonSetLabel = new JLabel("Apply to taxon set:"); toolBar2.add(tipDateTaxonSetLabel); toolBar2.add(tipDateTaxonSetCombo); setOpaque(false); setBorder(new BorderUIResource.EmptyBorderUIResource(new java.awt.Insets(12, 12, 12, 12))); setLayout(new BorderLayout(0, 0)); add(usingTipDates, BorderLayout.NORTH); add(panel1, BorderLayout.CENTER); add(toolBar2, BorderLayout.SOUTH); tipDateSamplingCombo.addItemListener( new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent ev) { boolean samplingOn = tipDateSamplingCombo.getSelectedItem() != TipDateSamplingType.NO_SAMPLING; tipDateTaxonSetLabel.setEnabled(samplingOn); tipDateTaxonSetCombo.setEnabled(samplingOn); fireModelsChanged(); } } ); clearDatesAction.setEnabled(false); guessDatesAction.setEnabled(false); directionCombo.setEnabled(false); unitsLabel.setEnabled(false); unitsCombo.setEnabled(false); scrollPane.setEnabled(false); dataTable.setEnabled(false); tipDateSamplingLabel.setEnabled(false); tipDateSamplingCombo.setEnabled(false); tipDateTaxonSetLabel.setEnabled(false); tipDateTaxonSetCombo.setEnabled(false); usingTipDates.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { boolean enabled = usingTipDates.isSelected(); clearDatesAction.setEnabled(enabled); guessDatesAction.setEnabled(enabled); unitsLabel.setEnabled(enabled); unitsCombo.setEnabled(enabled); directionCombo.setEnabled(enabled); scrollPane.setEnabled(enabled); dataTable.setEnabled(enabled); tipDateSamplingCombo.setEnabled(enabled); tipDateSamplingLabel.setEnabled(enabled); frame.removeSpecifiedTreePrior(enabled); options.fixedSubstitutionRate = !enabled; } }); ItemListener listener = new ItemListener() { public void itemStateChanged(ItemEvent ev) { timeScaleChanged(); } }; unitsCombo.addItemListener(listener); directionCombo.addItemListener(listener); } public final void timeScaleChanged() { Units.Type units = Units.Type.YEARS; switch (unitsCombo.getSelectedIndex()) { case 0: units = Units.Type.YEARS; break; case 1: units = Units.Type.MONTHS; break; case 2: units = Units.Type.DAYS; break; } boolean backwards = directionCombo.getSelectedIndex() == 1; for (int i = 0; i < options.taxonList.getTaxonCount(); i++) { Date date = options.taxonList.getTaxon(i).getDate(); double d = date.getTimeValue(); Date newDate = createDate(d, units, backwards, 0.0); options.taxonList.getTaxon(i).setDate(newDate); } calculateHeights(); dataTableModel.fireTableDataChanged(); frame.setDirty(); } private Date createDate(double timeValue, Units.Type units, boolean backwards, double origin) { if (backwards) { return Date.createTimeAgoFromOrigin(timeValue, units, origin); } else { return Date.createTimeSinceOrigin(timeValue, units, origin); } } public void setOptions(BeautiOptions options) { this.options = options; setupTable(); unitsCombo.setSelectedIndex(options.datesUnits); directionCombo.setSelectedIndex(options.datesDirection); calculateHeights(); dataTableModel.fireTableDataChanged(); tipDateTaxonSetCombo.removeAllItems(); tipDateTaxonSetCombo.addItem("All taxa"); for (TaxonList taxa : options.taxonSets) { tipDateTaxonSetCombo.addItem(taxa); } } private void setupTable() { dataTableModel.fireTableDataChanged(); } public void getOptions(BeautiOptions options) { options.datesUnits = unitsCombo.getSelectedIndex(); options.datesDirection = directionCombo.getSelectedIndex(); TipDateSamplingComponentOptions comp = (TipDateSamplingComponentOptions) options.getComponentOptions(TipDateSamplingComponentOptions.class); comp.tipDateSamplingType = (TipDateSamplingType) tipDateSamplingCombo.getSelectedItem(); if (tipDateTaxonSetCombo.getSelectedItem() instanceof TaxonList) { comp.tipDateSamplingTaxonSet = (TaxonList) tipDateTaxonSetCombo.getSelectedItem(); } else { comp.tipDateSamplingTaxonSet = null; } } private void fireModelsChanged() { frame.setDirty(); } public JComponent getExportableComponent() { return dataTable; } public void selectionChanged() { // nothing to do } public void clearDates() { for (int i = 0; i < options.taxonList.getTaxonCount(); i++) { java.util.Date origin = new java.util.Date(0); double d = 0.0; Date date = Date.createTimeSinceOrigin(d, Units.Type.YEARS, origin); options.taxonList.getTaxon(i).setAttribute("date", date); } // adjust the dates to the current timescale... timeScaleChanged(); dataTableModel.fireTableDataChanged(); } public void guessDates() { if (guessDatesDialog == null) { guessDatesDialog = new GuessDatesDialog(frame); } int result = guessDatesDialog.showDialog(); if (result == -1 || result == JOptionPane.CANCEL_OPTION) { return; } DateGuesser guesser = options.dateGuesser; guesser.guessDates = true; guessDatesDialog.setupGuesser(guesser); String warningMessage = null; guesser.guessDates(options.taxonList); if (warningMessage != null) { JOptionPane.showMessageDialog(this, "Warning: some dates may not be set correctly - \n" + warningMessage, "Error guessing dates", JOptionPane.WARNING_MESSAGE); } // adjust the dates to the current timescale... timeScaleChanged(); dataTableModel.fireTableDataChanged(); } public class ClearDatesAction extends AbstractAction { private static final long serialVersionUID = -7281309694753868635L; public ClearDatesAction() { super("Clear Dates"); setToolTipText("Use this tool to remove sampling dates from each taxon"); } public void actionPerformed(ActionEvent ae) { clearDates(); } } public class GuessDatesAction extends AbstractAction { private static final long serialVersionUID = 8514706149822252033L; public GuessDatesAction() { super("Guess Dates"); setToolTipText("Use this tool to guess the sampling dates from the taxon labels"); } public void actionPerformed(ActionEvent ae) { guessDates(); } } private void calculateHeights() { options.maximumTipHeight = 0.0; if (options.taxonList == null || options.taxonList.getTaxonCount() == 0) return; heights = null; dr.evolution.util.Date mostRecent = null; for (int i = 0; i < options.taxonList.getTaxonCount(); i++) { Date date = options.taxonList.getTaxon(i).getDate(); if ((date != null) && (mostRecent == null || date.after(mostRecent))) { mostRecent = date; } } if (mostRecent != null) { heights = new double[options.taxonList.getTaxonCount()]; TimeScale timeScale = new TimeScale(mostRecent.getUnits(), true, mostRecent.getAbsoluteTimeValue()); double time0 = timeScale.convertTime(mostRecent.getTimeValue(), mostRecent); for (int i = 0; i < options.taxonList.getTaxonCount(); i++) { Taxon taxon = options.taxonList.getTaxon(i); Date date = taxon.getDate(); if (date != null) { heights[i] = timeScale.convertTime(date.getTimeValue(), date) - time0; taxon.setAttribute("height", heights[i]); if (heights[i] > options.maximumTipHeight) options.maximumTipHeight = heights[i]; } } } } class DataTableModel extends AbstractTableModel { private static final long serialVersionUID = -6707994233020715574L; String[] columnNames = {"Name", "Date", "Height"}; public DataTableModel() { } public int getColumnCount() { return columnNames.length; } public int getRowCount() { if (options == null) return 0; if (options.taxonList == null) return 0; return options.taxonList.getTaxonCount(); } public Object getValueAt(int row, int col) { switch (col) { case 0: return options.taxonList.getTaxonId(row); case 1: Date date = options.taxonList.getTaxon(row).getDate(); if (date != null) { return date.getTimeValue(); } else { return "-"; } case 2: if (heights != null) { return heights[row]; } else { return "0.0"; } } return null; } public void setValueAt(Object aValue, int row, int col) { if (col == 0) { options.taxonList.getTaxon(row).setId(aValue.toString()); } else if (col == 1) { Date date = options.taxonList.getTaxon(row).getDate(); if (date != null) { double d = (Double) aValue; Date newDate = createDate(d, date.getUnits(), date.isBackwards(), date.getOrigin()); options.taxonList.getTaxon(row).setDate(newDate); } } timeScaleChanged(); } public boolean isCellEditable(int row, int col) { if (col == 0) return false; if (col == 1) { Date date = options.taxonList.getTaxon(row).getDate(); return (date != null); } return false; } public String getColumnName(int column) { return columnNames[column]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getColumnName(0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getColumnName(j)); } buffer.append("\n"); for (int i = 0; i < getRowCount(); i++) { buffer.append(getValueAt(i, 0)); for (int j = 1; j < getColumnCount(); j++) { buffer.append("\t"); buffer.append(getValueAt(i, j)); } buffer.append("\n"); } return buffer.toString(); } } }
package seedu.tasklist.logic.parser; import java.util.regex.Pattern; import seedu.tasklist.logic.parser.ArgumentTokenizer.Prefix; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Prefix definitions */ public static final Prefix PREFIX_DATE = new Prefix("d/"); public static final Prefix PREFIX_COMMENT = new Prefix("c/"); public static final Prefix PREFIX_PRIORITY = new Prefix("p/"); public static final Prefix PREFIX_TAG = new Prefix("t/"); public static final Prefix PREFIX_NAME = new Prefix("n/"); public static final Prefix PREFIX_STARTDATE = new Prefix("sd/"); public static final Prefix PREFIX_ENDDATE = new Prefix("ed/"); /* Patterns definitions */ public static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace }
package dr.app.gui.chart; import dr.math.distributions.GammaKDEDistribution; import dr.math.distributions.KernelDensityEstimatorDistribution; import dr.math.distributions.NormalKDEDistribution; import dr.stats.Variate; import dr.util.FrequencyDistribution; import java.util.List; import static dr.math.distributions.TransformedNormalKDEDistribution.getLogTransformedNormalKDEDistribution; /** * @author Marc A. Suchard */ public class KDENumericalDensityPlot extends NumericalDensityPlot { private final static boolean DEBUG = false; protected static final int DEFAULT_KDE_BINS = 5000; public KDENumericalDensityPlot(List<Double> data) { super(data, DEFAULT_KDE_BINS); } public KDENumericalDensityPlot(List<Double> data, int minimumBinCount) { super(data, minimumBinCount); } private KernelDensityEstimatorDistribution getKDE(Double[] samples) { // System.err.println("samples is null? " + (samples == null ? "yes" : "no")); // System.err.println("type is null? " + (type == null ? "yes" : "no")); type = KernelDensityEstimatorDistribution.Type.GAUSSIAN; switch (type) { case GAUSSIAN: return new NormalKDEDistribution(samples); case GAMMA: return new GammaKDEDistribution(samples); case LOG_TRANSFORMED_GAUSSIAN: return getLogTransformedNormalKDEDistribution(samples); default: throw new RuntimeException("Unknown type"); } } /** * Set data */ public void setData(Variate.D data, int minimumBinCount) { setRawData(data); Double[] samples = new Double[data.getCount()]; for (int i = 0; i < data.getCount(); i++) { samples[i] = data.get(i); } kde = getKDE(samples); FrequencyDistribution frequency = getFrequencyDistribution(data, minimumBinCount); Variate.D xData = new Variate.D(); Variate.D yData = new Variate.D(); // double x = frequency.getLowerBound() - frequency.getBinSize(); // double maxDensity = 0.0; // // TODO Compute KDE once //// for (int i = 0; i < frequency.getBinCount(); i++) { //// double density = frequency.getFrequency(i) / frequency.getBinSize() / data.getValuesSize(); //// if (density > maxDensity) maxDensity = density; // xData.add(x + (frequency.getBinSize() / 2.0)); // yData.add(0.0); // x += frequency.getBinSize(); // for (int i = 0; i < frequency.getBinCount(); i++) { // double xPoint = x + (frequency.getBinSize() / 2.0); // xData.add(xPoint); //// double density = frequency.getFrequency(i) / frequency.getBinSize() / data.getValuesSize(); // double density = kde.pdf(xPoint); // if (relativeDensity) { // yData.add(density / maxDensity); // } else { // yData.add(density); // x += frequency.getBinSize(); // xData.add(x + (frequency.getBinSize() / 2.0)); // yData.add(0.0); double x = frequency.getLowerBound() - (frequency.getBinSize() / 2.0); int extraEdgeCount = 0; while (kde.pdf(x) > minDensity && x > lowerBoundary) { x -= frequency.getBinSize(); extraEdgeCount += 1; } // take the raw X min double rawXMin = Double.parseDouble(raw.getMin().toString()); // here sometime final x < lowerBoundary from above loop // rawXMin >= lowerBoundary to ignore the negative X, e.g. likelihoods if (rawXMin >= lowerBoundary && x < lowerBoundary) xData.add(lowerBoundary); // set min x to lowerBoundary else xData.add(x); yData.add(0.0); x += frequency.getBinSize(); int count = 0; while (count < (frequency.getBinCount() + extraEdgeCount)) { // (kde.pdf(x) > minDensity && x < upperBoundary)) { xData.add(x); yData.add(kde.pdf(x)); x += frequency.getBinSize(); count++; } if (DEBUG) { System.err.println("kde = " + kde.pdf(x)); } while (kde.pdf(x) > minDensity ) { if (DEBUG) { System.err.println("add bit on end!!!"); } xData.add(x); yData.add(kde.pdf(x)); x += frequency.getBinSize(); } xData.add(x); yData.add(0.0); // int extraBinsOnEdges = 5; // double x = frequency.getLowerBound() - extraBinsOnEdges * frequency.getBinSize(); // for (int i = 0; i < frequency.getBinCount() + 2 * extraBinsOnEdges; i++) { // double xMidPoint = x + (frequency.getBinSize() / 2.0); // xData.add(xMidPoint); // yData.add(kde.pdf(xMidPoint)); // x += frequency.getBinSize(); setData(xData, yData); } protected Variate getXCoordinates(int numPoints) { Double[] points = new Double[numPoints]; for (int i = 0; i < numPoints; i++) { points[i] = (double) i; } return new Variate.D(points); } protected Variate getYCoordinates(Variate.D xData) { final int length = xData.getCount(); Double[] points = new Double[length]; for (int i = 0; i < length; i++) { points[i] = kde.pdf(xData.get(i)); } return new Variate.D(points); } protected double getQuantile(double y) { return kde.quantile(y); } protected double getDensity(double x) { return kde.pdf(x); } private KernelDensityEstimatorDistribution kde; private NumericalDensityPlot densityPlot; private KernelDensityEstimatorDistribution.Type type; private double lowerBoundary = 0; private double upperBoundary = Double.POSITIVE_INFINITY; private static final double minDensity = 10E-6; // @Override // protected void paintData(Graphics2D g2, Variate xData, Variate yData) { // double x = transformX(xData.get(0)); // double y = transformY(yData.get(0)); // GeneralPath path = new GeneralPath(); // path.moveTo((float) x, (float) y); // int n = xData.getValuesSize(); // boolean failed = false; // for (int i = 1; i < n; i++) { // x = transformX(xData.get(i)); // y = transformY(yData.get(i)); // if (x == Double.NEGATIVE_INFINITY || y == Double.NEGATIVE_INFINITY || // Double.isNaN(x) || Double.isNaN(y)) { // failed = true; // } else if (failed) { // failed = false; // path.moveTo((float) x, (float) y); // } else { // path.lineTo((float) x, (float) y); // g2.setPaint(linePaint); // g2.setStroke(lineStroke); // g2.draw(path); }
package seedu.todo.controllers; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import edu.emory.mathcs.backport.java.util.Arrays; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * Controller to find task/event by keyword * * @@author A0093907W * */ public class FindController extends Controller { private static final String NAME = "Find"; private static final String DESCRIPTION = "Find tasks and events based on the provided keyword."; private static final String COMMAND_SYNTAX = "find [name]"; private static final String COMMAND_KEYWORD = "find"; public static final String MESSAGE_LISTING_SUCCESS = "A total of %s %s and %s %s found!"; public static final String MESSAGE_LISTING_FAILURE = "No tasks or events found!"; public static final String STRING_SPACE = " "; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX, COMMAND_KEYWORD); @Override public CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public void process(String input) throws ParseException { input = input.replaceFirst(COMMAND_KEYWORD, "").trim(); List<String> namesToFind = Arrays.asList(input.split(STRING_SPACE)); List<Predicate<Task>> taskPredicates = new ArrayList<Predicate<Task>>(); taskPredicates.add(Task.predByNameAny(namesToFind)); List<Task> tasks = Task.where(taskPredicates); List<Predicate<Event>> eventPredicates = new ArrayList<Predicate<Event>>(); eventPredicates.add(Event.predByNameAny(namesToFind)); List<Event> events = Event.where(eventPredicates); if (tasks.size() == 0 && events.size() == 0) { Renderer.renderIndex(TodoListDB.getInstance(), MESSAGE_LISTING_FAILURE); } else { String consoleMessage = String.format(MESSAGE_LISTING_SUCCESS, tasks.size(), StringUtil.pluralizer(tasks.size(), "task", "tasks"), events.size(), StringUtil.pluralizer(events.size(), "event", "events")); Renderer.renderSelected(TodoListDB.getInstance(), consoleMessage, tasks, events); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edacc.properties; import edacc.model.ComputationMethodDAO; import edacc.model.ComputationMethodDoesNotExistException; import edacc.model.DatabaseConnector; import edacc.model.ExperimentResult; import edacc.model.ExperimentResultDAO; import edacc.model.ExperimentResultHasProperty; import edacc.model.ExperimentResultHasPropertyDAO; import edacc.model.InstanceDAO; import edacc.model.InstanceHasProperty; import edacc.model.InstanceHasPropertyDAO; import edacc.model.InstanceNotInDBException; import edacc.model.NoConnectionToDBException; import edacc.model.Property; import edacc.model.PropertyDAO; import edacc.model.PropertyNotInDBException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.sql.Blob; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author rretz * @author dgall */ public class PropertyComputationUnit implements Runnable { private ExperimentResultHasProperty erhp; private InstanceHasProperty ihp; private PropertyComputationController callback; private Property property; /** * Defines the maximum time the unit will wait for a value of an external program (in millis). * default: 10 sec */ private static final int MAX_WAIT_TIME = 10000; PropertyComputationUnit(ExperimentResultHasProperty erhp, PropertyComputationController callback) { this.property = erhp.getProperty(); this.erhp = erhp; this.callback = callback; } PropertyComputationUnit(InstanceHasProperty ihp, PropertyComputationController callback) { this.ihp = ihp; this.callback = callback; this.property = ihp.getProperty(); } @Override public void run() { if (erhp != null) { try { Property property = erhp.getProperty(); switch (property.getPropertySource()) { case LauncherOutput: compute(ExperimentResultDAO.getLauncherOutput(erhp.getExpResult())); break; case SolverOutput: compute(ExperimentResultDAO.getSolverOutput(erhp.getExpResult())); break; case VerifierOutput: compute(ExperimentResultDAO.getVerifierOutput(erhp.getExpResult())); break; case WatcherOutput: compute(ExperimentResultDAO.getWatcherOutput(erhp.getExpResult())); break; } } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } else if (ihp != null) { try { switch (property.getPropertySource()) { case Instance: try { compute(InstanceDAO.getBinary(ihp.getInstance().getId())); } catch (InstanceNotInDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } break; case InstanceName: parseInstanceName(); break; case ExperimentResults: computeFromExperimentResults(); break; } } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } callback.callback(); } public static final Object sync = new Object(); private void computeFromExperimentResults() throws NoConnectionToDBException, SQLException, ComputationMethodDoesNotExistException, FileNotFoundException, IOException, InstanceNotInDBException, ErrorInExternalProgramException { if (ihp == null) { // only instance properties can be computed from experiment results return; } File bin; synchronized (sync) { bin = ComputationMethodDAO.getBinaryOfComputationMethod(property.getComputationMethod()); } bin.setExecutable(true); // only java files, we pipe objects :-) Process p = Runtime.getRuntime().exec("java -jar " + bin.getAbsolutePath()); // The std output stream of the external program (-> output of the program). We read the calculated value from this stream. BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // The error stream of the program BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); try { ArrayList<ExperimentResult> er; synchronized (sync) { er = ExperimentResultDAO.getAllByInstanceId(ihp.getInstance().getId()); } ObjectOutputStream os = new ObjectOutputStream(p.getOutputStream()); os.writeUnshared(er); os.flush(); os.close(); } catch (Exception e) { // TODO: error e.printStackTrace(); } // check, if already an error occured if (err.ready()) { throw new ErrorInExternalProgramException(err.readLine()); } // check, if program already has terminated try { int exit; if ((exit = p.exitValue()) != 0) { throw new ErrorInExternalProgramException("External program exited with errors! Exit value: " + exit); } } catch (IllegalThreadStateException e) { // do nothing if program is still running } long time = System.currentTimeMillis(); while (System.currentTimeMillis() - time < MAX_WAIT_TIME && !in.ready()) { try { Thread.sleep(100); } catch (InterruptedException ex) { break; } } // if no value is available after waitng time, kill the program if (!in.ready()) { p.destroy(); throw new ErrorInExternalProgramException("Time limit of external calculation exceeded! The external program has been terminated!"); } // Read first line of program output String value = in.readLine(); // set the value and save it ihp.setValue(value); InstanceHasPropertyDAO.save(ihp); } private void compute(Blob b) throws FileNotFoundException, IOException, SQLException, NoConnectionToDBException, InstanceNotInDBException, ComputationMethodDoesNotExistException, ErrorInExternalProgramException { if (b == null) { return; } if (property.getComputationMethod() != null) { // parse instance file (external program call) if (ihp != null) { File bin; synchronized (sync) { bin = ComputationMethodDAO.getBinaryOfComputationMethod(property.getComputationMethod()); } bin.setExecutable(true); System.out.println(bin.getAbsolutePath()); Process p = Runtime.getRuntime().exec(bin.getAbsolutePath()); Blob instance = InstanceDAO.getBinary(ihp.getInstance().getId()); BufferedReader instanceReader = new BufferedReader(new InputStreamReader(instance.getBinaryStream())); // The std input stream of the external program. We pipe the content of the instance file into that stream BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); // The std output stream of the external program (-> output of the program). We read the calculated value from this stream. BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // The error stream of the program BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); // pipe the content of the instance file to the input of the external program try { String s; while ((s = instanceReader.readLine()) != null) { out.write(s); out.newLine(); } } catch (IOException e) { // if a program stops reading from the stream, stop writing to it but show no error. Otherwise show an error message if (!e.getMessage().contains("Broken pipe")) { e.printStackTrace(); throw e; } } // Close output stream, after whole instance file has been written to program input out.close(); // check, if already an error occured if (err.ready()) { throw new ErrorInExternalProgramException(err.readLine()); } // check, if program already has terminated try { int exit; if ((exit = p.exitValue()) != 0) { throw new ErrorInExternalProgramException("External program exited with errors! Exit value: " + exit); } } catch (IllegalThreadStateException e) { // do nothing if program is still running } /** * Read the program output and save it as value of the property * for the given instance. * IMPORTANT! * The value will be saved as a String in the DB and no * conversion will be done! * When loading the value from the DB, the method * PropertyValueType.getJavaRepresentation(String) will be called * on that value for the PropertyValueType of the property (so * the String will be converted to the correct Java type). */ // wait some time till program output is available (maybe external program needs some time to calculate the property) long time = System.currentTimeMillis(); while (System.currentTimeMillis() - time < MAX_WAIT_TIME && !in.ready()) { try { Thread.sleep(100); } catch (InterruptedException ex) { break; } } // if no value is available after waitng time, kill the program if (!in.ready()) { p.destroy(); throw new ErrorInExternalProgramException("Time limit of external calculation exceeded! The external program has been terminated!"); } // Read first line of program output String value = in.readLine(); // set the value and save it ihp.setValue(value); System.out.println(value); InstanceHasPropertyDAO.save(ihp); } else if (erhp != null) { File bin = ComputationMethodDAO.getBinaryOfComputationMethod(property.getComputationMethod()); bin.setExecutable(true); Process p = Runtime.getRuntime().exec(bin.getAbsolutePath()); BufferedReader outputFileReader = new BufferedReader(new InputStreamReader(b.getBinaryStream())); // The std input stream of the external program. We pipe the content of the Blob b BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); // The std output stream of the external program (-> output of the program). We read the calculated value from this stream. BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // pipe the content of the output file to the input of the external program try { int i; while ((i = outputFileReader.read()) != -1) { out.write(i); } } catch (IOException e) { if (!e.getMessage().contains("Broken pipe")) { throw e; } } Vector<String> value = new Vector<String>(); while (in.ready()) { value.add(in.readLine()); } erhp.setValue(value); ExperimentResultHasPropertyDAO.save(erhp); } } else if (property.getRegularExpression() != null) { Vector<String> res = new Vector<String>(); BufferedReader buf = new BufferedReader(new InputStreamReader(b.getBinaryStream())); String tmp; Vector<String> toAdd = new Vector<String>(); while ((tmp = buf.readLine()) != null) { if (!(toAdd = parse(tmp)).isEmpty()) { res.addAll(toAdd); if (!property.isMultiple() || ihp != null) { break; } } } if (ihp != null) { ihp.setValue(res.firstElement()); InstanceHasPropertyDAO.save(ihp); } else if (erhp != null) { erhp.setValue(res); ExperimentResultHasPropertyDAO.save(erhp); } } } private Vector<String> parse(String toParse) { Vector<String> res = new Vector<String>(); for (int i = 0; i < property.getRegularExpression().size(); i++) { Pattern pat = Pattern.compile(property.getRegularExpression().get(i)); Matcher m = pat.matcher(toParse); while (m.find()) { res.add(m.group(1)); if (!property.isMultiple() || ihp != null) { return res; } } } return res; } private void parseInstanceName() { if (ihp != null) { Vector<String> res = parse(ihp.getInstance().getName()); if (!res.isEmpty()) { ihp.setValue(res.firstElement()); try { InstanceHasPropertyDAO.save(ihp); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } } } } public static void main(String[] args) { try { DatabaseConnector.getInstance().connect("edacc.informatik.uni-ulm.de", 3306, "edacc", "EDACC2", "edaccteam", false, false); PropertyComputationUnit unit = new PropertyComputationUnit(InstanceHasPropertyDAO.createInstanceHasInstanceProperty(InstanceDAO.getById(1), PropertyDAO.getById(1)), null); unit.compute(null); } catch (NoConnectionToDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (PropertyNotInDBException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (PropertyTypeNotExistException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (ComputationMethodDoesNotExistException ex) { Logger.getLogger(PropertyComputationUnit.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { e.printStackTrace(); } } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.todo.commons.exceptions.UnmatchedQuotesException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; public class FindController implements Controller { private static final String NAME = "Find"; private static final String DESCRIPTION = "Find all tasks and events based on the provided keywords."; private static final String COMMAND_SYNTAX = "find [name] or/and [on date]"; private static final String COMMAND_WORD = "find"; private static final String MESSAGE_LISTING_SUCCESS = "A total of %s found!"; private static final String MESSAGE_LISTING_FAILURE = "No task or event found!"; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { return (input.toLowerCase().startsWith(COMMAND_WORD)) ? 1 : 0; } private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"find"}); tokenDefinitions.put("eventType", new String[] { "event", "events", "task", "tasks"}); tokenDefinitions.put("status", new String[] { "complete" , "completed", "uncomplete", "uncompleted"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to", "before" }); tokenDefinitions.put("name", new String[] { "name" }); tokenDefinitions.put("tag", new String [] { "tag" }); //TODO return tokenDefinitions; } @Override public void process(String input) { Map<String, String[]> parsedResult; try { parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); } catch (UnmatchedQuotesException e) { System.out.println("Unmatched quote!"); return ; } HashSet<String> itemNameList = new HashSet<String>(); parseExactFindCommand(parsedResult, itemNameList); parseName(parsedResult, itemNameList); //parse addtional name enter by user System.out.println(Arrays.toString(parsedResult.get("name"))); System.out.println(itemNameList); // Task or event? boolean listAll = parseListAllType(parsedResult); boolean isTask = true; //default //if listing all type , set isTask and isEvent true if (!listAll) { isTask = parseIsTask(parsedResult); } boolean listAllStatus = parseListAllStatus(parsedResult); boolean isCompleted = false; //default //if listing all status, isCompleted will be ignored, listing both complete and uncomplete if (!listAllStatus) { isCompleted = !parseIsUncomplete(parsedResult); } String[] parsedDates = parseDates(parsedResult); if (parsedDates == null && listAllStatus == true && listAll == true && parsedResult.size() == 1 && itemNameList.size() == 0) { //display error message, no keyword provided String disambiguationString = String.format("%s %s %s %s", COMMAND_WORD, "<name>" , "<complete/incomplete>", "<task/event>"); Renderer.renderDisambiguation(disambiguationString, input); return ; } LocalDateTime dateOn = null; LocalDateTime dateFrom = null; LocalDateTime dateTo = null; if (parsedDates != null) { String naturalOn = parsedDates[0]; String naturalFrom = parsedDates[1]; String naturalTo = parsedDates[2]; // Parse natural date using Natty. dateOn = naturalOn == null ? null : parseNatural(naturalOn); dateFrom = naturalFrom == null ? null : parseNatural(naturalFrom); dateTo = naturalTo == null ? null : parseNatural(naturalTo); } //setting up view setupView(isTask, listAll, isCompleted, listAllStatus, dateOn, dateFrom, dateTo, itemNameList); } /** * Setting up the view * * @param isTask * true if CalendarItem should be a Task, false if Event * @param isEvent * true if CalendarItem should be a Event, false if Task * @param listAll * true if listing all type, isTask or isEvent are ignored * @param isCompleted * true if user request completed item * @param listAllStatus * true if user did not request any status, isCompleted is ignored * @param dateOn * Date if user specify for a certain date * @param dateFrom * Due date for Task or start date for Event * @param dateTo * End date for Event */ private void setupView(boolean isTask, boolean listAll, boolean isCompleted, boolean listAllStatus, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, HashSet<String> itemNameList) { TodoListDB db = TodoListDB.getInstance(); List<Task> tasks = null; List<Event> events = null; // isTask and isEvent = true, list all type if (listAll) { //no event or task keyword found isTask = false; tasks = setupTaskView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, itemNameList, db); events = setupEventView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, itemNameList, db); } if (isTask) { tasks = setupTaskView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, itemNameList, db); } else { events = setupEventView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, itemNameList, db); } // Update console message int numTasks = 0; int numEvents = 0; if (tasks != null) { numTasks = tasks.size(); } if(events != null) { numEvents = events.size(); } String consoleMessage = MESSAGE_LISTING_FAILURE; if (numTasks != 0 || numEvents != 0) { consoleMessage = String.format(MESSAGE_LISTING_SUCCESS, formatDisplayMessage(numTasks, numEvents)); } Renderer.renderSelected(db, consoleMessage, tasks, events); } private String formatDisplayMessage (int numTasks, int numEvents) { if (numTasks != 0 && numEvents != 0) { return String.format("%s and %s", formatTaskMessage(numTasks), formatEventMessage(numEvents)); } else if (numTasks != 0) { return formatTaskMessage(numTasks); } else { return formatEventMessage(numEvents); } } private String formatEventMessage (int numEvents) { return String.format("%d %s", numEvents, StringUtil.pluralizer(numEvents, "event", "events")); } private String formatTaskMessage (int numTasks) { return String.format("%d %s", numTasks, StringUtil.pluralizer(numTasks, "task", "tasks")); } private List<Event> setupEventView(boolean isCompleted, boolean listAllStatus, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, HashSet<String> itemNameList, TodoListDB db) { final LocalDateTime NO_DATE = null; if (dateFrom == null && dateTo == null && dateOn == null) { if (listAllStatus && itemNameList.size() == 0) { System.out.println("error"); //TODO : Nothing found return null; } else if (listAllStatus && itemNameList.size() != 0) { return db.getEventByName(db.getAllEvents(), itemNameList); } else if (isCompleted) { return db.getEventByRangeWithName(NO_DATE, LocalDateTime.now(), itemNameList); } else { return db.getEventByRangeWithName(LocalDateTime.now(), NO_DATE, itemNameList); } } else if (dateOn != null) { //by keyword found return db.getEventbyDateWithName(dateOn, itemNameList); } else { return db.getEventByRangeWithName(dateFrom, dateTo, itemNameList); } } private List<Task> setupTaskView(boolean isCompleted, boolean listAllStatus, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, HashSet<String> itemNameList, TodoListDB db) { if (dateFrom == null && dateTo == null && dateOn == null) { if (listAllStatus && itemNameList.size() == 0) { System.out.println("error"); //TODO : Nothing found return null; } else { return db.getTaskByRangeWithName(dateFrom, dateTo, isCompleted, listAllStatus, itemNameList); } } else if (dateOn != null) { //by keyword found return db.getTaskByDateWithStatusAndName(dateOn, isCompleted, listAllStatus, itemNameList); } else { return db.getTaskByRangeWithName(dateFrom, dateTo, isCompleted, listAllStatus, itemNameList); } } /** * Extract the name keyword enter by the user and put in the hashset of name keywords * @param parsedResult */ private void parseExactFindCommand(Map<String, String[]> parsedResult, HashSet<String> itemNameList) { if (parsedResult.get("default")[1] != null) { String[] result = parsedResult.get("default")[1].trim().split(" "); for (int i = 0; i < result.length; i ++) { itemNameList.add(result[i]); } } } /** * Extract the name keyword enter by the user and put in the hashset of name keywords * @param parsedResult */ private void parseName(Map<String, String[]> parsedResult, HashSet<String> itemNameList) { if (parsedResult.get("name") != null) { String[] result = parsedResult.get("name")[1].trim().split(" "); for (int i = 0; i < result.length; i ++) { itemNameList.add(result[i]); } } } /** * Parse a natural date into a LocalDateTime object. * * @param natural * @return LocalDateTime object */ private LocalDateTime parseNatural(String natural) { Parser parser = new Parser(); List<DateGroup> groups = parser.parse(natural); Date date = null; try { date = groups.get(0).getDates().get(0); } catch (IndexOutOfBoundsException e) { System.out.println("Error!"); // TODO return null; } LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return DateUtil.floorDate(ldt); } /** * Extracts the intended CalendarItem type specify from parsedResult. * * @param parsedResult * @return true if Task or event is not specify, false if either Task or Event specify */ private boolean parseListAllType (Map<String, String[]> parsedResult) { return !(parsedResult.get("eventType") != null); } /** * Extracts the intended status type specify from parsedResult. * * @param parsedResult * @return true if Task or event is not specify, false if either Task or Event specify */ private boolean parseListAllStatus (Map<String, String[]> parsedResult) { return !(parsedResult.get("status") != null); } /** * Extracts the intended CalendarItem status from parsedResult. * * @param parsedResult * @return true if uncomplete, false if complete */ private boolean parseIsUncomplete (Map<String, String[]> parsedResult) { return parsedResult.get("status")[0].contains("uncomplete"); } /** * Extracts the intended CalendarItem type from parsedResult. * * @param parsedResult * @return true if Task, false if Event */ private boolean parseIsTask (Map<String, String[]> parsedResult) { return parsedResult.get("eventType")[0].contains("task"); } /** * Extracts the natural dates from parsedResult. * * @param parsedResult * @return { naturalOn, naturalFrom, naturalTo } */ private String[] parseDates(Map<String, String[]> parsedResult) { String naturalFrom = null; String naturalTo = null; String naturalOn = null; if (parsedResult.get("time") == null) { if (parsedResult.get("timeFrom") != null) { naturalFrom = parsedResult.get("timeFrom")[1]; } if (parsedResult.get("timeTo") != null) { naturalTo = parsedResult.get("timeTo")[1]; } } else { naturalOn = parsedResult.get("time")[1]; } if (naturalFrom == null && naturalTo == null && naturalOn == null) { // no date found return null; } return new String[] { naturalOn, naturalFrom, naturalTo }; } }
package net.fortuna.ical4j.model; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import net.fortuna.ical4j.model.component.Daylight; import net.fortuna.ical4j.model.component.Observance; import net.fortuna.ical4j.model.component.VTimeZone; import net.fortuna.ical4j.model.property.TzId; import net.fortuna.ical4j.model.property.TzOffsetTo; public class TimeZone extends java.util.TimeZone { private static final long serialVersionUID = -5620979316746547234L; private final VTimeZone vTimeZone; private final int rawOffset; /** * Constructs a new instance based on the specified VTimeZone. * @param vTimeZone a VTIMEZONE object instance */ public TimeZone(final VTimeZone vTimeZone) { this.vTimeZone = vTimeZone; final TzId tzId = (TzId) vTimeZone.getProperty(Property.TZID); setID(tzId.getValue()); this.rawOffset = getRawOffset(vTimeZone); } /** * {@inheritDoc} */ public final int getOffset(final int era, final int year, final int month, final int day, final int dayOfWeek, final int milliseconds) { final Calendar cal = Calendar.getInstance(); cal.set(Calendar.ERA, era); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month); cal.set(Calendar.DAY_OF_YEAR, day); cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); cal.set(Calendar.MILLISECOND, milliseconds); final Observance observance = vTimeZone.getApplicableObservance(new DateTime(cal.getTime())); if (observance != null) { final TzOffsetTo offset = (TzOffsetTo) observance.getProperty(Property.TZOFFSETTO); return (int) offset.getOffset().getOffset(); } return 0; } /** * {@inheritDoc} */ public final int getRawOffset() { return rawOffset; } /** * Determines if the specified date is in daylight time according to * this timezone. This is done by finding the latest supporting * observance for the specified date and identifying whether it is * daylight time. * @param date a date instance * @return true if the specified date is in daylight time, otherwise false */ public final boolean inDaylightTime(final Date date) { final Observance observance = vTimeZone.getApplicableObservance(new DateTime(date)); return (observance != null && observance instanceof Daylight); } /** * {@inheritDoc} */ public final void setRawOffset(final int offsetMillis) { throw new UnsupportedOperationException("Updates to the VTIMEZONE object must be performed directly"); } /** * {@inheritDoc} */ public final boolean useDaylightTime() { final ComponentList daylights = vTimeZone.getObservances().getComponents(Observance.DAYLIGHT); return (!daylights.isEmpty()); } /** * @return Returns the VTimeZone backing this instance. */ public final VTimeZone getVTimeZone() { return vTimeZone; } private static final int getRawOffset(VTimeZone vt) { List seasonalTimes = vt.getObservances().getComponents(Observance.STANDARD); // if no standard time use daylight time.. if (seasonalTimes.size() == 0) { seasonalTimes = vt.getObservances().getComponents(Observance.DAYLIGHT); } if (seasonalTimes.size() > 0) { Collections.sort(seasonalTimes); final Component latestSeasonalTime = (Component) seasonalTimes.get(seasonalTimes.size() - 1); final TzOffsetTo offsetTo = (TzOffsetTo) latestSeasonalTime.getProperty(Property.TZOFFSETTO); if (offsetTo != null) { return (int) offsetTo.getOffset().getOffset(); } } return 0; } }
package tw.edu.ncu.cc.manage.dao.impl; import java.util.Collections; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import tw.edu.ncu.cc.manage.dao.IUserDao; import tw.edu.ncu.cc.manage.dao.support.AbstractOAuthServiceDao; import tw.edu.ncu.cc.manage.domain.User; @Repository public class UserDao extends AbstractOAuthServiceDao<User> implements IUserDao { private static final ParameterizedTypeReference<List<User>> parameterizedTypeReference = new ParameterizedTypeReference<List<User>>() {}; @Override protected ParameterizedTypeReference<List<User>> parameterizedTypeReferenceForList() { return parameterizedTypeReference; } @Override public Optional<User> find(String username) { Assert.hasText(username); return get(withUrl(userUrl(), username)); } @Override public User create(User user) { Assert.notNull(user); post(userUrl(), user); return user; } @Override public List<User> search(User dto) { Assert.notNull(dto); if (StringUtils.isEmpty(dto.getName())) { return Collections.emptyList(); } String url = UriComponentsBuilder.fromHttpUrl(userUrl()) .queryParam("name", dto.getName()) .build(false).toUriString(); return getList(url); } }
package org.bouncycastle.crypto.signers; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.Signer; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.util.Arrays; public class GenericSigner implements Signer { private final AsymmetricBlockCipher engine; private final Digest digest; private boolean forSigning; public GenericSigner( AsymmetricBlockCipher engine, Digest digest) { this.engine = engine; this.digest = digest; } /** * initialise the signer for signing or verification. * * @param forSigning * true if for signing, false otherwise * @param parameters * necessary parameters. */ public void init( boolean forSigning, CipherParameters parameters) { this.forSigning = forSigning; AsymmetricKeyParameter k; if (parameters instanceof ParametersWithRandom) { k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).getParameters(); } else { k = (AsymmetricKeyParameter)parameters; } if (forSigning && !k.isPrivate()) { throw new IllegalArgumentException("signing requires private key"); } if (!forSigning && k.isPrivate()) { throw new IllegalArgumentException("verification requires public key"); } reset(); engine.init(forSigning, parameters); } /** * update the internal digest with the byte b */ public void update( byte input) { digest.update(input); } /** * update the internal digest with the byte array in */ public void update( byte[] input, int inOff, int length) { digest.update(input, inOff, length); } /** * Generate a signature for the message we've been loaded with using the key * we were initialised with. */ public byte[] generateSignature() throws CryptoException, DataLengthException { if (!forSigning) { throw new IllegalStateException("GenericSigner not initialised for signature generation."); } byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return engine.processBlock(hash, 0, hash.length); } /** * return true if the internal state represents the signature described in * the passed in array. */ public boolean verifySignature( byte[] signature) { if (forSigning) { throw new IllegalStateException("GenericSigner not initialised for verification"); } byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); try { byte[] sig = engine.processBlock(signature, 0, signature.length); return Arrays.areEqual(sig, hash); } catch (Exception e) { return false; } } public void reset() { digest.reset(); } }
package org.jfree.chart.axis; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.jfree.chart.entity.CategoryLabelEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.util.ParamChecks; import org.jfree.data.category.CategoryDataset; import org.jfree.io.SerialUtilities; import org.jfree.text.G2TextMeasurer; import org.jfree.text.TextBlock; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.ui.Size2D; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.ShapeUtilities; /** * An axis that displays categories. */ public class CategoryAxis extends Axis implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5886554608114265863L; /** * The default margin for the axis (used for both lower and upper margins). */ public static final double DEFAULT_AXIS_MARGIN = 0.05; /** * The default margin between categories (a percentage of the overall axis * length). */ public static final double DEFAULT_CATEGORY_MARGIN = 0.20; /** The amount of space reserved at the start of the axis. */ private double lowerMargin; /** The amount of space reserved at the end of the axis. */ private double upperMargin; /** The amount of space reserved between categories. */ private double categoryMargin; /** The maximum number of lines for category labels. */ private int maximumCategoryLabelLines; /** * A ratio that is multiplied by the width of one category to determine the * maximum label width. */ private float maximumCategoryLabelWidthRatio; /** The category label offset. */ private int categoryLabelPositionOffset; /** * A structure defining the category label positions for each axis * location. */ private CategoryLabelPositions categoryLabelPositions; /** Storage for tick label font overrides (if any). */ private Map tickLabelFontMap; /** Storage for tick label paint overrides (if any). */ private transient Map tickLabelPaintMap; /** Storage for the category label tooltips (if any). */ private Map categoryLabelToolTips; /** Storage for the category label URLs (if any). */ private Map categoryLabelURLs; /** * Creates a new category axis with no label. */ public CategoryAxis() { this(null); } /** * Constructs a category axis, using default values where necessary. * * @param label the axis label (<code>null</code> permitted). */ public CategoryAxis(String label) { super(label); this.lowerMargin = DEFAULT_AXIS_MARGIN; this.upperMargin = DEFAULT_AXIS_MARGIN; this.categoryMargin = DEFAULT_CATEGORY_MARGIN; this.maximumCategoryLabelLines = 1; this.maximumCategoryLabelWidthRatio = 0.0f; this.categoryLabelPositionOffset = 4; this.categoryLabelPositions = CategoryLabelPositions.STANDARD; this.tickLabelFontMap = new HashMap(); this.tickLabelPaintMap = new HashMap(); this.categoryLabelToolTips = new HashMap(); this.categoryLabelURLs = new HashMap(); } /** * Returns the lower margin for the axis. * * @return The margin. * * @see #getUpperMargin() * @see #setLowerMargin(double) */ public double getLowerMargin() { return this.lowerMargin; } /** * Sets the lower margin for the axis and sends an {@link AxisChangeEvent} * to all registered listeners. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getLowerMargin() */ public void setLowerMargin(double margin) { this.lowerMargin = margin; fireChangeEvent(); } /** * Returns the upper margin for the axis. * * @return The margin. * * @see #getLowerMargin() * @see #setUpperMargin(double) */ public double getUpperMargin() { return this.upperMargin; } /** * Sets the upper margin for the axis and sends an {@link AxisChangeEvent} * to all registered listeners. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getUpperMargin() */ public void setUpperMargin(double margin) { this.upperMargin = margin; fireChangeEvent(); } /** * Returns the category margin. * * @return The margin. * * @see #setCategoryMargin(double) */ public double getCategoryMargin() { return this.categoryMargin; } /** * Sets the category margin and sends an {@link AxisChangeEvent} to all * registered listeners. The overall category margin is distributed over * N-1 gaps, where N is the number of categories on the axis. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getCategoryMargin() */ public void setCategoryMargin(double margin) { this.categoryMargin = margin; fireChangeEvent(); } /** * Returns the maximum number of lines to use for each category label. * * @return The maximum number of lines. * * @see #setMaximumCategoryLabelLines(int) */ public int getMaximumCategoryLabelLines() { return this.maximumCategoryLabelLines; } /** * Sets the maximum number of lines to use for each category label and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param lines the maximum number of lines. * * @see #getMaximumCategoryLabelLines() */ public void setMaximumCategoryLabelLines(int lines) { this.maximumCategoryLabelLines = lines; fireChangeEvent(); } /** * Returns the category label width ratio. * * @return The ratio. * * @see #setMaximumCategoryLabelWidthRatio(float) */ public float getMaximumCategoryLabelWidthRatio() { return this.maximumCategoryLabelWidthRatio; } /** * Sets the maximum category label width ratio and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param ratio the ratio. * * @see #getMaximumCategoryLabelWidthRatio() */ public void setMaximumCategoryLabelWidthRatio(float ratio) { this.maximumCategoryLabelWidthRatio = ratio; fireChangeEvent(); } /** * Returns the offset between the axis and the category labels (before * label positioning is taken into account). * * @return The offset (in Java2D units). * * @see #setCategoryLabelPositionOffset(int) */ public int getCategoryLabelPositionOffset() { return this.categoryLabelPositionOffset; } /** * Sets the offset between the axis and the category labels (before label * positioning is taken into account) and sends a change event to all * registered listeners. * * @param offset the offset (in Java2D units). * * @see #getCategoryLabelPositionOffset() */ public void setCategoryLabelPositionOffset(int offset) { this.categoryLabelPositionOffset = offset; fireChangeEvent(); } /** * Returns the category label position specification (this contains label * positioning info for all four possible axis locations). * * @return The positions (never <code>null</code>). * * @see #setCategoryLabelPositions(CategoryLabelPositions) */ public CategoryLabelPositions getCategoryLabelPositions() { return this.categoryLabelPositions; } /** * Sets the category label position specification for the axis and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param positions the positions (<code>null</code> not permitted). * * @see #getCategoryLabelPositions() */ public void setCategoryLabelPositions(CategoryLabelPositions positions) { ParamChecks.nullNotPermitted(positions, "positions"); this.categoryLabelPositions = positions; fireChangeEvent(); } /** * Returns the font for the tick label for the given category. * * @param category the category (<code>null</code> not permitted). * * @return The font (never <code>null</code>). * * @see #setTickLabelFont(Comparable, Font) */ public Font getTickLabelFont(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); Font result = (Font) this.tickLabelFontMap.get(category); // if there is no specific font, use the general one... if (result == null) { result = getTickLabelFont(); } return result; } /** * Sets the font for the tick label for the specified category and sends * an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param font the font (<code>null</code> permitted). * * @see #getTickLabelFont(Comparable) */ public void setTickLabelFont(Comparable category, Font font) { ParamChecks.nullNotPermitted(category, "category"); if (font == null) { this.tickLabelFontMap.remove(category); } else { this.tickLabelFontMap.put(category, font); } fireChangeEvent(); } /** * Returns the paint for the tick label for the given category. * * @param category the category (<code>null</code> not permitted). * * @return The paint (never <code>null</code>). * * @see #setTickLabelPaint(Paint) */ public Paint getTickLabelPaint(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); Paint result = (Paint) this.tickLabelPaintMap.get(category); // if there is no specific paint, use the general one... if (result == null) { result = getTickLabelPaint(); } return result; } /** * Sets the paint for the tick label for the specified category and sends * an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param paint the paint (<code>null</code> permitted). * * @see #getTickLabelPaint(Comparable) */ public void setTickLabelPaint(Comparable category, Paint paint) { ParamChecks.nullNotPermitted(category, "category"); if (paint == null) { this.tickLabelPaintMap.remove(category); } else { this.tickLabelPaintMap.put(category, paint); } fireChangeEvent(); } /** * Adds a tooltip to the specified category and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param tooltip the tooltip text (<code>null</code> permitted). * * @see #removeCategoryLabelToolTip(Comparable) */ public void addCategoryLabelToolTip(Comparable category, String tooltip) { ParamChecks.nullNotPermitted(category, "category"); this.categoryLabelToolTips.put(category, tooltip); fireChangeEvent(); } /** * Returns the tool tip text for the label belonging to the specified * category. * * @param category the category (<code>null</code> not permitted). * * @return The tool tip text (possibly <code>null</code>). * * @see #addCategoryLabelToolTip(Comparable, String) * @see #removeCategoryLabelToolTip(Comparable) */ public String getCategoryLabelToolTip(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); return (String) this.categoryLabelToolTips.get(category); } /** * Removes the tooltip for the specified category and, if there was a value * associated with that category, sends an {@link AxisChangeEvent} to all * registered listeners. * * @param category the category (<code>null</code> not permitted). * * @see #addCategoryLabelToolTip(Comparable, String) * @see #clearCategoryLabelToolTips() */ public void removeCategoryLabelToolTip(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); if (this.categoryLabelToolTips.remove(category) != null) { fireChangeEvent(); } } /** * Clears the category label tooltips and sends an {@link AxisChangeEvent} * to all registered listeners. * * @see #addCategoryLabelToolTip(Comparable, String) * @see #removeCategoryLabelToolTip(Comparable) */ public void clearCategoryLabelToolTips() { this.categoryLabelToolTips.clear(); fireChangeEvent(); } /** * Adds a URL (to be used in image maps) to the specified category and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param url the URL text (<code>null</code> permitted). * * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public void addCategoryLabelURL(Comparable category, String url) { ParamChecks.nullNotPermitted(category, "category"); this.categoryLabelURLs.put(category, url); fireChangeEvent(); } /** * Returns the URL for the label belonging to the specified category. * * @param category the category (<code>null</code> not permitted). * * @return The URL text (possibly <code>null</code>). * * @see #addCategoryLabelURL(Comparable, String) * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public String getCategoryLabelURL(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); return (String) this.categoryLabelURLs.get(category); } /** * Removes the URL for the specified category and, if there was a URL * associated with that category, sends an {@link AxisChangeEvent} to all * registered listeners. * * @param category the category (<code>null</code> not permitted). * * @see #addCategoryLabelURL(Comparable, String) * @see #clearCategoryLabelURLs() * * @since 1.0.16 */ public void removeCategoryLabelURL(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); if (this.categoryLabelURLs.remove(category) != null) { fireChangeEvent(); } } /** * Clears the category label URLs and sends an {@link AxisChangeEvent} * to all registered listeners. * * @see #addCategoryLabelURL(Comparable, String) * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public void clearCategoryLabelURLs() { this.categoryLabelURLs.clear(); fireChangeEvent(); } /** * Returns the Java 2D coordinate for a category. * * @param anchor the anchor point. * @param category the category index. * @param categoryCount the category count. * @param area the data area. * @param edge the location of the axis. * * @return The coordinate. */ public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; if (anchor == CategoryAnchor.START) { result = getCategoryStart(category, categoryCount, area, edge); } else if (anchor == CategoryAnchor.MIDDLE) { result = getCategoryMiddle(category, categoryCount, area, edge); } else if (anchor == CategoryAnchor.END) { result = getCategoryEnd(category, categoryCount, area, edge); } return result; } /** * Returns the starting coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryStart(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { result = area.getX() + area.getWidth() * getLowerMargin(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { result = area.getMinY() + area.getHeight() * getLowerMargin(); } double categorySize = calculateCategorySize(categoryCount, area, edge); double categoryGapWidth = calculateCategoryGapSize(categoryCount, area, edge); result = result + category * (categorySize + categoryGapWidth); return result; } /** * Returns the middle coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryMiddle(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { if (category < 0 || category >= categoryCount) { throw new IllegalArgumentException("Invalid category index: " + category); } return getCategoryStart(category, categoryCount, area, edge) + calculateCategorySize(categoryCount, area, edge) / 2; } /** * Returns the end coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryEnd(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { return getCategoryStart(category, categoryCount, area, edge) + calculateCategorySize(categoryCount, area, edge); } /** * A convenience method that returns the axis coordinate for the centre of * a category. * * @param category the category key (<code>null</code> not permitted). * @param categories the categories (<code>null</code> not permitted). * @param area the data area (<code>null</code> not permitted). * @param edge the edge along which the axis lies (<code>null</code> not * permitted). * * @return The centre coordinate. * * @since 1.0.11 * * @see #getCategorySeriesMiddle(Comparable, Comparable, CategoryDataset, * double, Rectangle2D, RectangleEdge) */ public double getCategoryMiddle(Comparable category, List categories, Rectangle2D area, RectangleEdge edge) { ParamChecks.nullNotPermitted(categories, "categories"); int categoryIndex = categories.indexOf(category); int categoryCount = categories.size(); return getCategoryMiddle(categoryIndex, categoryCount, area, edge); } /** * Returns the middle coordinate (in Java2D space) for a series within a * category. * * @param category the category (<code>null</code> not permitted). * @param seriesKey the series key (<code>null</code> not permitted). * @param dataset the dataset (<code>null</code> not permitted). * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0); * @param area the area (<code>null</code> not permitted). * @param edge the edge (<code>null</code> not permitted). * * @return The coordinate in Java2D space. * * @since 1.0.7 */ public double getCategorySeriesMiddle(Comparable category, Comparable seriesKey, CategoryDataset dataset, double itemMargin, Rectangle2D area, RectangleEdge edge) { int categoryIndex = dataset.getColumnIndex(category); int categoryCount = dataset.getColumnCount(); int seriesIndex = dataset.getRowIndex(seriesKey); int seriesCount = dataset.getRowCount(); double start = getCategoryStart(categoryIndex, categoryCount, area, edge); double end = getCategoryEnd(categoryIndex, categoryCount, area, edge); double width = end - start; if (seriesCount == 1) { return start + width / 2.0; } else { double gap = (width * itemMargin) / (seriesCount - 1); double ww = (width * (1 - itemMargin)) / seriesCount; return start + (seriesIndex * (ww + gap)) + ww / 2.0; } } /** * Returns the middle coordinate (in Java2D space) for a series within a * category. * * @param categoryIndex the category index. * @param categoryCount the category count. * @param seriesIndex the series index. * @param seriesCount the series count. * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0); * @param area the area (<code>null</code> not permitted). * @param edge the edge (<code>null</code> not permitted). * * @return The coordinate in Java2D space. * * @since 1.0.13 */ public double getCategorySeriesMiddle(int categoryIndex, int categoryCount, int seriesIndex, int seriesCount, double itemMargin, Rectangle2D area, RectangleEdge edge) { double start = getCategoryStart(categoryIndex, categoryCount, area, edge); double end = getCategoryEnd(categoryIndex, categoryCount, area, edge); double width = end - start; if (seriesCount == 1) { return start + width / 2.0; } else { double gap = (width * itemMargin) / (seriesCount - 1); double ww = (width * (1 - itemMargin)) / seriesCount; return start + (seriesIndex * (ww + gap)) + ww / 2.0; } } /** * Calculates the size (width or height, depending on the location of the * axis) of a category. * * @param categoryCount the number of categories. * @param area the area within which the categories will be drawn. * @param edge the axis location. * * @return The category size. */ protected double calculateCategorySize(int categoryCount, Rectangle2D area, RectangleEdge edge) { double result; double available = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { available = area.getWidth(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { available = area.getHeight(); } if (categoryCount > 1) { result = available * (1 - getLowerMargin() - getUpperMargin() - getCategoryMargin()); result = result / categoryCount; } else { result = available * (1 - getLowerMargin() - getUpperMargin()); } return result; } /** * Calculates the size (width or height, depending on the location of the * axis) of a category gap. * * @param categoryCount the number of categories. * @param area the area within which the categories will be drawn. * @param edge the axis location. * * @return The category gap width. */ protected double calculateCategoryGapSize(int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; double available = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { available = area.getWidth(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { available = area.getHeight(); } if (categoryCount > 1) { result = available * getCategoryMargin() / (categoryCount - 1); } return result; } /** * Estimates the space required for the axis, given a specific drawing area. * * @param g2 the graphics device (used to obtain font information). * @param plot the plot that the axis belongs to. * @param plotArea the area within which the axis should be drawn. * @param edge the axis location (top or bottom). * @param space the space already reserved. * * @return The space required to draw the axis. */ @Override public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) { // create a new space object if one wasn't supplied... if (space == null) { space = new AxisSpace(); } // if the axis is not visible, no additional space is required... if (!isVisible()) { return space; } // calculate the max size of the tick labels (if visible)... double tickLabelHeight = 0.0; double tickLabelWidth = 0.0; if (isTickLabelsVisible()) { g2.setFont(getTickLabelFont()); AxisState state = new AxisState(); // we call refresh ticks just to get the maximum width or height refreshTicks(g2, state, plotArea, edge); if (edge == RectangleEdge.TOP) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.BOTTOM) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.LEFT) { tickLabelWidth = state.getMax(); } else if (edge == RectangleEdge.RIGHT) { tickLabelWidth = state.getMax(); } } // get the axis label size and update the space object... Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge); double labelHeight, labelWidth; if (RectangleEdge.isTopOrBottom(edge)) { labelHeight = labelEnclosure.getHeight(); space.add(labelHeight + tickLabelHeight + this.categoryLabelPositionOffset, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { labelWidth = labelEnclosure.getWidth(); space.add(labelWidth + tickLabelWidth + this.categoryLabelPositionOffset, edge); } return space; } /** * Configures the axis against the current plot. */ @Override public void configure() { // nothing required } /** * Draws the axis on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device (<code>null</code> not permitted). * @param cursor the cursor location. * @param plotArea the area within which the axis should be drawn * (<code>null</code> not permitted). * @param dataArea the area within which the plot is being drawn * (<code>null</code> not permitted). * @param edge the location of the axis (<code>null</code> not permitted). * @param plotState collects information about the plot * (<code>null</code> permitted). * * @return The axis state (never <code>null</code>). */ @Override public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) { // if the axis is not visible, don't draw it... if (!isVisible()) { return new AxisState(cursor); } if (isAxisLineVisible()) { drawAxisLine(g2, cursor, dataArea, edge); } AxisState state = new AxisState(cursor); if (isTickMarksVisible()) { drawTickMarks(g2, cursor, dataArea, edge, state); } createAndAddEntity(cursor, state, dataArea, edge, plotState); // draw the category labels and axis label state = drawCategoryLabels(g2, plotArea, dataArea, edge, state, plotState); if (getAttributedLabel() != null) { state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, dataArea, edge, state); } else { state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state); } return state; } /** * Draws the category labels and returns the updated axis state. * * @param g2 the graphics device (<code>null</code> not permitted). * @param plotArea the plot area (<code>null</code> not permitted). * @param dataArea the area inside the axes (<code>null</code> not * permitted). * @param edge the axis location (<code>null</code> not permitted). * @param state the axis state (<code>null</code> not permitted). * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return The updated axis state (never <code>null</code>). */ protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { ParamChecks.nullNotPermitted(state, "state"); if (!isTickLabelsVisible()) { return state; } List ticks = refreshTicks(g2, state, plotArea, edge); state.setTicks(ticks); int categoryIndex = 0; Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { CategoryTick tick = (CategoryTick) iterator.next(); g2.setFont(getTickLabelFont(tick.getCategory())); g2.setPaint(getTickLabelPaint(tick.getCategory())); CategoryLabelPosition position = this.categoryLabelPositions.getLabelPosition(edge); double x0 = 0.0; double x1 = 0.0; double y0 = 0.0; double y1 = 0.0; if (edge == RectangleEdge.TOP) { x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); y1 = state.getCursor() - this.categoryLabelPositionOffset; y0 = y1 - state.getMax(); } else if (edge == RectangleEdge.BOTTOM) { x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); y0 = state.getCursor() + this.categoryLabelPositionOffset; y1 = y0 + state.getMax(); } else if (edge == RectangleEdge.LEFT) { y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); x1 = state.getCursor() - this.categoryLabelPositionOffset; x0 = x1 - state.getMax(); } else if (edge == RectangleEdge.RIGHT) { y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); x0 = state.getCursor() + this.categoryLabelPositionOffset; x1 = x0 - state.getMax(); } Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0), (y1 - y0)); Point2D anchorPoint = RectangleAnchor.coordinates(area, position.getCategoryAnchor()); TextBlock block = tick.getLabel(); block.draw(g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getLabelAnchor(), (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getAngle()); Shape bounds = block.calculateBounds(g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getLabelAnchor(), (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getAngle()); if (plotState != null && plotState.getOwner() != null) { EntityCollection entities = plotState.getOwner() .getEntityCollection(); if (entities != null) { String tooltip = getCategoryLabelToolTip( tick.getCategory()); String url = getCategoryLabelURL(tick.getCategory()); entities.add(new CategoryLabelEntity(tick.getCategory(), bounds, tooltip, url)); } } categoryIndex++; } if (edge.equals(RectangleEdge.TOP)) { double h = state.getMax() + this.categoryLabelPositionOffset; state.cursorUp(h); } else if (edge.equals(RectangleEdge.BOTTOM)) { double h = state.getMax() + this.categoryLabelPositionOffset; state.cursorDown(h); } else if (edge == RectangleEdge.LEFT) { double w = state.getMax() + this.categoryLabelPositionOffset; state.cursorLeft(w); } else if (edge == RectangleEdge.RIGHT) { double w = state.getMax() + this.categoryLabelPositionOffset; state.cursorRight(w); } return state; } /** * Creates a temporary list of ticks that can be used when drawing the axis. * * @param g2 the graphics device (used to get font measurements). * @param state the axis state. * @param dataArea the area inside the axes. * @param edge the location of the axis. * * @return A list of ticks. */ @Override public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { List ticks = new java.util.ArrayList(); // sanity check for data area... if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) { return ticks; } CategoryPlot plot = (CategoryPlot) getPlot(); List categories = plot.getCategoriesForAxis(this); double max = 0.0; if (categories != null) { CategoryLabelPosition position = this.categoryLabelPositions.getLabelPosition(edge); float r = this.maximumCategoryLabelWidthRatio; if (r <= 0.0) { r = position.getWidthRatio(); } float l; if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) { l = (float) calculateCategorySize(categories.size(), dataArea, edge); } else { if (RectangleEdge.isLeftOrRight(edge)) { l = (float) dataArea.getWidth(); } else { l = (float) dataArea.getHeight(); } } int categoryIndex = 0; Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable category = (Comparable) iterator.next(); g2.setFont(getTickLabelFont(category)); TextBlock label = createLabel(category, l * r, edge, g2); if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) { max = Math.max(max, calculateTextBlockHeight(label, position, g2)); } else if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) { max = Math.max(max, calculateTextBlockWidth(label, position, g2)); } Tick tick = new CategoryTick(category, label, position.getLabelAnchor(), position.getRotationAnchor(), position.getAngle()); ticks.add(tick); categoryIndex = categoryIndex + 1; } } state.setMax(max); return ticks; } /** * Draws the tick marks. * * @param g2 the graphics target. * @param cursor the cursor position (an offset when drawing multiple axes) * @param dataArea the area for plotting the data. * @param edge the location of the axis. * @param state the axis state. * * @since 1.0.13 */ public void drawTickMarks(Graphics2D g2, double cursor, Rectangle2D dataArea, RectangleEdge edge, AxisState state) { Plot p = getPlot(); if (p == null) { return; } CategoryPlot plot = (CategoryPlot) p; double il = getTickMarkInsideLength(); double ol = getTickMarkOutsideLength(); Line2D line = new Line2D.Double(); List categories = plot.getCategoriesForAxis(this); g2.setPaint(getTickMarkPaint()); g2.setStroke(getTickMarkStroke()); if (edge.equals(RectangleEdge.TOP)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double x = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(x, cursor, x, cursor + il); g2.draw(line); line.setLine(x, cursor, x, cursor - ol); g2.draw(line); } state.cursorUp(ol); } else if (edge.equals(RectangleEdge.BOTTOM)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double x = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(x, cursor, x, cursor - il); g2.draw(line); line.setLine(x, cursor, x, cursor + ol); g2.draw(line); } state.cursorDown(ol); } else if (edge.equals(RectangleEdge.LEFT)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double y = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(cursor, y, cursor + il, y); g2.draw(line); line.setLine(cursor, y, cursor - ol, y); g2.draw(line); } state.cursorLeft(ol); } else if (edge.equals(RectangleEdge.RIGHT)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double y = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(cursor, y, cursor - il, y); g2.draw(line); line.setLine(cursor, y, cursor + ol, y); g2.draw(line); } state.cursorRight(ol); } } /** * Creates a label. * * @param category the category. * @param width the available width. * @param edge the edge on which the axis appears. * @param g2 the graphics device. * * @return A label. */ protected TextBlock createLabel(Comparable category, float width, RectangleEdge edge, Graphics2D g2) { TextBlock label = TextUtilities.createTextBlock(category.toString(), getTickLabelFont(category), getTickLabelPaint(category), width, this.maximumCategoryLabelLines, new G2TextMeasurer(g2)); return label; } /** * A utility method for determining the width of a text block. * * @param block the text block. * @param position the position. * @param g2 the graphics device. * * @return The width. */ protected double calculateTextBlockWidth(TextBlock block, CategoryLabelPosition position, Graphics2D g2) { RectangleInsets insets = getTickLabelInsets(); Size2D size = block.calculateDimensions(g2); Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(), size.getHeight()); Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(), 0.0f, 0.0f); double w = rotatedBox.getBounds2D().getWidth() + insets.getLeft() + insets.getRight(); return w; } /** * A utility method for determining the height of a text block. * * @param block the text block. * @param position the label position. * @param g2 the graphics device. * * @return The height. */ protected double calculateTextBlockHeight(TextBlock block, CategoryLabelPosition position, Graphics2D g2) { RectangleInsets insets = getTickLabelInsets(); Size2D size = block.calculateDimensions(g2); Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(), size.getHeight()); Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(), 0.0f, 0.0f); double h = rotatedBox.getBounds2D().getHeight() + insets.getTop() + insets.getBottom(); return h; } /** * Creates a clone of the axis. * * @return A clone. * * @throws CloneNotSupportedException if some component of the axis does * not support cloning. */ @Override public Object clone() throws CloneNotSupportedException { CategoryAxis clone = (CategoryAxis) super.clone(); clone.tickLabelFontMap = new HashMap(this.tickLabelFontMap); clone.tickLabelPaintMap = new HashMap(this.tickLabelPaintMap); clone.categoryLabelToolTips = new HashMap(this.categoryLabelToolTips); clone.categoryLabelURLs = new HashMap(this.categoryLabelToolTips); return clone; } /** * Tests this axis for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryAxis)) { return false; } if (!super.equals(obj)) { return false; } CategoryAxis that = (CategoryAxis) obj; if (that.lowerMargin != this.lowerMargin) { return false; } if (that.upperMargin != this.upperMargin) { return false; } if (that.categoryMargin != this.categoryMargin) { return false; } if (that.maximumCategoryLabelWidthRatio != this.maximumCategoryLabelWidthRatio) { return false; } if (that.categoryLabelPositionOffset != this.categoryLabelPositionOffset) { return false; } if (!ObjectUtilities.equal(that.categoryLabelPositions, this.categoryLabelPositions)) { return false; } if (!ObjectUtilities.equal(that.categoryLabelToolTips, this.categoryLabelToolTips)) { return false; } if (!ObjectUtilities.equal(this.categoryLabelURLs, that.categoryLabelURLs)) { return false; } if (!ObjectUtilities.equal(this.tickLabelFontMap, that.tickLabelFontMap)) { return false; } if (!equalPaintMaps(this.tickLabelPaintMap, that.tickLabelPaintMap)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); writePaintMap(this.tickLabelPaintMap, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.tickLabelPaintMap = readPaintMap(stream); } /** * Reads a <code>Map</code> of (<code>Comparable</code>, <code>Paint</code>) * elements from a stream. * * @param in the input stream. * * @return The map. * * @throws IOException * @throws ClassNotFoundException * * @see #writePaintMap(Map, ObjectOutputStream) */ private Map readPaintMap(ObjectInputStream in) throws IOException, ClassNotFoundException { boolean isNull = in.readBoolean(); if (isNull) { return null; } Map result = new HashMap(); int count = in.readInt(); for (int i = 0; i < count; i++) { Comparable category = (Comparable) in.readObject(); Paint paint = SerialUtilities.readPaint(in); result.put(category, paint); } return result; } /** * Writes a map of (<code>Comparable</code>, <code>Paint</code>) * elements to a stream. * * @param map the map (<code>null</code> permitted). * * @param out * @throws IOException * * @see #readPaintMap(ObjectInputStream) */ private void writePaintMap(Map map, ObjectOutputStream out) throws IOException { if (map == null) { out.writeBoolean(true); } else { out.writeBoolean(false); Set keys = map.keySet(); int count = keys.size(); out.writeInt(count); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); out.writeObject(key); SerialUtilities.writePaint((Paint) map.get(key), out); } } } /** * Tests two maps containing (<code>Comparable</code>, <code>Paint</code>) * elements for equality. * * @param map1 the first map (<code>null</code> not permitted). * @param map2 the second map (<code>null</code> not permitted). * * @return A boolean. */ private boolean equalPaintMaps(Map map1, Map map2) { if (map1.size() != map2.size()) { return false; } Set entries = map1.entrySet(); Iterator iterator = entries.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Paint p1 = (Paint) entry.getValue(); Paint p2 = (Paint) map2.get(entry.getKey()); if (!PaintUtilities.equal(p1, p2)) { return false; } } return true; } /** * Draws the category labels and returns the updated axis state. * * @param g2 the graphics device (<code>null</code> not permitted). * @param dataArea the area inside the axes (<code>null</code> not * permitted). * @param edge the axis location (<code>null</code> not permitted). * @param state the axis state (<code>null</code> not permitted). * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return The updated axis state (never <code>null</code>). * * @deprecated Use {@link #drawCategoryLabels(Graphics2D, Rectangle2D, * Rectangle2D, RectangleEdge, AxisState, PlotRenderingInfo)}. */ protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { // this method is deprecated because we really need the plotArea // when drawing the labels - see bug 1277726 return drawCategoryLabels(g2, dataArea, dataArea, edge, state, plotState); } }
package edu.iu.grid.oim.view.divrep; import java.io.PrintWriter; import com.divrep.DivRep; import com.divrep.DivRepEvent; import com.divrep.DivRepEventListener; import com.divrep.common.DivRepButton; import com.divrep.common.DivRepCheckBox; import com.divrep.common.DivRepFormElement; import com.divrep.common.DivRepTextBox; import com.divrep.validator.DivRepDoubleValidator; import edu.iu.grid.oim.model.Context; import edu.iu.grid.oim.model.db.ResourceWLCGModel; import edu.iu.grid.oim.model.db.record.ResourceWLCGRecord; public class ResourceWLCG extends DivRepFormElement { private Context context; private WLCGEditor editor; private DivRepButton add_button; class WLCGEditor extends DivRepFormElement { //WLCG Interop details private DivRepCheckBox interop_bdii; private DivRepCheckBox interop_monitoring; private DivRepCheckBox interop_accounting; private DivRepTextBox wlcg_accounting_name; private DivRepTextBox ksi2k_minimum; private DivRepTextBox ksi2k_maximum; private DivRepTextBox hepspec; private DivRepTextBox storage_capacity_minimum; private DivRepTextBox storage_capacity_maximum; private WLCGEditor myself; protected WLCGEditor(DivRep parent, ResourceWLCGRecord wrec) { super(parent); myself = this; interop_bdii = new DivRepCheckBox(this); interop_bdii.setLabel("Should this resource be part of WLCG Interop BDII?"); interop_monitoring = new DivRepCheckBox(this); interop_monitoring.setLabel("Should this resource be part of WLCG Interop Monitoring?"); interop_accounting = new DivRepCheckBox(this); interop_accounting.setLabel("Should this resource be part of WLCG Interop Accounting?"); wlcg_accounting_name = new DivRepTextBox(this); wlcg_accounting_name.setLabel("WLCG Accounting Name"); wlcg_accounting_name.setSampleValue("ABC Accounting"); wlcg_accounting_name.setRequired(true); hideWLCGAccountingName(true); interop_accounting.addEventListener(new DivRepEventListener() { public void handleEvent(DivRepEvent e) { if(((String)e.value).compareTo("true") == 0) { hideWLCGAccountingName(false); } else { hideWLCGAccountingName(true); } } }); ksi2k_minimum = new DivRepTextBox(this); ksi2k_minimum.setLabel("KSI2K Minimum"); ksi2k_minimum.addValidator(DivRepDoubleValidator.getInstance()); ksi2k_minimum.setSampleValue("100.0"); ksi2k_minimum.setRequired(true); ksi2k_maximum = new DivRepTextBox(this); ksi2k_maximum.setLabel("KSI2K Maximum"); ksi2k_maximum.addValidator(DivRepDoubleValidator.getInstance()); ksi2k_maximum.setSampleValue("500.0"); ksi2k_maximum.setRequired(true); hepspec = new DivRepTextBox(this); hepspec.setLabel("HEPSPEC Value"); hepspec.addValidator(DivRepDoubleValidator.getInstance()); hepspec.setSampleValue("85.0"); hepspec.setRequired(true); storage_capacity_minimum = new DivRepTextBox(this); storage_capacity_minimum.setLabel("Storage Capacity Minimum (in TeraBytes)"); storage_capacity_minimum.addValidator(DivRepDoubleValidator.getInstance()); storage_capacity_minimum.setSampleValue("1.0"); storage_capacity_minimum.setRequired(true); storage_capacity_maximum = new DivRepTextBox(this); storage_capacity_maximum.setLabel("Storage Capacity Maximum (in TeraBytes)"); storage_capacity_maximum.addValidator(DivRepDoubleValidator.getInstance()); storage_capacity_maximum.setSampleValue("5.5"); storage_capacity_maximum.setRequired(true); ResourceWLCGModel wmodel = new ResourceWLCGModel(context); if(wrec != null) { //if WLCG record exist, populate the values interop_bdii.setValue(wrec.interop_bdii); interop_monitoring.setValue(wrec.interop_monitoring); interop_accounting.setValue(wrec.interop_accounting); if(wrec.interop_accounting) { hideWLCGAccountingName(false); } if (wrec.interop_accounting != null) { wlcg_accounting_name.setValue(wrec.accounting_name); } if(wrec.ksi2k_minimum != null) { ksi2k_minimum.setValue(wrec.ksi2k_minimum.toString()); } if(wrec.ksi2k_maximum != null) { ksi2k_maximum.setValue(wrec.ksi2k_maximum.toString()); } if(wrec.hepspec != null) { hepspec.setValue(wrec.hepspec.toString()); } if(wrec.storage_capacity_minimum != null) { storage_capacity_minimum.setValue(wrec.storage_capacity_minimum.toString()); } if(wrec.storage_capacity_maximum != null) { storage_capacity_maximum.setValue(wrec.storage_capacity_maximum.toString()); } } } private void hideWLCGAccountingName(Boolean b) { wlcg_accounting_name.setHidden(b); redraw(); wlcg_accounting_name.setRequired(!b); } protected void onEvent(DivRepEvent e) { // TODO Auto-generated method stub } public void render(PrintWriter out) { out.write("<div id=\""+getNodeID()+"\" class=\"wlcg_editor\">"); for(DivRep child : childnodes) { if(child instanceof DivRepFormElement) { DivRepFormElement elem = (DivRepFormElement)child; if(!elem.isHidden()) { out.print("<div class=\"divrep_form_element\">"); child.render(out); out.print("</div>"); } } else { //non form element.. child.render(out); } } out.write("</div>"); } //caller should set resource_id public ResourceWLCGRecord getWLCGRecord() { ResourceWLCGRecord rec = new ResourceWLCGRecord(); rec.interop_monitoring = interop_monitoring.getValue(); rec.interop_bdii = interop_bdii.getValue(); rec.interop_accounting = interop_accounting.getValue(); rec.accounting_name = wlcg_accounting_name.getValue(); rec.ksi2k_minimum = ksi2k_minimum.getValueAsDouble(); rec.ksi2k_maximum = ksi2k_maximum.getValueAsDouble(); rec.hepspec = hepspec.getValueAsDouble(); rec.storage_capacity_minimum = storage_capacity_minimum.getValueAsDouble(); rec.storage_capacity_maximum = storage_capacity_maximum.getValueAsDouble(); return rec; } } public ResourceWLCGRecord getWlcgRecord () { return editor.getWLCGRecord(); } public void setWlcgRecord (ResourceWLCGRecord _wrec) { editor = new WLCGEditor(this, _wrec); } public ResourceWLCG(DivRep parent, Context _context, ResourceWLCGRecord _wrec) { super(parent); context = _context; setWlcgRecord (_wrec); } protected void onEvent(DivRepEvent e) { // TODO Auto-generated method stub } public void validate() { //validate WLCG interop selections redraw(); valid = true; if(!editor.isValid()) { valid = false; } } public void render(PrintWriter out) { out.print("<div id=\""+getNodeID()+"\">"); if (!hidden) { editor.render(out); } out.print("</div>"); } }
package visnode.challenge; import java.io.File; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import org.paim.commons.BinaryImage; import org.paim.commons.Image; import org.paim.commons.ImageFactory; import visnode.application.NodeNetwork; import visnode.application.parser.NodeNetworkParser; import visnode.commons.DynamicValue; import visnode.commons.MultiFileInput; import visnode.executor.OutputNode; /** * Executes the challenge comparation */ public class ChallengeComparator { /** Max image error */ private static final int MAX_ERROR = 1; /** Node network parser */ private final NodeNetworkParser parser; public ChallengeComparator() { this.parser = new NodeNetworkParser(); } /** * Execute the challenge comparation * * @param challenge * @param challengeUser * @return boolean */ public CompletableFuture<Boolean> comparate(Mission challenge, MissionUser challengeUser) { CompletableFuture<Boolean> future = new CompletableFuture(); File[] files = challenge.getInputFiles().stream().map((file) -> { return file; }).toArray(File[]::new); List<CompletableFuture<Boolean>> stream = challenge. getOutput(). stream(). map((value) -> comparate( files[challenge.getOutput().indexOf(value)], value, challengeUser )). collect(Collectors.toList()); CompletableFuture.allOf( stream.stream().toArray(CompletableFuture[]::new) ).thenAccept((accepted) -> { future.complete(!stream.stream(). filter((ft) -> !ft.join()). findFirst(). isPresent()); }); return future; } /** * Execute the challenge comparation * * @param challengeValue * @param challengeUser * @return boolean */ private CompletableFuture<Boolean> comparate(File input, MissionValue challengeValue, MissionUser challengeUser) { CompletableFuture<Boolean> future = new CompletableFuture(); NodeNetwork nodeNetwork = parser.fromJson(challengeUser.getSubmission()); nodeNetwork.getInputNode().getOutput("image").subscribe((it) -> { nodeNetwork.setInput(new MultiFileInput(input)); OutputNode outputNode = nodeNetwork.getOutputNode(); outputNode.execute().thenAccept((output) -> { if (output == null) { future.complete(false); return; } if (challengeValue.isTypeImage()) { future.complete(comparateImage(challengeValue, output)); return; } future.complete(comprateObject(challengeValue, output)); }); }).dispose(); return future; } /** * Execute the challenge comparation to images * * @param challengeValue * @param output * @return boolean */ public boolean comparateImage(MissionValue challengeValue, DynamicValue<Object> output) { if (!output.isImage()) { return false; } Image base = ImageFactory.buildRGBImage(challengeValue.getValueBufferedImage()); Image outputImage = output.get(Image.class); int[][][] expected = base.getData(); int[][][] result = outputImage.getData(); int error = 0; int chennels = Math.min(expected.length, result.length); for (int channel = 0; channel < chennels; channel++) { for (int x = 0; x < expected[channel].length; x++) { for (int y = 0; y < expected[channel][x].length; y++) { int resultValue = result[channel][x][y]; if ((output.is(BinaryImage.class) || outputImage.getPixelValueRange().isBinary()) && resultValue == 1) { resultValue = 255; } if (Math.abs(expected[channel][x][y] - resultValue) > 30) { error++; } } } } if (error > MAX_ERROR) { return false; } return true; } /** * Execute the challenge comparation to object * * @param challangeValue * @param output * @return boolean */ private boolean comprateObject(MissionValue challangeValue, DynamicValue output) { return challangeValue.getValue().equals(String.valueOf(output.get())); } }
package edu.wpi.first.wpilibj.templates; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public final class RobotMap { /** * Signals a value that needs to be changed. Used for code for a device that * hasn't been built yet and the slot/channel for it is unknown. To find usages * of this in netbeans, right click on the variable and select "Find Usage" */ public static final int INVALID = Integer.MIN_VALUE; /** * Contains input device mappings (ex joysticks and gamepads) */ public static final class Input { private Input() {} /// Joystick port public static final int joystick = 1; } /** * Contains drive motor mappings. */ public static final class DriveMotors { private DriveMotors() {} /// Slot that motors are on public static final int slot = 1; /// left motor channel public static final int left = 1; /// right motor channel public static final int right = 2; } /** * Contains the Bridge Manipulator Arm motor */ public static final class ManipulatorMotor { private ManipulatorMotor(){} //Manipulator Arm Slot public static final int slot = 1; //Manipulator Arm channel public static final int channel = 6; } /** * Contains shooter motor mappings. */ public static final class Shooter { private Shooter() {} /// Slot that pneumatics are on public static final int pneumatics_slot = 1; /// Slot that motors are on public static final int motor_slot = 1; /// Motor 1 channel public static final int topmotor = 3; /// Motor 2 channel public static final int bottommotor = 4; /// Piston channel public static final int piston = 1; } public static final class Compressor { /// Slot for compressor and pressureSwitch public static final int compressor_slot = 1; /// Compressor channel public static final int compressor = 5; /// Pressure Switch channel public static final int pressureSwitch = 1; } }
package yanagishima.service; import com.facebook.presto.client.*; import com.google.common.collect.Lists; import io.airlift.http.client.HttpClientConfig; import io.airlift.http.client.jetty.JettyHttpClient; import io.airlift.json.JsonCodec; import io.airlift.units.DataSize; import io.airlift.units.Duration; import me.geso.tinyorm.TinyORM; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import yanagishima.config.YanagishimaConfig; import yanagishima.exception.QueryErrorException; import yanagishima.result.PrestoQueryResult; import yanagishima.row.Query; import javax.inject.Inject; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.SQLException; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static io.airlift.json.JsonCodec.jsonCodec; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.MINUTES; public class PrestoServiceImpl implements PrestoService { private static Logger LOGGER = LoggerFactory.getLogger(PrestoServiceImpl.class); private YanagishimaConfig yanagishimaConfig; private JettyHttpClient httpClient; private ExecutorService executorService = Executors.newFixedThreadPool(10); private Duration queryMaxRunTime; @Inject private TinyORM db; @Inject public PrestoServiceImpl(YanagishimaConfig yanagishimaConfig) { this.yanagishimaConfig = yanagishimaConfig; HttpClientConfig httpClientConfig = new HttpClientConfig().setConnectTimeout(new Duration(10, TimeUnit.SECONDS)); this.httpClient = new JettyHttpClient(httpClientConfig); queryMaxRunTime = new Duration(this.yanagishimaConfig.getQueryMaxRunTimeSeconds(), TimeUnit.SECONDS); } @Override public String doQueryAsync(String datasource, String query, String userName) { StatementClient client = getStatementClient(datasource, query, userName); executorService.submit(new Task(datasource, query, client)); return client.current().getId(); } public class Task implements Runnable { private String datasource; private String query; private StatementClient client; public Task(String datasource, String query, StatementClient client) { this.datasource = datasource; this.query = query; this.client = client; } @Override public void run() { try { getPrestoQueryResult(this.datasource, this.query, this.client, true); } catch (Throwable e) { LOGGER.error(e.getMessage(), e); } finally { if(this.client != null) { this.client.close(); } } } } @Override public PrestoQueryResult doQuery(String datasource, String query, String userName) throws QueryErrorException { try (StatementClient client = getStatementClient(datasource, query, userName)) { return getPrestoQueryResult(datasource, query, client, false); } } private void checkTimeout(long start, String datasource, String queryId, String query) { if(System.currentTimeMillis() - start > queryMaxRunTime.toMillis()) { String message = "Query exceeded maximum time limit of " + queryMaxRunTime; storeError(datasource, queryId, query, message); throw new RuntimeException(message); } } private PrestoQueryResult getPrestoQueryResult(String datasource, String query, StatementClient client, boolean asyncFlag) throws QueryErrorException { long start = System.currentTimeMillis(); while (client.isValid() && (client.current().getData() == null)) { client.advance(); checkTimeout(start, datasource, client.current().getId(), query); } if ((!client.isFailed()) && (!client.isGone()) && (!client.isClosed())) { QueryResults results = client.isValid() ? client.current() : client.finalResults(); String queryId = results.getId(); if (results.getColumns() == null) { throw new QueryErrorException(new SQLException(format("Query %s has no columns\n", results.getId()))); } else { PrestoQueryResult prestoQueryResult = new PrestoQueryResult(); prestoQueryResult.setQueryId(queryId); prestoQueryResult.setUpdateType(results.getUpdateType()); List<String> columns = Lists.transform(results.getColumns(), Column::getName); prestoQueryResult.setColumns(columns); List<List<String>> rowDataList = new ArrayList<List<String>>(); processData(client, datasource, queryId, query, prestoQueryResult, columns, rowDataList); prestoQueryResult.setRecords(rowDataList); if(asyncFlag) { insertQueryHistory(datasource, query, queryId); } return prestoQueryResult; } } if (client.isClosed()) { throw new RuntimeException("Query aborted by user"); } else if (client.isGone()) { throw new RuntimeException("Query is gone (server restarted?)"); } else if (client.isFailed()) { QueryResults results = client.finalResults(); storeError(datasource, results.getId(), query, results.getError().getMessage()); throw resultsException(results); } throw new RuntimeException("should not reach"); } private void storeError(String datasource, String queryId, String query, String errorMessage) { db.insert(Query.class) .value("datasource", datasource) .value("query_id", queryId) .value("fetch_result_time_string", ZonedDateTime.now().toString()) .value("query_string", query) .execute(); Path dst = getResultFilePath(datasource, queryId, true); String message = format("Query failed (#%s): %s", queryId, errorMessage); try (BufferedWriter bw = Files.newBufferedWriter(dst, StandardCharsets.UTF_8)) { bw.write(message); } catch (IOException e) { throw new RuntimeException(e); } } private void insertQueryHistory(String datasource, String query, String queryId) { db.insert(Query.class) .value("datasource", datasource) .value("query_id", queryId) .value("fetch_result_time_string", ZonedDateTime.now().toString()) .value("query_string", query) .execute(); } private void processData(StatementClient client, String datasource, String queryId, String query, PrestoQueryResult prestoQueryResult, List<String> columns, List<List<String>> rowDataList) { long start = System.currentTimeMillis(); int limit = yanagishimaConfig.getSelectLimit(); Path dst = getResultFilePath(datasource, queryId, false); int lineNumber = 0; int maxResultFileByteSize = yanagishimaConfig.getMaxResultFileByteSize(); int resultBytes = 0; try (BufferedWriter bw = Files.newBufferedWriter(dst, StandardCharsets.UTF_8)) { ObjectMapper columnsMapper = new ObjectMapper(); String columnsStr = columnsMapper.writeValueAsString(columns) + "\n"; bw.write(columnsStr); lineNumber++; while (client.isValid()) { Iterable<List<Object>> data = client.current().getData(); if (data != null) { for(List<Object> row : data) { List<String> columnDataList = new ArrayList<>(); List<Object> tmpColumnDataList = row.stream().collect(Collectors.toList()); for (Object tmpColumnData : tmpColumnDataList) { if (tmpColumnData instanceof Long) { columnDataList.add(((Long) tmpColumnData).toString()); } else { if (tmpColumnData == null) { columnDataList.add(null); } else { columnDataList.add(tmpColumnData.toString()); } } } try { ObjectMapper resultMapper = new ObjectMapper(); String resultStr = resultMapper.writeValueAsString(columnDataList) + "\n"; bw.write(resultStr); lineNumber++; resultBytes += resultStr.getBytes(StandardCharsets.UTF_8).length; if(resultBytes > maxResultFileByteSize) { String message = String.format("Result file size exceeded %s bytes. queryId=%s", maxResultFileByteSize, queryId); storeError(datasource, client.current().getId(), query, message); throw new RuntimeException(message); } } catch (IOException e) { throw new RuntimeException(e); } if (client.getQuery().toLowerCase().startsWith("show") || rowDataList.size() < limit) { rowDataList.add(columnDataList); } else { prestoQueryResult.setWarningMessage(String.format("now fetch size is %d. This is more than %d. So, fetch operation stopped.", rowDataList.size(), limit)); } } } client.advance(); checkTimeout(start, datasource, queryId, query); } } catch (IOException e) { throw new RuntimeException(e); } prestoQueryResult.setLineNumber(lineNumber); try { long size = Files.size(dst); DataSize rawDataSize = new DataSize(size, DataSize.Unit.BYTE); prestoQueryResult.setRawDataSize(rawDataSize.convertToMostSuccinctDataSize()); } catch (IOException e) { throw new RuntimeException(e); } } private Path getResultFilePath(String datasource, String queryId, boolean error) { String currentPath = new File(".").getAbsolutePath(); String yyyymmdd = queryId.substring(0, 8); File datasourceDir = new File(String.format("%s/result/%s", currentPath, datasource)); if (!datasourceDir.isDirectory()) { datasourceDir.mkdir(); } File yyyymmddDir = new File(String.format("%s/result/%s/%s", currentPath, datasource, yyyymmdd)); if (!yyyymmddDir.isDirectory()) { yyyymmddDir.mkdir(); } if(error) { return Paths.get(String.format("%s/result/%s/%s/%s.err", currentPath, datasource, yyyymmdd, queryId)); } else { return Paths.get(String.format("%s/result/%s/%s/%s.json", currentPath, datasource, yyyymmdd, queryId)); } } private StatementClient getStatementClient(String datasource, String query, String userName) { String prestoCoordinatorServer = yanagishimaConfig .getPrestoCoordinatorServer(datasource); String catalog = yanagishimaConfig.getCatalog(datasource); String schema = yanagishimaConfig.getSchema(datasource); String user = null; if(userName == null ) { user = yanagishimaConfig.getUser(); } else { user = userName; } String source = yanagishimaConfig.getSource(); JsonCodec<QueryResults> jsonCodec = jsonCodec(QueryResults.class); ClientSession clientSession = new ClientSession( URI.create(prestoCoordinatorServer), user, source, null, catalog, schema, TimeZone.getDefault().getID(), Locale.getDefault(), new HashMap<String, String>(), null, false, new Duration(2, MINUTES)); return new StatementClient(httpClient, jsonCodec, clientSession, query); } private QueryErrorException resultsException(QueryResults results) { QueryError error = results.getError(); String message = format("Query failed (#%s): %s", results.getId(), error.getMessage()); Throwable cause = (error.getFailureInfo() == null) ? null : error.getFailureInfo().toException(); return new QueryErrorException(results.getId(), error, new SQLException(message, error.getSqlState(), error.getErrorCode(), cause)); } }
package org.dita.dost.module; import static org.dita.dost.util.Constants.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageBean; import org.dita.dost.log.MessageUtils; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; import org.dita.dost.reader.DitaValReader; import org.dita.dost.reader.GenListModuleReader; import org.dita.dost.reader.GrammarPoolManager; import org.dita.dost.util.DelayConrefUtils; import org.dita.dost.util.FileUtils; import org.dita.dost.util.FilterUtils; import org.dita.dost.util.OutputUtils; import org.dita.dost.util.StringUtils; import org.dita.dost.util.TimingUtils; import org.dita.dost.util.XMLSerializer; import org.dita.dost.writer.PropertiesWriter; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * This class extends AbstractPipelineModule, used to generate map and topic * list by parsing all the refered dita files. * * @version 1.0 2004-11-25 * * @author Wu, Zhi Qiang */ final class GenMapAndTopicListModule implements AbstractPipelineModule { /** Set of all dita files */ private final Set<String> ditaSet; /** Set of all topic files */ private final Set<String> fullTopicSet; /** Set of all map files */ private final Set<String> fullMapSet; /** Set of topic files containing href */ private final Set<String> hrefTopicSet; /** Set of href topic files with anchor ID */ private final Set<String> hrefWithIDSet; /** Set of chunk topic with anchor ID */ private final Set<String> chunkTopicSet; /** Set of map files containing href */ private final Set<String> hrefMapSet; /** Set of dita files containing conref */ private final Set<String> conrefSet; /** Set of topic files containing coderef */ private final Set<String> coderefSet; /** Set of all images */ private final Set<String> imageSet; /** Set of all images used for flagging */ private final Set<String> flagImageSet; /** Set of all html files */ private final Set<String> htmlSet; /** Set of all the href targets */ private final Set<String> hrefTargetSet; /** Set of all the conref targets */ private Set<String> conrefTargetSet; /** Set of all the copy-to sources */ private Set<String> copytoSourceSet; /** Set of all the non-conref targets */ private final Set<String> nonConrefCopytoTargetSet; /** Set of sources of those copy-to that were ignored */ private final Set<String> ignoredCopytoSourceSet; /** Set of subsidiary files */ private final Set<String> subsidiarySet; /** Set of relative flag image files */ private final Set<String> relFlagImagesSet; /** Map of all copy-to (target,source) */ private Map<String, String> copytoMap; /** List of files waiting for parsing */ private final List<String> waitList; /** List of parsed files */ private final List<String> doneList; /** Set of outer dita files */ private final Set<String> outDitaFilesSet; /** Set of sources of conacion */ private final Set<String> conrefpushSet; /** Set of files containing keyref */ private final Set<String> keyrefSet; /** Set of files with "@processing-role=resource-only" */ private final Set<String> resourceOnlySet; /** Map of all key definitions */ private final Map<String, String> keysDefMap; /** Basedir for processing */ private String baseInputDir; /** Tempdir for processing */ private String tempDir; /** ditadir for processing */ private String ditaDir; private String inputFile; private String ditavalFile; private int uplevels = 0; private String prefix = ""; private DITAOTLogger logger; private GenListModuleReader reader; private boolean xmlValidate = true; private String relativeValue; private String formatRelativeValue; private String rootFile; private XMLSerializer keydef; // keydef file from keys used in schema files private XMLSerializer schemekeydef; // Added by William on 2009-06-25 for req #12014 start /** Export file */ private OutputStreamWriter export; // Added by William on 2009-06-25 for req #12014 end private final Set<String> schemeSet; private final Map<String, Set<String>> schemeDictionary; // Added by William on 2009-07-18 for req #12014 start private String transtype; // Added by William on 2009-07-18 for req #12014 end // Added by William on 2010-06-09 for bug:3013079 start private final Map<String, String> exKeyDefMap; // Added by William on 2010-06-09 for bug:3013079 end private final String moduleStartMsg = "GenMapAndTopicListModule.execute(): Starting..."; private final String moduleEndMsg = "GenMapAndTopicListModule.execute(): Execution time: "; // Added on 2010-08-24 for bug:2994593 start /** use grammar pool cache */ private boolean gramcache = true; // Added on 2010-08-24 for bug:2994593 end // Added on 2010-08-24 for bug:3086552 start private boolean setSystemid = true; // Added on 2010-08-24 for bug:3086552 end /** * Create a new instance and do the initialization. * * @throws ParserConfigurationException never throw such exception * @throws SAXException never throw such exception */ public GenMapAndTopicListModule() throws SAXException, ParserConfigurationException { ditaSet = new HashSet<String>(INT_128); fullTopicSet = new HashSet<String>(INT_128); fullMapSet = new HashSet<String>(INT_128); hrefTopicSet = new HashSet<String>(INT_128); hrefWithIDSet = new HashSet<String>(INT_128); chunkTopicSet = new HashSet<String>(INT_128); schemeSet = new HashSet<String>(INT_128); hrefMapSet = new HashSet<String>(INT_128); conrefSet = new HashSet<String>(INT_128); imageSet = new HashSet<String>(INT_128); flagImageSet = new LinkedHashSet<String>(INT_128); htmlSet = new HashSet<String>(INT_128); hrefTargetSet = new HashSet<String>(INT_128); subsidiarySet = new HashSet<String>(INT_16); waitList = new LinkedList<String>(); doneList = new LinkedList<String>(); conrefTargetSet = new HashSet<String>(INT_128); nonConrefCopytoTargetSet = new HashSet<String>(INT_128); copytoMap = new HashMap<String, String>(); copytoSourceSet = new HashSet<String>(INT_128); ignoredCopytoSourceSet = new HashSet<String>(INT_128); outDitaFilesSet = new HashSet<String>(INT_128); relFlagImagesSet = new LinkedHashSet<String>(INT_128); conrefpushSet = new HashSet<String>(INT_128); keysDefMap = new HashMap<String, String>(); exKeyDefMap = new HashMap<String, String>(); keyrefSet = new HashSet<String>(INT_128); coderefSet = new HashSet<String>(INT_128); this.schemeDictionary = new HashMap<String, Set<String>>(); // @processing-role resourceOnlySet = new HashSet<String>(INT_128); } public void setLogger(final DITAOTLogger logger) { this.logger = logger; } public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { if (logger == null) { throw new IllegalStateException("Logger not set"); } final Date startTime = TimingUtils.getNowTime(); try { logger.logInfo(moduleStartMsg); parseInputParameters(input); // set grammar pool flag GrammarPoolManager.setGramCache(gramcache); reader = new GenListModuleReader(); reader.setLogger(logger); reader.initXMLReader(ditaDir, xmlValidate, rootFile, setSystemid); // Added on 2010-08-24 for bug:3086552 start DitaValReader.initXMLReader(setSystemid); // Added on 2010-08-24 for bug:3086552 end // first parse filter file for later use parseFilterFile(); addToWaitList(inputFile); processWaitList(); // Depreciated function // The base directory does not change according to the referenceing // topic files in the new resolution updateBaseDirectory(); refactoringResult(); outputResult(); keydef.writeEndDocument(); keydef.close(); schemekeydef.writeEndDocument(); schemekeydef.close(); // Added by William on 2009-06-25 for req #12014 start // write the end tag export.write("</stub>"); // close the steam export.close(); // Added by William on 2009-06-25 for req #12014 end } catch (final DITAOTException e) { throw e; } catch (final SAXException e) { throw new DITAOTException(e.getMessage(), e); } catch (final Exception e) { throw new DITAOTException(e.getMessage(), e); } finally { logger.logInfo(moduleEndMsg + TimingUtils.reportElapsedTime(startTime)); } return null; } private void parseInputParameters(final AbstractPipelineInput input) { final String basedir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR); final String ditaInput = input.getAttribute(ANT_INVOKER_PARAM_INPUTMAP); tempDir = input.getAttribute(ANT_INVOKER_PARAM_TEMPDIR); ditaDir = input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR); ditavalFile = input.getAttribute(ANT_INVOKER_PARAM_DITAVAL); xmlValidate = Boolean.valueOf(input.getAttribute(ANT_INVOKER_EXT_PARAM_VALIDATE)); // Added by William on 2009-07-18 for req #12014 start // get transtype transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE); // Added by William on 2009-07-18 for req #12014 start gramcache = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAM_GRAMCACHE)); setSystemid = "yes".equalsIgnoreCase(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID)); // For the output control OutputUtils.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER)); OutputUtils.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL)); OutputUtils.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP)); // Set the OutputDir final File path = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR)); if (path.isAbsolute()) { OutputUtils.setOutputDir(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR)); } else { final StringBuffer buff = new StringBuffer(input.getAttribute(ANT_INVOKER_PARAM_BASEDIR)).append( File.separator).append(path); OutputUtils.setOutputDir(buff.toString()); } // Resolve relative paths base on the basedir. File inFile = new File(ditaInput); if (!inFile.isAbsolute()) { inFile = new File(basedir, ditaInput); } if (!new File(tempDir).isAbsolute()) { tempDir = new File(basedir, tempDir).getAbsolutePath(); } else { tempDir = FileUtils.removeRedundantNames(tempDir); } if (!new File(ditaDir).isAbsolute()) { ditaDir = new File(basedir, ditaDir).getAbsolutePath(); } else { ditaDir = FileUtils.removeRedundantNames(ditaDir); } if (ditavalFile != null && !new File(ditavalFile).isAbsolute()) { ditavalFile = new File(basedir, ditavalFile).getAbsolutePath(); } baseInputDir = new File(inFile.getAbsolutePath()).getParent(); baseInputDir = FileUtils.removeRedundantNames(baseInputDir); rootFile = inFile.getAbsolutePath(); rootFile = FileUtils.removeRedundantNames(rootFile); inputFile = inFile.getName(); try { keydef = XMLSerializer.newInstance(new FileOutputStream(new File(tempDir, "keydef.xml"))); keydef.writeStartDocument(); keydef.writeStartElement("stub"); // Added by William on 2009-06-09 for scheme key bug // create the keydef file for scheme files schemekeydef = XMLSerializer.newInstance(new FileOutputStream(new File(tempDir, "schemekeydef.xml"))); schemekeydef.writeStartDocument(); schemekeydef.writeStartElement("stub"); // Added by William on 2009-06-25 for req #12014 start // create the export file for exportanchors // write the head export = new OutputStreamWriter(new FileOutputStream(new File(tempDir, FILE_NAME_EXPORT_XML))); export.write(XML_HEAD); export.write("<stub>"); // Added by William on 2009-06-25 for req #12014 end } catch (final FileNotFoundException e) { logger.logException(e); } catch (final IOException e) { logger.logException(e); } catch (final SAXException e) { logger.logException(e); } // Set the mapDir OutputUtils.setInputMapPathName(inFile.getAbsolutePath()); } private void processWaitList() throws DITAOTException { // Added by William on 2009-07-18 for req #12014 start reader.setTranstype(transtype); // Added by William on 2009-07-18 for req #12014 end if (FileUtils.isDITAMapFile(inputFile)) { reader.setPrimaryDitamap(inputFile); } while (!waitList.isEmpty()) { processFile(waitList.remove(0)); } } private void processFile(String currentFile) throws DITAOTException { File fileToParse; final File file = new File(currentFile); if (file.isAbsolute()) { fileToParse = file; currentFile = FileUtils.getRelativePathFromMap(rootFile, currentFile); } else { fileToParse = new File(baseInputDir, currentFile); } logger.logInfo("Processing " + fileToParse.getAbsolutePath()); String msg = null; final Properties params = new Properties(); params.put("%1", currentFile); try { fileToParse = fileToParse.getCanonicalFile(); if (FileUtils.isValidTarget(currentFile.toLowerCase())) { reader.setTranstype(transtype); reader.setCurrentDir(new File(currentFile).getParent()); reader.parse(fileToParse); } else { // edited by Alan on Date:2009-11-02 for Work Item:#1590 start // logger.logWarn("Input file name is not valid DITA file name."); final Properties prop = new Properties(); prop.put("%1", fileToParse); logger.logWarn(MessageUtils.getMessage("DOTJ021W", params).toString()); // edited by Alan on Date:2009-11-02 for Work Item:#1590 end } // don't put it into dita.list if it is invalid if (reader.isValidInput()) { processParseResult(currentFile); categorizeCurrentFile(currentFile); } else if (!currentFile.equals(inputFile)) { logger.logWarn(MessageUtils.getMessage("DOTJ021W", params).toString()); } } catch (final SAXParseException sax) { // To check whether the inner third level is DITAOTBuildException // :FATALERROR final Exception inner = sax.getException(); if (inner != null && inner instanceof DITAOTException) {// second // level logger.logInfo(inner.getMessage()); throw (DITAOTException) inner; } if (currentFile.equals(inputFile)) { // stop the build if exception thrown when parsing input file. final MessageBean msgBean = MessageUtils.getMessage("DOTJ012F", params); msg = MessageUtils.getMessage("DOTJ012F", params).toString(); msg = new StringBuffer(msg).append(":").append(sax.getMessage()).toString(); throw new DITAOTException(msgBean, sax, msg); } final StringBuffer buff = new StringBuffer(); msg = MessageUtils.getMessage("DOTJ013E", params).toString(); buff.append(msg).append(LINE_SEPARATOR).append(sax.getMessage()); logger.logError(buff.toString()); } catch (final Exception e) { if (currentFile.equals(inputFile)) { // stop the build if exception thrown when parsing input file. final MessageBean msgBean = MessageUtils.getMessage("DOTJ012F", params); msg = MessageUtils.getMessage("DOTJ012F", params).toString(); msg = new StringBuffer(msg).append(":").append(e.getMessage()).toString(); throw new DITAOTException(msgBean, e, msg); } final StringBuffer buff = new StringBuffer(); msg = MessageUtils.getMessage("DOTJ013E", params).toString(); buff.append(msg).append(LINE_SEPARATOR).append(e.getMessage()); logger.logError(buff.toString()); } if (!reader.isValidInput() && currentFile.equals(inputFile)) { if (xmlValidate == true) { // stop the build if all content in the input file was filtered // out. msg = MessageUtils.getMessage("DOTJ022F", params).toString(); throw new DITAOTException(msg); } else { // stop the build if the content of the file is not valid. msg = MessageUtils.getMessage("DOTJ034F", params).toString(); throw new DITAOTException(msg); } } doneList.add(currentFile); reader.reset(); } private void processParseResult(String currentFile) { Iterator<String> iter = reader.getNonCopytoResult().iterator(); final Map<String, String> cpMap = reader.getCopytoMap(); final Map<String, String> kdMap = reader.getKeysDMap(); // Added by William on 2010-06-09 for bug:3013079 start // the reader's reset method will clear the map. final Map<String, String> exKdMap = reader.getExKeysDefMap(); exKeyDefMap.putAll(exKdMap); // Added by William on 2010-06-09 for bug:3013079 end // Category non-copyto result and update uplevels accordingly while (iter.hasNext()) { final String file = iter.next(); categorizeResultFile(file); updateUplevels(file); } // Update uplevels for copy-to targets, and store copy-to map. // Note: same key(target) copy-to will be ignored. iter = cpMap.keySet().iterator(); while (iter.hasNext()) { final String key = iter.next(); final String value = cpMap.get(key); if (copytoMap.containsKey(key)) { // edited by Alan on Date:2009-11-02 for Work Item:#1590 start /* * StringBuffer buff = new StringBuffer(); * buff.append("Copy-to task [href=\""); buff.append(value); * buff.append("\" copy-to=\""); buff.append(key); * buff.append("\"] which points to another copy-to target"); * buff.append(" was ignored."); * logger.logWarn(buff.toString()); */ final Properties prop = new Properties(); prop.setProperty("%1", value); prop.setProperty("%2", key); logger.logWarn(MessageUtils.getMessage("DOTX065W", prop).toString()); // edited by Alan on Date:2009-11-02 for Work Item:#1590 end ignoredCopytoSourceSet.add(value); } else { updateUplevels(key); copytoMap.put(key, value); } } // TODO Added by William on 2009-06-09 for scheme key bug(497) schemeSet.addAll(reader.getSchemeRefSet()); /** * collect key definitions */ iter = kdMap.keySet().iterator(); while (iter.hasNext()) { final String key = iter.next(); final String value = kdMap.get(key); if (keysDefMap.containsKey(key)) { // if there already exists duplicated key definition in // different map files. // Should only emit this if in a debug mode; comment out for now /* * Properties prop = new Properties(); prop.put("%1", key); * prop.put("%2", value); prop.put("%3", currentFile); logger * .logInfo(MessageUtils.getMessage("DOTJ048I", * prop).toString()); */ } else { updateUplevels(key); // add the ditamap where it is defined. /* * try { keydef.write("<keydef "); * keydef.write("keys=\""+key+"\" "); * keydef.write("href=\""+value+"\" "); * keydef.write("source=\""+currentFile+"\"/>"); * keydef.write("\n"); keydef.flush(); } catch (IOException e) { * * logger.logException(e); } */ keysDefMap.put(key, value + "(" + currentFile + ")"); } // TODO Added by William on 2009-06-09 for scheme key bug(532-547) // if the current file is also a schema file if (schemeSet.contains(currentFile)) { // write the keydef into the scheme keydef file try { schemekeydef.writeStartElement("keydef"); schemekeydef.writeAttribute("keys", key); schemekeydef.writeAttribute("href", value); schemekeydef.writeAttribute("source", currentFile); schemekeydef.writeEndElement(); } catch (final SAXException e) { logger.logException(e); } } } hrefTargetSet.addAll(reader.getHrefTargets()); hrefWithIDSet.addAll(reader.getHrefTopicSet()); chunkTopicSet.addAll(reader.getChunkTopicSet()); // schemeSet.addAll(reader.getSchemeRefSet()); conrefTargetSet.addAll(reader.getConrefTargets()); nonConrefCopytoTargetSet.addAll(reader.getNonConrefCopytoTargets()); ignoredCopytoSourceSet.addAll(reader.getIgnoredCopytoSourceSet()); subsidiarySet.addAll(reader.getSubsidiaryTargets()); outDitaFilesSet.addAll(reader.getOutFilesSet()); resourceOnlySet.addAll(reader.getResourceOnlySet()); // Generate topic-scheme dictionary if (reader.getSchemeSet() != null && reader.getSchemeSet().size() > 0) { Set<String> children = null; children = this.schemeDictionary.get(currentFile); if (children == null) { children = new HashSet<String>(); } children.addAll(reader.getSchemeSet()); // for Linux support currentFile = currentFile.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); this.schemeDictionary.put(currentFile, children); final Set<String> hrfSet = reader.getHrefTargets(); final Iterator<String> it = hrfSet.iterator(); while (it.hasNext()) { String filename = it.next(); // for Linux support filename = filename.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); children = this.schemeDictionary.get(filename); if (children == null) { children = new HashSet<String>(); } children.addAll(reader.getSchemeSet()); this.schemeDictionary.put(filename, children); } } } private void categorizeCurrentFile(final String currentFile) { final String lcasefn = currentFile.toLowerCase(); ditaSet.add(currentFile); if (FileUtils.isTopicFile(currentFile)) { hrefTargetSet.add(currentFile); } if (reader.hasConaction()) { conrefpushSet.add(currentFile); } if (reader.hasConRef()) { conrefSet.add(currentFile); } if (reader.hasKeyRef()) { keyrefSet.add(currentFile); } if (reader.hasCodeRef()) { coderefSet.add(currentFile); } if (FileUtils.isDITATopicFile(lcasefn)) { fullTopicSet.add(currentFile); if (reader.hasHref()) { hrefTopicSet.add(currentFile); } } if (FileUtils.isDITAMapFile(lcasefn)) { fullMapSet.add(currentFile); if (reader.hasHref()) { hrefMapSet.add(currentFile); } } } private void categorizeResultFile(String file) { // edited by william on 2009-08-06 for bug:2832696 start String lcasefn = null; String format = null; // has format attribute set if (file.contains(STICK)) { // get lower case file name lcasefn = file.substring(0, file.indexOf(STICK)).toLowerCase(); // get format attribute format = file.substring(file.indexOf(STICK) + 1); file = file.substring(0, file.indexOf(STICK)); } else { lcasefn = file.toLowerCase(); } // Added by William on 2010-03-04 for bug:2957938 start // avoid files referred by coderef being added into wait list if (subsidiarySet.contains(lcasefn)) { return; } // Added by William on 2010-03-04 for bug:2957938 end if (FileUtils.isDITAFile(lcasefn) && (format == null || ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(format) || ATTR_FORMAT_VALUE_DITAMAP .equalsIgnoreCase(format))) { addToWaitList(file); } else if (!FileUtils.isSupportedImageFile(lcasefn)) { htmlSet.add(file); } // edited by william on 2009-08-06 for bug:2832696 end if (FileUtils.isSupportedImageFile(lcasefn)) { imageSet.add(file); } if (FileUtils.isHTMLFile(lcasefn) || FileUtils.isResourceFile(lcasefn)) { htmlSet.add(file); } } /** * Update uplevels if needed. * * @param file */ private void updateUplevels(String file) { // Added by william on 2009-08-06 for bug:2832696 start if (file.contains(STICK)) { file = file.substring(0, file.indexOf(STICK)); } // Added by william on 2009-08-06 for bug:2832696 end // for uplevels (../../) // modified start by wxzhang 20070518 final int lastIndex = FileUtils.removeRedundantNames(file).replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR) .lastIndexOf("../"); // modified end by wxzhang 20070518 if (lastIndex != -1) { final int newUplevels = lastIndex / 3 + 1; uplevels = newUplevels > uplevels ? newUplevels : uplevels; } } /** * Add the given file the wait list if it has not been parsed. * * @param file */ private void addToWaitList(final String file) { if (doneList.contains(file) || waitList.contains(file)) { return; } waitList.add(file); } private void updateBaseDirectory() { baseInputDir = new File(baseInputDir).getAbsolutePath(); for (int i = uplevels; i > 0; i final File file = new File(baseInputDir); baseInputDir = file.getParent(); prefix = new StringBuffer(file.getName()).append(File.separator).append(prefix).toString(); } } private String getUpdateLevels() { int current = uplevels; final StringBuffer buff = new StringBuffer(); while (current > 0) { buff.append(".." + FILE_SEPARATOR); current } return buff.toString(); } /** * Escape regular expression special characters. * * @param value input * @return input with regular expression special characters escaped */ private String formatRelativeValue(final String value) { final StringBuffer buff = new StringBuffer(); if (value == null || value.length() == 0) { return ""; } int index = 0; while (index < value.length()) { final char current = value.charAt(index); switch (current) { case '.': buff.append("\\."); break; // case '/': // case '|': case '\\': buff.append("[\\\\|/]"); break; case '(': buff.append("\\("); break; case ')': buff.append("\\)"); break; case '[': buff.append("\\["); break; case ']': buff.append("\\]"); break; case '{': buff.append("\\{"); break; case '}': buff.append("\\}"); break; case '^': buff.append("\\^"); break; case '+': buff.append("\\+"); break; case '$': buff.append("\\$"); break; default: buff.append(current); } index++; } return buff.toString(); } private void parseFilterFile() { if (ditavalFile != null) { final DitaValReader ditaValReader = new DitaValReader(); ditaValReader.setLogger(logger); ditaValReader.read(ditavalFile); // Store filter map for later use FilterUtils.setFilterMap(ditaValReader.getFilterMap()); // Store flagging image used for image copying flagImageSet.addAll(ditaValReader.getImageList()); relFlagImagesSet.addAll(ditaValReader.getRelFlagImageList()); } else { FilterUtils.setFilterMap(null); } } private void refactoringResult() { handleConref(); handleCopyto(); } private void handleCopyto() { final Map<String, String> tempMap = new HashMap<String, String>(); final Set<String> pureCopytoSources = new HashSet<String>(INT_128); final Set<String> totalCopytoSources = new HashSet<String>(INT_128); // Validate copy-to map, remove those without valid sources Iterator<String> iter = copytoMap.keySet().iterator(); while (iter.hasNext()) { final String key = iter.next(); final String value = copytoMap.get(key); if (new File(baseInputDir + File.separator + prefix, value).exists()) { tempMap.put(key, value); // Add the copy-to target to conreflist when its source has // conref if (conrefSet.contains(value)) { conrefSet.add(key); } } } copytoMap = tempMap; // Add copy-to targets into ditaSet, fullTopicSet ditaSet.addAll(copytoMap.keySet()); fullTopicSet.addAll(copytoMap.keySet()); // Get pure copy-to sources totalCopytoSources.addAll(copytoMap.values()); totalCopytoSources.addAll(ignoredCopytoSourceSet); iter = totalCopytoSources.iterator(); while (iter.hasNext()) { final String src = iter.next(); if (!nonConrefCopytoTargetSet.contains(src) && !copytoMap.keySet().contains(src)) { pureCopytoSources.add(src); } } copytoSourceSet = pureCopytoSources; // Remove pure copy-to sources from ditaSet, fullTopicSet ditaSet.removeAll(pureCopytoSources); fullTopicSet.removeAll(pureCopytoSources); } private void handleConref() { // Get pure conref targets final Set<String> pureConrefTargets = new HashSet<String>(INT_128); final Iterator<String> iter = conrefTargetSet.iterator(); while (iter.hasNext()) { final String target = iter.next(); if (!nonConrefCopytoTargetSet.contains(target)) { pureConrefTargets.add(target); } } conrefTargetSet = pureConrefTargets; // Remove pure conref targets from ditaSet, fullTopicSet ditaSet.removeAll(pureConrefTargets); fullTopicSet.removeAll(pureConrefTargets); } private void outputResult() throws DITAOTException { final Properties prop = new Properties(); final PropertiesWriter writer = new PropertiesWriter(); final Content content = new ContentImpl(); final File outputFile = new File(tempDir, FILE_NAME_DITA_LIST); final File xmlDitalist = new File(tempDir, FILE_NAME_DITA_LIST_XML); final File dir = new File(tempDir); final Set<String> copytoSet = new HashSet<String>(INT_128); final Set<String> keysDefSet = new HashSet<String>(INT_128); Iterator<Entry<String, String>> iter = null; if (!dir.exists()) { dir.mkdirs(); } prop.put("user.input.dir", baseInputDir); prop.put("user.input.file", prefix + inputFile); prop.put("user.input.file.listfile", "usr.input.file.list"); final File inputfile = new File(tempDir, "usr.input.file.list"); Writer bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputfile))); bufferedWriter.write(prefix + inputFile); bufferedWriter.flush(); } catch (final FileNotFoundException e) { logger.logException(e); } catch (final IOException e) { logger.logException(e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (final IOException e) { logger.logException(e); } } } // add out.dita.files,tempdirToinputmapdir.relative.value to solve the // output problem relativeValue = prefix; formatRelativeValue = formatRelativeValue(relativeValue); prop.put("tempdirToinputmapdir.relative.value", formatRelativeValue); prop.put("uplevels", getUpdateLevels()); addSetToProperties(prop, OUT_DITA_FILES_LIST, outDitaFilesSet); addSetToProperties(prop, FULL_DITAMAP_TOPIC_LIST, ditaSet); addSetToProperties(prop, FULL_DITA_TOPIC_LIST, fullTopicSet); addSetToProperties(prop, FULL_DITAMAP_LIST, fullMapSet); addSetToProperties(prop, HREF_DITA_TOPIC_LIST, hrefTopicSet); addSetToProperties(prop, CONREF_LIST, conrefSet); addSetToProperties(prop, IMAGE_LIST, imageSet); addSetToProperties(prop, FLAG_IMAGE_LIST, flagImageSet); addSetToProperties(prop, HTML_LIST, htmlSet); addSetToProperties(prop, HREF_TARGET_LIST, hrefTargetSet); addSetToProperties(prop, HREF_TOPIC_LIST, hrefWithIDSet); addSetToProperties(prop, CHUNK_TOPIC_LIST, chunkTopicSet); addSetToProperties(prop, SUBJEC_SCHEME_LIST, schemeSet); addSetToProperties(prop, CONREF_TARGET_LIST, conrefTargetSet); addSetToProperties(prop, COPYTO_SOURCE_LIST, copytoSourceSet); addSetToProperties(prop, SUBSIDIARY_TARGET_LIST, subsidiarySet); addSetToProperties(prop, CONREF_PUSH_LIST, conrefpushSet); addSetToProperties(prop, KEYREF_LIST, keyrefSet); addSetToProperties(prop, CODEREF_LIST, coderefSet); // @processing-role addSetToProperties(prop, RESOURCE_ONLY_LIST, resourceOnlySet); addFlagImagesSetToProperties(prop, REL_FLAGIMAGE_LIST, relFlagImagesSet); // Convert copyto map into set and output iter = copytoMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, String> entry = iter.next(); copytoSet.add(entry.toString()); } iter = keysDefMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, String> entry = iter.next(); keysDefSet.add(entry.toString()); } addSetToProperties(prop, COPYTO_TARGET_TO_SOURCE_MAP_LIST, copytoSet); addSetToProperties(prop, KEY_LIST, keysDefSet); content.setValue(prop); writer.setContent(content); writer.write(outputFile.getAbsolutePath()); writer.writeToXML(xmlDitalist.getAbsolutePath()); // Output relation-graph writeMapToXML(reader.getRelationshipGrap(), FILE_NAME_SUBJECT_RELATION); // Output topic-scheme dictionary writeMapToXML(this.schemeDictionary, FILE_NAME_SUBJECT_DICTIONARY); // added by Willam on 2009-07-17 for req #12014 start if (INDEX_TYPE_ECLIPSEHELP.equals(transtype)) { // Output plugin id final File pluginIdFile = new File(tempDir, FILE_NAME_PLUGIN_XML); DelayConrefUtils.getInstance().writeMapToXML(reader.getPluginMap(), pluginIdFile); // write the result into the file final StringBuffer result = reader.getResult(); try { export.write(result.toString()); } catch (final IOException e) { logger.logException(e); } } // added by Willam on 2009-07-17 for req #12014 end } private void writeMapToXML(final Map<String, Set<String>> m, final String filename) { if (m == null) { return; } final Properties prop = new Properties(); final Iterator<Map.Entry<String, Set<String>>> iter = m.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, Set<String>> entry = iter.next(); final String key = entry.getKey(); final String value = StringUtils.assembleString(entry.getValue(), COMMA); prop.setProperty(key, value); } final File outputFile = new File(tempDir, filename); OutputStream os = null; try { os = new FileOutputStream(outputFile); prop.storeToXML(os, null); os.close(); } catch (final IOException e) { this.logger.logException(e); } finally { if (os != null) { try { os.close(); } catch (final Exception e) { logger.logException(e); } } } } private void addSetToProperties(final Properties prop, final String key, final Set<String> set) { String value = null; final Set<String> newSet = new LinkedHashSet<String>(INT_128); final Iterator<String> iter = set.iterator(); while (iter.hasNext()) { final String file = iter.next(); if (new File(file).isAbsolute()) { // no need to append relative path before absolute paths newSet.add(FileUtils.removeRedundantNames(file)); } else { // In ant, all the file separator should be slash, so we need to // replace all the back slash with slash. final int index = file.indexOf(EQUAL); if (index != -1) { // keyname final String to = file.substring(0, index); final String source = file.substring(index + 1); // TODO Added by William on 2009-05-14 for keyref bug start // When generating key.list if (KEY_LIST.equals(key)) { final StringBuilder repStr = new StringBuilder(); repStr.append(FileUtils.removeRedundantNames(prefix + to) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); repStr.append(EQUAL); // cases where keymap is in map ancestor folder if (source.substring(0, 1).equals(LEFT_BRACKET)) { repStr.append(FileUtils.removeRedundantNames(prefix) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); repStr.append(LEFT_BRACKET); repStr.append(FileUtils.removeRedundantNames(source.substring(1, source.length() - 1)) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); repStr.append(RIGHT_BRACKET); } else { repStr.append(FileUtils.removeRedundantNames(prefix + source) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); } StringBuffer result = new StringBuffer(repStr); // move the prefix position // maps/target_topic_1=topics/target-topic-a.xml(root-map-01.ditamap)--> // target_topic_1=topics/target-topic-a.xml(maps/root-map-01.ditamap) if (!"".equals(prefix)) { final String prefix1 = prefix.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR); if (repStr.indexOf(prefix1) != -1) { result = new StringBuffer(); result.append(repStr.substring(prefix1.length())); result.insert(result.lastIndexOf(LEFT_BRACKET) + 1, prefix1); // Added by William on 2010-06-08 for bug:3013079 start // if this key definition refer to a external resource if (exKeyDefMap.containsKey(to)) { final int pos = result.indexOf(prefix1); result.delete(pos, pos + prefix1.length()); } // Added by William on 2010-06-08 for bug:3013079 end newSet.add(result.toString()); } } else { // no prefix newSet.add(result.toString()); } // TODO Added by William on 2009-05-14 for keyref bug end // Added by William on 2010-06-10 for bug:3013545 start writeKeyDef(to, result); // Added by William on 2010-06-10 for bug:3013545 end } else { // other case do nothing newSet.add(FileUtils.removeRedundantNames(new StringBuffer(prefix).append(to).toString()) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR) + EQUAL + FileUtils.removeRedundantNames(new StringBuffer(prefix).append(source).toString()) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); } } else { newSet.add(FileUtils.removeRedundantNames(new StringBuffer(prefix).append(file).toString()) .replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR)); } } } /* * write filename in the list to a file, in order to use the * includesfile attribute in ant script */ final String fileKey = key.substring(0, key.lastIndexOf("list")) + "file"; prop.put(fileKey, key.substring(0, key.lastIndexOf("list")) + ".list"); final File list = new File(tempDir, prop.getProperty(fileKey)); Writer bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(list))); final Iterator<String> it = newSet.iterator(); while (it.hasNext()) { bufferedWriter.write(it.next()); if (it.hasNext()) { bufferedWriter.write("\n"); } } bufferedWriter.flush(); bufferedWriter.close(); } catch (final FileNotFoundException e) { logger.logException(e); } catch (final IOException e) { logger.logException(e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (final IOException e) { logger.logException(e); } } } value = StringUtils.assembleString(newSet, COMMA); prop.put(key, value); // clear set set.clear(); newSet.clear(); } // Added by William on 2010-06-10 for bug:3013545 start /** * Write keydef into keydef.xml. * * @param keyName key name. * @param result keydef. */ private void writeKeyDef(final String keyName, final StringBuffer result) { try { final int equalIndex = result.indexOf(EQUAL); final int leftBracketIndex = result.lastIndexOf(LEFT_BRACKET); final int rightBracketIndex = result.lastIndexOf(RIGHT_BRACKET); // get href final String href = result.substring(equalIndex + 1, leftBracketIndex); // get source file final String sourcefile = result.substring(leftBracketIndex + 1, rightBracketIndex); keydef.writeStartElement("keydef"); keydef.writeAttribute("keys", keyName); keydef.writeAttribute("href", href); keydef.writeAttribute("source", sourcefile); keydef.writeEndElement(); } catch (final SAXException e) { logger.logException(e); } } // Added by William on 2010-06-10 for bug:3013545 end /** * add FlagImangesSet to Properties, which needn't to change the dir level, * just ouput to the ouput dir. * * @param prop * @param key * @param set */ private void addFlagImagesSetToProperties(final Properties prop, final String key, final Set<String> set) { String value = null; final Set<String> newSet = new LinkedHashSet<String>(INT_128); final Iterator<String> iter = set.iterator(); while (iter.hasNext()) { final String file = iter.next(); if (new File(file).isAbsolute()) { // no need to append relative path before absolute paths newSet.add(FileUtils.removeRedundantNames(file)); } else { // In ant, all the file separator should be slash, so we need to // replace all the back slash with slash. newSet.add(FileUtils.removeRedundantNames(new StringBuffer().append(file).toString()).replace( WINDOWS_SEPARATOR, UNIX_SEPARATOR)); } } // write list attribute to file final String fileKey = key.substring(0, key.lastIndexOf("list")) + "file"; prop.put(fileKey, key.substring(0, key.lastIndexOf("list")) + ".list"); final File list = new File(tempDir, prop.getProperty(fileKey)); Writer bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(list))); final Iterator<String> it = newSet.iterator(); while (it.hasNext()) { bufferedWriter.write(it.next()); if (it.hasNext()) { bufferedWriter.write("\n"); } } bufferedWriter.flush(); bufferedWriter.close(); } catch (final FileNotFoundException e) { logger.logException(e); } catch (final IOException e) { logger.logException(e); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (final IOException e) { logger.logException(e); } } } value = StringUtils.assembleString(newSet, COMMA); prop.put(key, value); // clear set set.clear(); newSet.clear(); } }
/** * @authors Tanner Glantz and Brett Phillips * @version 02/27/2016 * Description: The MainGUI class creates the Connect 4 game board * Course: ISTE-121 */ //imports the necesary classes for GUI program. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; public class MainGUI { private JFrame frame; private JMenuBar menuBar; private JMenu fileMenu; private JMenu helpMenu; private JMenuItem newGame; private JMenuItem exitMenu; private JMenuItem instructions; private JPanel mainPanel; private JPanel panel; private JPanel buttonPanel; private JButton colButton1; private JButton colButton2; private JButton colButton3; private JButton colButton4; private JButton colButton5; private JButton colButton6; private JButton colButton7; private static final int PANNEL_WIDTH = 700; private static final int PANNEL_HEIGHT = 670; private ArrayList col1 = new ArrayList(); private ArrayList col2 = new ArrayList(); private ArrayList col3 = new ArrayList(); private ArrayList col4 = new ArrayList(); private ArrayList col5 = new ArrayList(); private ArrayList col6 = new ArrayList(); private ArrayList col7 = new ArrayList(); private Icon theBoard = new ImageIcon("grid.png"); private Icon yellow = new ImageIcon("yellowpiece.png"); private Icon red = new ImageIcon("redpiece.png"); public MainGUI() { frame = new JFrame(); frame.setSize(PANNEL_WIDTH, PANNEL_HEIGHT); frame.setTitle("Connect 4"); frame.setLayout(new BorderLayout()); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); EventListener al = new EventListener(); menuBar = new JMenuBar(); fileMenu = new JMenu("File"); newGame = new JMenuItem("New Game"); newGame.addActionListener(al); exitMenu = new JMenuItem("Exit"); exitMenu.addActionListener(al); fileMenu.add(newGame); fileMenu.add(exitMenu); helpMenu = new JMenu("Help"); instructions = new JMenuItem("Instructions"); instructions.addActionListener(al); helpMenu.add(instructions); menuBar.add(fileMenu); menuBar.add(helpMenu); buttonPanel = new JPanel(new FlowLayout(0,23,0)); colButton1 = new JButton("1"); colButton2 = new JButton("2"); colButton3 = new JButton("3"); colButton4 = new JButton("4"); colButton5 = new JButton("5"); colButton6 = new JButton("6"); colButton7 = new JButton("7"); colButton1.addActionListener(al); colButton2.addActionListener(al); colButton3.addActionListener(al); colButton4.addActionListener(al); colButton5.addActionListener(al); colButton6.addActionListener(al); colButton7.addActionListener(al); buttonPanel.add(colButton1); buttonPanel.add(colButton2); buttonPanel.add(colButton3); buttonPanel.add(colButton4); buttonPanel.add(colButton5); buttonPanel.add(colButton6); buttonPanel.add(colButton7); panel = new JPanel(new BorderLayout()); panel.add(new Board()); mainPanel = new JPanel(new BorderLayout()); mainPanel.add(buttonPanel, BorderLayout.NORTH); mainPanel.add(panel,BorderLayout.CENTER); frame.add(menuBar, BorderLayout.NORTH); frame.add(mainPanel, BorderLayout.CENTER); frame.setVisible(true); } public static void main(String[] args) { MainGUI game = new MainGUI(); } public void exitProgram() { System.exit(0); } class EventListener extends JPanel implements ActionListener { private String instructionsDialog = "Game Description:\n\tConnect 4 is a two player game in which players attempt to align their colored chips four in a row.\nPlayers place their chips into the top of the board, which then fall to the lowest available spot in that column.\nPlayers place one chip per turn. The goal of the game is to align four of your chips in either horizontal, diagonal, or vertical alignment.\nThe first person to align their chips in the ways described above, is the winner.\n\nThe design of this game is close to that of the traditional version of this game.\n\n\tGame URL: https://en.wikipedia.org/wiki/Connect_Four"; public EventListener() { } /* public void addPiece(String arrayListName){ arrayListName.add(); }*/ public void actionPerformed(ActionEvent e) { String actionString = e.getActionCommand(); if (actionString.equals("New Game")) { } else if (actionString.equals("Exit")) { exitProgram(); } else if (actionString.equals("Instructions")) { JOptionPane.showMessageDialog(frame, instructionsDialog); } else if(actionString.equals("1")) { } else if(actionString.equals("2")) { } else if(actionString.equals("3")) { } else if(actionString.equals("4")) { } else if(actionString.equals("5")) { } else if(actionString.equals("6")) { } } } class Board extends JPanel{ public Board(){ } protected void paintComponent(Graphics g) { super.paintComponent(g); for(int i = 100; i<=600; i+=100){ g.drawLine(i,0, i, PANNEL_HEIGHT); } for(int i = 0; i<=500; i+=100){ g.drawLine(0,i,PANNEL_WIDTH,i); } theBoard.paintIcon(this, g, 0, 0); } } }
package org.fusfoundation.kranion; import java.beans.PropertyChangeEvent; import java.io.ByteArrayOutputStream; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Observer; import javax.swing.JFileChooser; import org.fusfoundation.kranion.model.image.ImageVolume; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.glBindBufferBase; import static org.lwjgl.opengl.GL43.GL_COMPUTE_SHADER; import static org.lwjgl.opengl.GL43.GL_SHADER_STORAGE_BUFFER; import org.lwjgl.util.vector.*; import org.fusfoundation.kranion.model.image.*; /** * * @author john */ public class TransducerRayTracer extends Renderable implements Pickable { private Vector3f steering = new Vector3f(0f, 0f, 0f); private float boneThreshold = /*1024f +*/ 700f; // 700 HU threshold for bone private static ShaderProgram refractShader; private static ShaderProgram sdrShader; private static ShaderProgram pressureShader; private static ShaderProgram pickShader; private int posSSBo=0; // buffer of element starting center points private int colSSBo=0; // buffer of color data per element private int outSSBo=0; // buffer of 6 vertices per element indicating beam path (3 line segments) private int distSSBo=0; // buffer containing minimum distance from focal spot per element private int outDiscSSBo = 0; // buffer of triangle vertices for 'discs' on skull surface private int outRaysSSBo = 0; // buffer of lines from element start point to outside of skull // skull floor strike data private int skullFloorRaysSSBo = 0; private int skullFloorDiscSSBo = 0; private int envSSBo = 0; // buffer for treatment envelope data (21x21x21 volume of active element counts) private int sdrSSBo = 0; // buffer of houdsfield values along the path between outside and inside of skull per element private int pressureSSBo = 0; // buffer of pressure contributions per ray to a given sample point private int phaseSSBo =0; private Trackball trackball = null; private Vector3f centerOfRotation; private ImageVolume CTimage = null; public FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); public Matrix4f ctTexMatrix = new Matrix4f(); public FloatBuffer normMatrixBuf = BufferUtils.createFloatBuffer(16); private int selectedElement = -1; private ImageVolume4D envelopeImage = null; private boolean showEnvelope = false; private boolean showSkullFloorStrikes = false; private int elementCount = 0; private int activeElementCount = 0; private float sdr = 0f; private float avgTransmitCoeff = 0f; // Observable pattern private List<Observer> observers = new ArrayList<Observer>(); public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void removeAllObservers() { observers.clear(); } private void updateObservers(PropertyChangeEvent e) { Iterator<Observer> i = observers.iterator(); while(i.hasNext()) { Observer o = i.next(); o.update(null, e); } } public int getActiveElementCount() { return activeElementCount; } public boolean getShowEnvelope() { return showEnvelope; } public void setShowEnvelope(boolean f) { if (showEnvelope != f) { setIsDirty(true); } showEnvelope = f; } public boolean getShowSkullFloorStrikes() { return showEnvelope; } public void setShowSkullFloorStrikes(boolean f) { if (showSkullFloorStrikes != f) { setIsDirty(true); } showSkullFloorStrikes = f; } private boolean clipRays = true; public void setClipRays(boolean clip) { if (clipRays != clip) { setIsDirty(true); } clipRays = clip; } private float rescaleIntercept = 0f; private float rescaleSlope = 1f; private float colormap_min, colormap_max; public void setImage(ImageVolume image) { // if (CTimage != image) { setIsDirty(true); CTimage = image; Float value = (Float) image.getAttribute("RescaleIntercept"); if (value != null) rescaleIntercept = value; value = (Float) image.getAttribute("RescaleSlope"); if (value != null) rescaleSlope = value; } public void setTextureRotatation(Vector3f rotationOffset, Trackball tb) { if (trackball == null || !centerOfRotation.equals(rotationOffset) || trackball.getCurrent() != tb.getCurrent()) { setIsDirty(true); } centerOfRotation = rotationOffset; trackball = tb; } public float getSDR() { return sdr; } public float getAvgTransmitCoeff() { return this.avgTransmitCoeff; } public float getBEAMvalue() { // from Dylan Beam @ Ohio State // These scaling values are derived from the min and max // penetration coefficients calculated from the Ohio State // patient cohort float MinPen = 0.0120f; float MaxPen = 0.1049f; float BeamValue = (avgTransmitCoeff-MinPen)*(99/(MaxPen-MinPen))+1; return BeamValue; } private float transducerTilt = 0f; // set tilt around x axis in degrees public void setTransducerTilt(float tilt) { if (transducerTilt != tilt) { setIsDirty(true); } transducerTilt = tilt; } private float boneSpeed = 2652f;//3500f; private float boneRefractionSpeed = 2900f; public void setTargetSteering(float x, float y, float z) { // (0, 0, 0) = no steering if (steering.x != x || steering.y != y || steering.z != z) { setIsDirty(true); } steering.set(x, y, z); } public Vector3f getTargetSteering() { return steering; } public void setBoneSpeed(float speed) { if (boneSpeed != speed) { setIsDirty(true); } boneSpeed = Math.min(3500, Math.max(1482, speed)); } public void setBoneRefractionSpeed(float speed) { if (boneRefractionSpeed != speed) { setIsDirty(true); } boneRefractionSpeed = Math.min(3500, Math.max(1482, speed)); } public float getBoneSpeed() { return boneSpeed; } public float getBoneRefractionSpeed() { return boneRefractionSpeed; } public void setBoneThreshold(float v) { if (boneThreshold != v) { setIsDirty(true); } boneThreshold = v; } public float getBoneThreshold() { return boneThreshold; } public ImageVolume getEnvelopeImage() { return envelopeImage; } public void setSelectedElement(int nelement) { selectedElement = nelement; } public int getSelectedElement() { return selectedElement; } private void initShader() { if (refractShader == null) { refractShader = new ShaderProgram(); refractShader.addShader(GL_COMPUTE_SHADER, "shaders/TransducerRayTracer5x5skullfloor.cs.glsl"); refractShader.compileShaderProgram(); } if (pickShader == null) { pickShader = new ShaderProgram(); pickShader.addShader(GL_COMPUTE_SHADER, "shaders/TransducerRayTracerPick.cs.glsl"); pickShader.compileShaderProgram(); } if (sdrShader == null) { sdrShader = new ShaderProgram(); sdrShader.addShader(GL_COMPUTE_SHADER, "shaders/sdrAreaShader2.cs.glsl"); // no refraction, only outer skull peak used sdrShader.compileShaderProgram(); } if (pressureShader == null) { pressureShader = new ShaderProgram(); pressureShader.addShader(GL_COMPUTE_SHADER, "shaders/pressureShader.cs.glsl"); pressureShader.compileShaderProgram(); } } public void init(Transducer trans) { setIsDirty(true); release(); initShader(); elementCount = trans.getElementCount(); FloatBuffer floatPosBuffer = ByteBuffer.allocateDirect(1024*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer(); int maxElemCount = elementCount > 1024 ? elementCount : 1024; for (int i=0; i<maxElemCount; i++) { Vector4f pos = new Vector4f(trans.getElement(i)); pos.w = 1f; if (!trans.getElementActive(i)) { pos.w = -1f; } floatPosBuffer.put(pos.x); floatPosBuffer.put(pos.y); floatPosBuffer.put(pos.z); floatPosBuffer.put(pos.w); Vector3f norm = new Vector3f(pos.x, pos.y, pos.z); norm.negate(norm); norm.normalise(); floatPosBuffer.put(norm.x); floatPosBuffer.put(norm.y); floatPosBuffer.put(norm.z); floatPosBuffer.put(0f); } floatPosBuffer.flip(); posSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, posSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_STATIC_DRAW); floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*12 * 20*3).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024*3*20; i++) { //positions floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); Vector3f norm = new Vector3f(1f, 1f, 1f); norm.normalise(); //normals floatPosBuffer.put(norm.x); floatPosBuffer.put(norm.y); floatPosBuffer.put(norm.z); floatPosBuffer.put(0f); //colors floatPosBuffer.put(1f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); } floatPosBuffer.flip(); outDiscSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW); // Rays between transducer surface and skull floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*8 * 2).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024*2; i++) { //positions floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); //colors floatPosBuffer.put(1f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); } floatPosBuffer.flip(); outRaysSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW); // Envelope survey data floatPosBuffer = ByteBuffer.allocateDirect(/*11x11x11*/1331 * 4*8).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1331; i++) { //positions floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); //colors floatPosBuffer.put(1f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); } floatPosBuffer.flip(); envSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW); // // Create a buffer of vertices to hold the output of the raytrace procedure // FloatBuffer floatOutBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer(); // for (int i=0; i<1024 * 2; i++) { // //color // floatOutBuffer.put(0f); // floatOutBuffer.put(0f); // floatOutBuffer.put(0f); // floatOutBuffer.put(1f); // floatOutBuffer.flip(); // outSSBo = glGenBuffers(); // glBindBuffer(GL_SHADER_STORAGE_BUFFER, outSSBo); // glBufferData(GL_SHADER_STORAGE_BUFFER, floatOutBuffer, GL_STATIC_DRAW); // Create a buffer of vertices to hold the output of the raytrace procedure FloatBuffer floatOutBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024 * 6; i++) { //color floatOutBuffer.put(0f); floatOutBuffer.put(0f); floatOutBuffer.put(0f); floatOutBuffer.put(1f); } floatOutBuffer.flip(); outSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glBufferData(GL_ARRAY_BUFFER, floatOutBuffer, GL_STATIC_DRAW); FloatBuffer floatColBuffer = ByteBuffer.allocateDirect(1024*4*4 * 6).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024 * 6; i++) { //color floatColBuffer.put(1f); floatColBuffer.put(1f); floatColBuffer.put(1f); floatColBuffer.put(0.4f); } floatColBuffer.flip(); colSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glBufferData(GL_ARRAY_BUFFER, floatColBuffer, GL_STATIC_DRAW); distSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, distSSBo); FloatBuffer distBuffer = ByteBuffer.allocateDirect(1024*4 *7).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024; i++) { //distance from focus distBuffer.put(0f); // SDR value distBuffer.put(0f); // Incident angle value distBuffer.put(0f); // Skull path length value distBuffer.put(0f); // SDR 2 value distBuffer.put(0f); // Normal skull thickness value distBuffer.put(0f); // transmission coeff distBuffer.put(0f); } distBuffer.flip(); glBufferData(GL_ARRAY_BUFFER,distBuffer,GL_STATIC_DRAW); sdrSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, sdrSSBo); FloatBuffer sdrBuffer = ByteBuffer.allocateDirect(1024*4 *(60 + 3)).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024; i++) { for (int j=0; j<60; j++) { //ct values along transit of skull per element sdrBuffer.put(0f); } // extrema values sdrBuffer.put(0f); sdrBuffer.put(0f); sdrBuffer.put(0f); } sdrBuffer.flip(); glBufferData(GL_ARRAY_BUFFER,sdrBuffer,GL_STATIC_DRAW); pressureSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, pressureSSBo); FloatBuffer pressureBuffer = ByteBuffer.allocateDirect(1024*4 * 1).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024; i++) { //ct values along transit of skull per element pressureBuffer.put(0f); } pressureBuffer.flip(); glBufferData(GL_ARRAY_BUFFER, pressureBuffer, GL_STATIC_DRAW); phaseSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, phaseSSBo); FloatBuffer phaseBuffer = ByteBuffer.allocateDirect(1024*4 * 1).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024; i++) { //ct values along transit of skull per element phaseBuffer.put(0f); } phaseBuffer.flip(); glBufferData(GL_ARRAY_BUFFER,phaseBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Skull floor strike geometry data floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*12 * 20*3).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024*3*20; i++) { //positions floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); Vector3f norm = new Vector3f(1f, 1f, 1f); norm.normalise(); //normals floatPosBuffer.put(norm.x); floatPosBuffer.put(norm.y); floatPosBuffer.put(norm.z); floatPosBuffer.put(0f); //colors floatPosBuffer.put(1f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); } floatPosBuffer.flip(); skullFloorDiscSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW); // Rays between final beam point and skull floor floatPosBuffer = ByteBuffer.allocateDirect(1024 * 4*8 * 2).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i=0; i<1024*2; i++) { //positions floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); //colors floatPosBuffer.put(1f); floatPosBuffer.put(0f); floatPosBuffer.put(0f); floatPosBuffer.put(1f); } floatPosBuffer.flip(); this.skullFloorRaysSSBo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, skullFloorRaysSSBo); glBufferData(GL_ARRAY_BUFFER, floatPosBuffer, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } private void doCalc() { refractShader.start(); int shaderProgID = refractShader.getShaderProgramID(); int texLoc = glGetUniformLocation(shaderProgID, "ct_tex"); glUniform1i(texLoc, 0); int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix"); glUniformMatrix4(texMatLoc, false, this.matrixBuf); int boneLoc = glGetUniformLocation(shaderProgID, "boneSpeed"); glUniform1f(boneLoc, boneRefractionSpeed); int waterLoc = glGetUniformLocation(shaderProgID, "waterSpeed"); glUniform1f(waterLoc, 1482f); int boneThreshLoc = glGetUniformLocation(shaderProgID, "ct_bone_threshold"); glUniform1f(boneThreshLoc, boneThreshold); int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept"); glUniform1f(rescaleLoc, this.rescaleIntercept); rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope"); glUniform1f(rescaleLoc, this.rescaleSlope); int targetLoc = glGetUniformLocation(shaderProgID, "target"); glUniform3f(targetLoc, steering.x, steering.y, steering.z); texLoc = glGetUniformLocation(shaderProgID, "selectedElement"); glUniform1i(texLoc, this.selectedElement); // int targetLoc = glGetUniformLocation(shaderprogram, "target"); // glUniform3f(targetLoc, 0f, 0f, 300f); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, colSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, distSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, outDiscSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, outRaysSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, phaseSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, skullFloorRaysSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, skullFloorDiscSSBo); // run compute shader org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1); org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, 0); refractShader.stop(); this.updateObservers(new PropertyChangeEvent(this, "rayCalc", null, null)); } private void doPickCalc() { pickShader.start(); int shaderProgID = pickShader.getShaderProgramID(); int texLoc = glGetUniformLocation(shaderProgID, "ct_tex"); glUniform1i(texLoc, 0); int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix"); glUniformMatrix4(texMatLoc, false, this.matrixBuf); int boneLoc = glGetUniformLocation(shaderProgID, "boneSpeed"); glUniform1f(boneLoc, boneRefractionSpeed); int waterLoc = glGetUniformLocation(shaderProgID, "waterSpeed"); glUniform1f(waterLoc, 1482f); int boneThreshLoc = glGetUniformLocation(shaderProgID, "ct_bone_threshold"); glUniform1f(boneThreshLoc, boneThreshold); int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept"); glUniform1f(rescaleLoc, this.rescaleIntercept); rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope"); glUniform1f(rescaleLoc, this.rescaleSlope); int targetLoc = glGetUniformLocation(shaderProgID, "target"); glUniform3f(targetLoc, steering.x, steering.y, steering.z); // int targetLoc = glGetUniformLocation(shaderprogram, "target"); // glUniform3f(targetLoc, 0f, 0f, 300f); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, colSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, distSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, outDiscSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, outRaysSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, phaseSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, skullFloorRaysSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, skullFloorDiscSSBo); // run compute shader org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1); org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 6, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 7, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 8, 0); pickShader.stop(); // this.updateObservers(new PropertyChangeEvent(this, "rayCalc", null, null)); } public void doSDRCalc() { // Calculate per element SDR data // doCalc() must be called first to compute the per element ray segments sdrShader.start(); int shaderProgID = sdrShader.getShaderProgramID(); int texLoc = glGetUniformLocation(shaderProgID, "ct_tex"); glUniform1i(texLoc, 0); int texMatLoc = glGetUniformLocation(shaderProgID, "ct_tex_matrix"); glUniformMatrix4(texMatLoc, false, this.matrixBuf); int rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_intercept"); glUniform1f(rescaleLoc, this.rescaleIntercept); rescaleLoc = glGetUniformLocation(shaderProgID, "ct_rescale_slope"); glUniform1f(rescaleLoc, this.rescaleSlope); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, outSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, distSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, sdrSSBo); // run compute shader org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1); org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0); sdrShader.stop(); this.updateObservers(new PropertyChangeEvent(this, "sdrCalc", null, null)); } public void doPressureCalc(Vector4f samplePoint) { // Calculate per element SDR data // doCalc() must be called first to compute the per element ray segments pressureShader.start(); int shaderProgID = pressureShader.getShaderProgramID(); int uniformLoc = glGetUniformLocation(shaderProgID, "sample_point"); glUniform3f(uniformLoc, samplePoint.x, samplePoint.y, samplePoint.z);// + 150f); uniformLoc = glGetUniformLocation(shaderProgID, "boneSpeed"); glUniform1f(uniformLoc, this.boneSpeed); //TEST glUniform1f(uniformLoc, 2640f); uniformLoc = glGetUniformLocation(shaderProgID, "waterSpeed"); glUniform1f(uniformLoc, 1482f); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, posSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, outSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, distSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, pressureSSBo); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, phaseSSBo); // run compute shader org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); org.lwjgl.opengl.GL43.glDispatchCompute(1024 / 256, 1, 1); org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, 0); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, 0); pressureShader.stop(); } public void calcEnvelope() { calcEnvelope(null); } public void calcSkullFloorDensity() { if (this.CTimage == null) return; int xsize = CTimage.getDimension(0).getSize() / 2; int ysize = CTimage.getDimension(1).getSize() / 2; int zsize = CTimage.getDimension(2).getSize() / 2; float xres = CTimage.getDimension(0).getSampleWidth(0) * 2f; float yres = CTimage.getDimension(1).getSampleWidth(1) * 2f; float zres = CTimage.getDimension(2).getSampleWidth(2) * 2f; Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); Quaternion imageRotation = (Quaternion)CTimage.getAttribute("ImageOrientationQ"); if (envelopeImage != null) { ImageVolumeUtil.releaseTexture(envelopeImage); } envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, xsize, ysize, zsize, 1); envelopeImage.getDimension(0).setSampleWidth(xres); envelopeImage.getDimension(1).setSampleWidth(yres); envelopeImage.getDimension(2).setSampleWidth(zres); envelopeImage.getDimension(0).setSampleSpacing(xres); envelopeImage.getDimension(1).setSampleSpacing(yres); envelopeImage.getDimension(2).setSampleSpacing(zres); envelopeImage.setAttribute("ImageTranslation", new Vector3f(imageTranslation)); envelopeImage.setAttribute("ImageOrientationQ", new Quaternion(imageRotation)); // setup textures // need to compile shader in init // TODO: work on integration of skull floor footprints // shader.start(); // int uloc = glGetUniformLocation(shader.getShaderProgramID(), "ct_rescale_intercept"); // glUniform1f(uloc, this.rescaleIntercept); // uloc = glGetUniformLocation(shader.getShaderProgramID(), "ct_rescale_slope"); // glUniform1f(uloc, this.rescaleSlope); // // run compute shader // org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); // org.lwjgl.opengl.GL43.glDispatchCompute((xsize+7)/8, (ysize+7)/8, (zsize+7)/8); // org.lwjgl.opengl.GL42.glMemoryBarrier(org.lwjgl.opengl.GL42.GL_ALL_BARRIER_BITS); // // Clean up // shader.stop(); } public void calcEnvelope(ProgressListener listener) { // if (envelopeImage == null) { if (envelopeImage != null) { ImageVolumeUtil.releaseTexture(envelopeImage); } envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, 21, 21, 21, 1); envelopeImage.getDimension(0).setSampleWidth(4f); envelopeImage.getDimension(1).setSampleWidth(6f); envelopeImage.getDimension(2).setSampleWidth(4f); envelopeImage.getDimension(0).setSampleSpacing(4f); envelopeImage.getDimension(1).setSampleSpacing(6f); envelopeImage.getDimension(2).setSampleSpacing(4f); Vector4f offset = new Vector4f(); Matrix4f transducerTiltMat = new Matrix4f(); transducerTiltMat.setIdentity(); Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat); if (CTimage == null) return; Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); envelopeImage.setAttribute("ImageTranslation", new Vector3f()); // 21x21x21 array of floats to hold sampled treatment envelope FloatBuffer envFloats = ByteBuffer.allocateDirect(9261*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer(); float[] voxels = (float[])envelopeImage.getData(); for (int i = -10; i <= 10; i++) { for (int j = -10; j <= 10; j++) { if (listener != null) { listener.percentDone("Treatment envelope", Math.round( ((i+10)*21f + (j+10))/440f*100f ) ); } for (int k = -10; k <= 10; k++) { offset.set(i * 4f, j * 6f, k * 4f, 1f); int elemCount = calcElementsOn(new Vector3f(0f, 0f, 0f), offset); voxels[(i+10) + (-j+10)*21 + (-k+10)*21*21] = (short)(elemCount & 0xffff); // System.out.print("elemCount = " + elemCount + " "); // envFloats.put(-centerOfRotation.x + imageTranslation.x + offset.x); // envFloats.put(-centerOfRotation.x + imageTranslation.y + offset.y); // envFloats.put(-centerOfRotation.x + imageTranslation.z + offset.z + 150f); Matrix4f.transform(transducerTiltMat, offset, offset); envFloats.put(offset.x);// + centerOfRotation.x); envFloats.put(offset.y);// - centerOfRotation.y); envFloats.put(-offset.z);// -centerOfRotation.z); envFloats.put(1f); if (elemCount >= 700) { envFloats.put(0f); envFloats.put(1f); envFloats.put(0f); envFloats.put(0.6f); } else if (elemCount >= 500) { envFloats.put(1f); envFloats.put(1f); envFloats.put(0f); envFloats.put(0.6f); } else { envFloats.put(1f); envFloats.put(0f); envFloats.put(0f); envFloats.put(0.6f); } } } // System.out.println(""); } if (listener != null) { listener.percentDone("Ready", -1); } envFloats.flip(); if (envSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(envSSBo); envSSBo = glGenBuffers(); } glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glBufferData(GL_ARRAY_BUFFER, envFloats, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } public float[] getChannelSkullSamples(int channel) { glBindBuffer(GL_ARRAY_BUFFER, this.sdrSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatSamples = dists.asFloatBuffer(); int count = 0; float[] huOut = new float[63]; for (int i=0; i<huOut.length; i++) { huOut[i] = floatSamples.get(channel * 63 + i); } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return huOut; } public void writeSkullMeasuresFile(File outFile) { if (outFile != null) { List<Double> speeds = getSpeeds(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(outFile)); writer.write("Skull parameters"); writer.newLine(); writer.write("NumberOfChannels = 1024"); writer.newLine(); writer.newLine(); writer.write("channel\tsdr\tsdr5x5\tincidentAngle\tskull_thickness\trefracted_skull_path_length\tSOS\ttransCoeff"); writer.newLine(); while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); float speed = CTSoundSpeed.lookupSpeed(speeds.get(count).floatValue() + 1000f); // add 1000 to get apparent density writer.write(count + "\t"); writer.write(String.format("%1.3f", sdr) + "\t"); writer.write(String.format("%1.3f", sdr2) + "\t"); writer.write(String.format("%3.3f", incidentAngle) + "\t"); writer.write(String.format("%3.3f", normSkullThickness) + "\t"); writer.write(String.format("%3.3f", skullThickness) + "\t"); writer.write(String.format("%3.3f", speed) + "\t"); writer.write(String.format("%3.6f", transmCoeff) + "\t"); writer.newLine(); count++; } writer.close(); } catch (IOException e) { e.printStackTrace(); } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); } } public void writeACTFile(File outFile) { if (outFile != null) { doCalc(); doPressureCalc(new Vector4f()); glBindBuffer(GL_ARRAY_BUFFER, phaseSSBo); ByteBuffer phases = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = phases.asFloatBuffer(); int count = 0, zeroCount = 0; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(outFile)); writer.write("[AMPLITUDE_AND_PHASE_CORRECTIONS]"); writer.newLine(); writer.write("NumberOfChannels = 1024"); writer.newLine(); writer.newLine(); while (floatPhases.hasRemaining()) { double phase = (double) floatPhases.get() % (2.0 * Math.PI); if (phase > Math.PI) { phase -= 2.0 * Math.PI; } else if (phase < -Math.PI) { phase += 2.0 * Math.PI; } if (phase == 0.0) { zeroCount++; } // phase = -phase; //double phase = (double)floatPhases.get(); // for outputing skull thickness if set in pressure shader // System.out.println("Channel " + count + " = " + phase); writer.write("CH" + count + "\t=\t"); count++; if (phase == 0.0) { writer.write("0\t"); } else { writer.write("1\t"); } writer.write(String.format("%1.4f", phase)); writer.newLine(); } System.out.println("zero phase channels = " + zeroCount); writer.close(); } catch (IOException e) { e.printStackTrace(); } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); } } public List<Double> getIncidentAngles() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (incidentAngle >= 0f) { result.add((double)incidentAngle); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getIncidentAnglesFull() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); result.add((double)incidentAngle); } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getSDRs() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)sdr); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } // include -1 for all inactive elements public List<Double> getSDRsFull() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)sdr); } else { result.add(-1.0); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getSDR2s() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)sdr2); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getSkullThicknesses() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)skullThickness); } else { result.add(-1.0); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getNormSkullThicknesses() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)normSkullThickness); } else { result.add(-1.0); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } // this list will contain sdr = -1 for inactive elements public List<Double> getSDR2sFull() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)sdr2); } else { result.add(-1.0); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } // this list will contain sdr = -1 for inactive elements public List<Double> getTransmissionCoeff() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_ARRAY_BUFFER, this.distSSBo); ByteBuffer dists = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPhases = dists.asFloatBuffer(); int count = 0; while (floatPhases.hasRemaining()) { float dist = floatPhases.get(); float sdr = floatPhases.get(); float incidentAngle = floatPhases.get(); float skullThickness = floatPhases.get(); float sdr2 = floatPhases.get(); float normSkullThickness = floatPhases.get(); float transmCoeff = floatPhases.get(); if (dist >= 0f) { result.add((double)transmCoeff); } else { result.add(-1.0); } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return result; } public List<Double> getSpeeds() { List<Double> result = new ArrayList<>(); glBindBuffer(GL_SHADER_STORAGE_BUFFER,sdrSSBo); ByteBuffer sdrOutput = glMapBuffer(GL_SHADER_STORAGE_BUFFER,GL_READ_ONLY,null); FloatBuffer huValues = sdrOutput.asFloatBuffer(); float[] huOut = new float[60]; float[] huIndices = new float[3]; for (int i=0; i<1024; i++) { huValues.get(huOut); huValues.get(huIndices); int left = 0; int right = 59; for (int x=0; x<59; x++) { if (huOut[x] >= 700f) { left = x; break; } } for (int x=59; x>=0; x if (huOut[x] >= 700f) { right = x; break; } } int count = 0; float sum = 0f; for (int x=left; x<=right; x++) { count++; sum += huOut[x]; } if (count > 0) { result.add((double)sum/(double)count); } else { result.add(-1.0); } } glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); return result; } public void calcPressureEnvelope() { // if (envelopeImage == null) { float voxelsize = 0.5f; int volumeHalfWidth = 10; int volumeWidth = 2*volumeHalfWidth+1; envelopeImage = new ImageVolume4D(ImageVolume.FLOAT_VOXEL, volumeWidth, volumeWidth, volumeWidth, 1); envelopeImage.getDimension(0).setSampleWidth(voxelsize); envelopeImage.getDimension(1).setSampleWidth(voxelsize); envelopeImage.getDimension(2).setSampleWidth(voxelsize); envelopeImage.getDimension(0).setSampleSpacing(voxelsize); envelopeImage.getDimension(1).setSampleSpacing(voxelsize); envelopeImage.getDimension(2).setSampleSpacing(voxelsize); Vector4f offset = new Vector4f(); // Matrix4f transducerTiltMat = new Matrix4f(); // transducerTiltMat.setIdentity(); // Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat); if (CTimage == null) return; // Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); // envelopeImage.setAttribute("ImageTranslation", new Vector3f(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z)); envelopeImage.setAttribute("ImageTranslation", new Vector3f(-centerOfRotation.x, -centerOfRotation.y, -centerOfRotation.z)); envelopeImage.setAttribute("ImageOrientationQ", new Quaternion()); float[] voxels = (float[])envelopeImage.getData(); this.colormap_min = Float.MAX_VALUE; this.colormap_max = -Float.MAX_VALUE; setupImageTexture(CTimage, 0, new Vector3f(centerOfRotation.x, centerOfRotation.y, centerOfRotation.z), new Vector4f(0f, 0f, 0f, 1f)/*offset*/); doCalc(); glActiveTexture(GL_TEXTURE0 + 0); glDisable(GL_TEXTURE_3D); for (int i = -volumeHalfWidth; i <= volumeHalfWidth; i++) { for (int j = -volumeHalfWidth; j <= volumeHalfWidth; j++) { for (int k = -volumeHalfWidth; k <= volumeHalfWidth; k++) { float pressure = 0f; //if (k==0) { offset.set(i * voxelsize, j * voxelsize, k * voxelsize, 1f); pressure = calcSamplePressure(new Vector3f(), offset) * 10f; pressure *= pressure; if (i==0 && j==0 && k==0) { //TODO: just for now, remove ///glMapBuffer // glBindBuffer(GL_SHADER_STORAGE_BUFFER, phaseSSBo); // ByteBuffer phases = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_WRITE, null); // FloatBuffer floatPhases = phases.asFloatBuffer(); // int count = 0, zeroCount = 0; // BufferedWriter writer=null; // try { // writer = new BufferedWriter(new FileWriter("ACT.ini")); // writer.write("[AMPLITUDE_AND_PHASE_CORRECTIONS]"); // writer.newLine(); // writer.write("NumberOfChannels = 1024"); // writer.newLine(); // writer.newLine(); // while (floatPhases.hasRemaining()) { // double phase = (double)floatPhases.get() % (2.0 * Math.PI); // if (phase > Math.PI) { // phase -= 2.0 * Math.PI; // else if (phase < -Math.PI) { // phase += 2.0 * Math.PI; // if (phase == 0.0) { // zeroCount++; //// phase = -phase; ////double phase = (double)floatPhases.get(); // for outputing skull thickness if set in pressure shader // System.out.println("Channel " + count + " = " + phase); // writer.write("CH" + count + "\t=\t"); // count++; // if (phase == 0.0) { // writer.write("0\t"); // else { // writer.write("1\t"); // writer.write(String.format("%1.4f", phase)); // writer.newLine(); // System.out.println("zero phase channels = " + zeroCount); // writer.close(); // catch(IOException e) { // e.printStackTrace(); // glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); // glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } if (pressure > colormap_max) { colormap_max = pressure; } if (pressure < colormap_min) { colormap_min = pressure; } voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (k + volumeHalfWidth) * volumeWidth * volumeWidth] = pressure; // if (i==0) { // if (k==-volumeHalfWidth) { // System.out.println(); // System.out.print(pressure + " "); // } // k == 0 } } } // for (int i = -volumeHalfWidth; i <= volumeHalfWidth; i++) { // for (int j = -volumeHalfWidth; j <= volumeHalfWidth; j++) { // for (int k = -volumeHalfWidth; k <= volumeHalfWidth; k++) { // float value = voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (-k + volumeHalfWidth) * volumeWidth * volumeWidth]; // voxels[(i + volumeHalfWidth) + (-j + volumeHalfWidth) * volumeWidth + (-k + volumeHalfWidth) * volumeWidth * volumeWidth] = (value - colormap_min) / (colormap_max - colormap_min); System.out.println("Pressure max = " + colormap_max + ", min = " + colormap_min); } public void calc2DEnvelope() { Vector4f offset = new Vector4f(); Matrix4f transducerTiltMat = new Matrix4f(); transducerTiltMat.setIdentity(); Matrix4f.rotate(-transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), transducerTiltMat, transducerTiltMat); if (CTimage == null) return; Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); // 21x21x21 array of floats to hold sampled treatment envelope FloatBuffer envFloats = ByteBuffer.allocateDirect(9261*4*8).order(ByteOrder.nativeOrder()).asFloatBuffer(); for (int i = -10; i <= 10; i++) { for (int j = -10; j <= 10; j++) { offset.set(i * 6f, j * 6f, 0f, 1f); Matrix4f rotMat = Trackball.toMatrix4f(trackball.getCurrent()); // rotMat.rotate((float)Math.PI, new Vector3f(0f, 0f, 1f), rotMat); Matrix4f.transform(rotMat, offset, offset); int elemCount = calcElementsOn(centerOfRotation, offset); System.out.print("" + elemCount + " "); // envFloats.put(-centerOfRotation.x + imageTranslation.x + offset.x); // envFloats.put(-centerOfRotation.x + imageTranslation.y + offset.y); // envFloats.put(-centerOfRotation.x + imageTranslation.z + offset.z + 150f); //Matrix4f.transform(transducerTiltMat, offset, offset); envFloats.put(offset.x);// + centerOfRotation.x); envFloats.put(offset.y);// - centerOfRotation.y); envFloats.put(-offset.z);// -centerOfRotation.z); envFloats.put(1f); if (elemCount >= 700) { envFloats.put(0f); envFloats.put(1f); envFloats.put(0f); envFloats.put(0.6f); } else if (elemCount >= 500) { envFloats.put(1f); envFloats.put(1f); envFloats.put(0f); envFloats.put(0.6f); } else { envFloats.put(1f); envFloats.put(0f); envFloats.put(0f); envFloats.put(0.6f); } } System.out.println(""); } envFloats.flip(); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glBufferData(GL_ARRAY_BUFFER, envFloats, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } private int calcElementsOn(Vector4f offset) { return calcElementsOn(centerOfRotation, offset); } private int calcElementsOn(Vector3f center, Vector4f offset) { if (CTimage == null) { return 0; } setupImageTexture(CTimage, 0, center, offset); doCalc(); glActiveTexture(GL_TEXTURE0 + 0); glDisable(GL_TEXTURE_3D); ///glMapBuffer glBindBuffer(GL_ARRAY_BUFFER, distSSBo); ByteBuffer distances = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatDistances = distances.asFloatBuffer(); int numberOn = 0; // float sdrSum = 0f; while (floatDistances.hasRemaining()) { float value = floatDistances.get(); float sdrval = floatDistances.get(); // TODO floatDistances.get(); // incidence angle floatDistances.get(); // skull thickness float sdrval2 = floatDistances.get(); // TODO float normSkullThickness = floatDistances.get(); float transmCoeff = floatDistances.get(); if (value > 0) { numberOn++; // sdrSum += sdr; } } // System.out.println("SDR = " + sdrSum/numberOn); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return numberOn; } private float calcSamplePressure(Vector3f center, Vector4f offset) { if (CTimage == null) { return 0; } // setupImageTexture(CTimage, 0, center, new Vector4f(0f, 0f, 0f, 1f)/*offset*/); // doCalc(); doPressureCalc(offset); // glActiveTexture(GL_TEXTURE0 + 0); // glDisable(GL_TEXTURE_3D); ///glMapBuffer glBindBuffer(GL_ARRAY_BUFFER, pressureSSBo); ByteBuffer pressures = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE, null); FloatBuffer floatPressures = pressures.asFloatBuffer(); float totalPressure = 0f; while (floatPressures.hasRemaining()) { totalPressure += floatPressures.get(); } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); return totalPressure; } @Override public void render() { if (!getVisible()) return; setIsDirty(false); if (CTimage == null) return; setupImageTexture(CTimage, 0, centerOfRotation); doCalc(); doSDRCalc(); glActiveTexture(GL_TEXTURE0 + 0); glDisable(GL_TEXTURE_3D); // Raytracer done, now render result // glBindBuffer(GL_SHADER_STORAGE_BUFFER,sdrSSBo); // ByteBuffer sdrOutput = glMapBuffer(GL_SHADER_STORAGE_BUFFER,GL_READ_ONLY,null); // FloatBuffer sdrValues = sdrOutput.asFloatBuffer(); // float[][] tmpOut = new float[1024][60]; // float[][] tmpIndices = new float[1024][3]; // for (int i=0; i<1024; i++) { // sdrValues.get(tmpOut[i]); // sdrValues.get(tmpIndices[i]); // glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); // glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); // System.out.println("///////////SDR data"); // for (int i=0; i<60; i++) { // System.out.print(i); // for (int j=0; j<1024; j++) { // System.out.print(", " + tmpOut[j][i]); // System.out.println(); // for (int i=0; i<3; i++) { // switch(i) { // case 0: // System.out.print("LPk"); // break; // case 1: // System.out.print("RPk"); // break; // case 2: // System.out.print("Min"); // break; // for (int j=0; j<1024; j++) { // System.out.print(", " + tmpIndices[j][i]); // System.out.println(); // System.out.print("CH, "); // for (int i=0; i<1024; i++) { // System.out.print(i); // if (i<1023) { // System.out.print(", "); // System.out.println(); // System.out.println("/////////////"); ///glMapBuffer glBindBuffer(GL_ARRAY_BUFFER,distSSBo); ByteBuffer distances = glMapBuffer(GL_ARRAY_BUFFER,GL_READ_WRITE,null); FloatBuffer floatDistances = distances.asFloatBuffer(); float distanceSum = 0.0f; int distanceNum = 0; int numberOn = 0; while (floatDistances.hasRemaining()) { float value = floatDistances.get(); float sdr = floatDistances.get(); floatDistances.get(); // skip incidence angle floatDistances.get(); // skip skull thickness float sdr2 = floatDistances.get(); float normSkullThickness = floatDistances.get(); float transmCoeff = floatDistances.get(); if (value > 0) { distanceNum++; distanceSum += value; numberOn++; } } float percentOn = numberOn/1024.0f; float mean = distanceSum/distanceNum; floatDistances.rewind(); float diffSqSum = 0.0f; float sdrSum = 0.0f; float sdrCount = 0.0f; float transmitCoeffSum = 0f; int transmitCoeffCount = 0; while (floatDistances.hasRemaining()) { float value = floatDistances.get(); float sdr = floatDistances.get(); float incidentAngle = floatDistances.get(); float skullThickness = floatDistances.get(); float sdr2 = floatDistances.get(); float normSkullThickness = floatDistances.get(); float transmitCoeff = floatDistances.get(); if (value > 0) { diffSqSum += (float) Math.pow(value-mean,2); sdrSum += sdr2; sdrCount += 1.0f; } if (value > 0 && incidentAngle < 20f) { transmitCoeffCount++; transmitCoeffSum += transmitCoeff; } else { transmitCoeffCount++; // transmitCoeff is zero for this element } } activeElementCount = numberOn; this.sdr = sdrSum/sdrCount; //distanceNum; this.avgTransmitCoeff = transmitCoeffSum/(float)transmitCoeffCount; float stDev = (float)Math.sqrt(diffSqSum/distanceNum); // System.out.println("Average: "+mean); // System.out.println("Std Dev: "+stDev); // System.out.println("% Within 3 mm of focus: "+(percentOn*100) + "(" + numberOn + " of 1024)"); // System.out.println("SDR: " + sdrSum/distanceNum); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); // glTranslatef(0, 0, 150); glTranslatef(-steering.x, -steering.y, -steering.z); glRotatef(this.transducerTilt, 1, 0, 0); // glTranslatef(0, 0, -150); glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16*6, 0); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16*6, 0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); Main.glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT); glDisable(GL_LIGHTING); if (clipRays) { glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); } else { glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); } //glEnable(GL_BLEND); //glColor4f(1f, 0f, 0f, 1f); glPointSize(6f); // Draw outer skull points if (clipRays) { glDrawArrays(GL_POINTS, 0, 1024); } // Draw inner skull points glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16*6, 16*3); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16*6, 16*3); if (clipRays) { glDrawArrays(GL_POINTS, 0, 1024); } // Draw envelope renderEnvelope(); // calc2DEnvelope(); // TODO: doesn't work yet // render2DEnvelope(); if (clipRays) { // Draw normal flags glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16, 0); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16, 0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); org.lwjgl.opengl.GL11.glLineWidth(1.2f); if (!showEnvelope) { glDrawArrays(GL_LINES, 0, 1024*6); } } // Draw skull strike discs if (!clipRays) { Main.glPushAttrib(GL_LIGHTING_BIT); glEnable(GL_LIGHTING); FloatBuffer matSpecular = BufferUtils.createFloatBuffer(4); matSpecular.put(0.2f).put(0.2f).put(0.2f).put(1.0f).flip(); glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, matSpecular); // sets specular material color glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 30.0f); // sets shininess glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glVertexPointer(4, GL_FLOAT, 12*4, 0); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glNormalPointer(GL_FLOAT, 12*4, 16); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glColorPointer(4, GL_FLOAT, 12*4, 32); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 1024*3*20); // skull floor normal discs if (showSkullFloorStrikes) { glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo); glVertexPointer(4, GL_FLOAT, 12*4, 0); glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo); glNormalPointer(GL_FLOAT, 12*4, 16); glBindBuffer(GL_ARRAY_BUFFER, skullFloorDiscSSBo); glColorPointer(4, GL_FLOAT, 12*4, 32); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 1024*3*20); } Main.glPopAttrib(); } else { Main.glPushAttrib(GL_COLOR_BUFFER_BIT); org.lwjgl.opengl.GL11.glLineWidth(1.0f); glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo); glVertexPointer(4, GL_FLOAT, 8*4, 0); glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo); glColorPointer(4, GL_FLOAT, 8*4, 16); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glDrawArrays(GL_LINES, 0, 1024*2); if (showSkullFloorStrikes) { // skull floor strike rays glBindBuffer(GL_ARRAY_BUFFER, this.skullFloorRaysSSBo); glVertexPointer(4, GL_FLOAT, 8*4, 0); glBindBuffer(GL_ARRAY_BUFFER, skullFloorRaysSSBo); glColorPointer(4, GL_FLOAT, 8*4, 16); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glDrawArrays(GL_LINES, 0, 1024*2); } Main.glPopAttrib(); } Main.glPopAttrib(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); } private void renderEnvelope() { Main.glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT); glPointSize(8f); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glVertexPointer(4, GL_FLOAT, 16*2, 0); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glColorPointer(4, GL_FLOAT, 16*2, 16); if (clipRays && showEnvelope) { //glEnable(GL_BLEND); glMatrixMode(GL_MODELVIEW); Main.glPushMatrix(); // envFloats.put(offset.x + centerOfRotation.x); // envFloats.put(offset.y - centerOfRotation.y); // envFloats.put(150f - offset.z - centerOfRotation.z); // Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); // glTranslatef(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z); // glTranslatef(0f, 0f, 150f); // glRotatef(-(float)Math.PI, 1f, 0f, 0f); glRotatef(-transducerTilt, 1f, 0f, 0f); glTranslatef(-centerOfRotation.x, centerOfRotation.y, centerOfRotation.z); glDrawArrays(GL_POINTS, 0, 9261); Main.glPopMatrix(); } Main.glPopAttrib(); } private void render2DEnvelope() { Main.glPushAttrib(GL_POINT_BIT | GL_ENABLE_BIT); glPointSize(8f); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glVertexPointer(4, GL_FLOAT, 16*2, 0); glBindBuffer(GL_ARRAY_BUFFER, envSSBo); glColorPointer(4, GL_FLOAT, 16*2, 16); if (clipRays && showEnvelope) { //glEnable(GL_BLEND); glMatrixMode(GL_MODELVIEW); Main.glPushMatrix(); // envFloats.put(offset.x + centerOfRotation.x); // envFloats.put(offset.y - centerOfRotation.y); // envFloats.put(150f - offset.z - centerOfRotation.z); // Vector3f imageTranslation = (Vector3f)CTimage.getAttribute("ImageTranslation"); // glTranslatef(-imageTranslation.x, -imageTranslation.y, -imageTranslation.z); // glTranslatef(0f, 0f, 150f); // glRotatef(-(float)Math.PI, 1f, 0f, 0f); // glRotatef(-transducerTilt, 1f, 0f, 0f); // glTranslatef(-centerOfRotation.x, centerOfRotation.y, centerOfRotation.z); glDrawArrays(GL_POINTS, 0, 9261); Main.glPopMatrix(); } Main.glPopAttrib(); } private void setupImageTexture(ImageVolume image, int textureUnit, Vector3f center) { setupImageTexture(image, textureUnit, center, new Vector4f(0f, 0f, 0f, 1f)); } private void setupImageTexture(ImageVolume image, int textureUnit, Vector3f center, Vector4f offset) { if (image == null) return; Main.glPushAttrib(GL_ENABLE_BIT | GL_TRANSFORM_BIT); glActiveTexture(GL_TEXTURE0 + textureUnit); glEnable(GL_TEXTURE_3D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); Integer tn = (Integer) image.getAttribute("textureName"); if (tn == null) return; // TODO: this should be handled when the 3D texture doesn't exist for some reason (i.e. after some image filter) int textureName = tn.intValue(); glBindTexture(GL_TEXTURE_3D, textureName); int iWidth = image.getDimension(0).getSize(); int iHeight = image.getDimension(1).getSize(); int idepth = image.getDimension(2).getSize(); int texWidth = iWidth; int texHeight = iHeight; int texDepth = idepth; // Build transformation of Texture matrix glMatrixMode(GL_TEXTURE); glLoadIdentity(); //System.out.println("mid z = " + (double)idepth/texDepth/2.0); //fix voxel scaling float xres = image.getDimension(0).getSampleWidth(0); float yres = image.getDimension(1).getSampleWidth(1); float zres = image.getDimension(2).getSampleWidth(2); // Translation to the texture volume center (convert 0 -> 1 value range to -0.5 -> 0.5) // glTranslated(0.5, 0.5, (double) idepth / texDepth / 2.0); // float zscaleFactor = ((float) texWidth * xres) / ((float) texDepth * zres); // // Scale for in-plane/out-of-plane ratio //// glScaled(1.0f, 1.0f, -zscaleFactor); // this assumes in-plane pixel dimesions are the same! //HACK // glScaled(1f /(texWidth * xres), 1f/(texWidth * xres), 1f/(texDepth * zres)); // // Translation of center of rotation to origin (mm to texture coord values (0 -> 1)) Vector3f imageTranslation = (Vector3f)image.getAttribute("ImageTranslation"); if (imageTranslation == null) { imageTranslation = new Vector3f(); } float[] imagePosition = (float[])image.getAttribute("ImagePosition"); if (imagePosition == null) { imagePosition = new float[3]; } // glTranslatef( //// (imageTranslation.x)/ (xres * iWidth), //// (imageTranslation.y) / (yres * iHeight), //// (imageTranslation.z) / (zres * idepth * zscaleFactor)); // (-imageTranslation.x), // (-imageTranslation.y), // (-imageTranslation.z) - 150f); Quaternion imageOrientation = (Quaternion)image.getAttribute("ImageOrientationQ"); if (imageOrientation == null) return; FloatBuffer orientBuffer = BufferUtils.createFloatBuffer(16); Trackball.toMatrix4f(imageOrientation).store(orientBuffer); orientBuffer.flip(); // Rotation for image orientation //glMultMatrix(orientBuffer); // Rotation for camera view // if (trackball != null) { // trackball.renderOpposite(); // matrixBuf.rewind(); // glGetFloat(GL_TEXTURE_MATRIX, matrixBuf); // ctTexMatrix.load(matrixBuf); ctTexMatrix.setIdentity(); // Final translation to put origin in the center of texture space (0.5, 0.5, 0.5) Matrix4f.translate(new Vector3f(0.5f, 0.5f, 0.5f), ctTexMatrix, ctTexMatrix); // Scale for image resolution (normalize to texture coordinates 0-1 Matrix4f.scale(new Vector3f(1.0f/(texWidth*xres), 1.0f/(texHeight*yres), -1.0f/(texDepth*zres)), ctTexMatrix, ctTexMatrix); // Rotation Matrix4f rotMat = new Matrix4f(); rotMat.load(orientBuffer); Matrix4f.mul(ctTexMatrix, rotMat, ctTexMatrix); // Translation Matrix4f.translate(new Vector3f( (center.x + imageTranslation.x /* + imagePosition[0] */), (center.y + imageTranslation.y /* + imagePosition[1] */), (center.z + imageTranslation.z /* + imagePosition[2] */) ), ctTexMatrix, ctTexMatrix); Matrix4f.rotate((float)Math.PI, new Vector3f(1f, 0f, 0f), ctTexMatrix, ctTexMatrix); //Matrix4f.rotate((float)Math.PI, new Vector3f(0f, 1f, 0f), ctTexMatrix, ctTexMatrix); // add in transducer tilt Matrix4f.rotate(transducerTilt/180f*(float)Math.PI, new Vector3f(1f, 0f, 0f), ctTexMatrix, ctTexMatrix); // Translate transducer origin to the transducer face // Matrix4f.translate(new Vector3f(0f, 0f, -150f), ctTexMatrix, ctTexMatrix); Matrix4f.translate(new Vector3f(offset.x, offset.y, -offset.z), ctTexMatrix, ctTexMatrix); // store matrix for use later matrixBuf.rewind(); ctTexMatrix.store(matrixBuf); matrixBuf.flip(); // System.out.println(ctTexMatrix); // System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(0f, 0f, 150f, 1f), null)); // System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(0f, 0f, 0f, 1f), null)); // System.out.println(Matrix4f.transform(ctTexMatrix, new Vector4f(150f, 0f, 0f, 1f), null)); glMatrixMode(GL_MODELVIEW); Main.glPopAttrib(); } @Override public void release() { if (posSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(posSSBo); posSSBo = 0; } if (colSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(colSSBo); colSSBo = 0; } if (outSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(outSSBo); outSSBo = 0; } if (distSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(distSSBo); distSSBo = 0; } if (outDiscSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(outDiscSSBo); outDiscSSBo = 0; } if (outRaysSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(outDiscSSBo); outRaysSSBo = 0; } if (envSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(envSSBo); envSSBo = 0; } if (sdrSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(sdrSSBo); sdrSSBo = 0; } if (pressureSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(pressureSSBo); pressureSSBo = 0; } if (phaseSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(phaseSSBo); phaseSSBo = 0; } if (skullFloorDiscSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(skullFloorDiscSSBo); skullFloorDiscSSBo = 0; } if (skullFloorRaysSSBo != 0) { org.lwjgl.opengl.GL15.glDeleteBuffers(skullFloorRaysSSBo); skullFloorRaysSSBo = 0; } if (refractShader != null) { refractShader.release(); refractShader = null; } if (sdrShader != null) { sdrShader.release(); sdrShader = null; } if (pressureShader != null) { pressureShader.release(); pressureShader = null; } } @Override public void renderPickable() { if (!getVisible()) return; if (CTimage == null) return; setupImageTexture(CTimage, 0, centerOfRotation); doPickCalc(); glActiveTexture(GL_TEXTURE0 + 0); glDisable(GL_TEXTURE_3D); glTranslatef(-steering.x, -steering.y, -steering.z); glRotatef(this.transducerTilt, 1, 0, 0); // glTranslatef(0, 0, -150); glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16*6, 0); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16*6, 0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); Main.glPushAttrib(GL_ENABLE_BIT | GL_LINE_BIT); glDisable(GL_LIGHTING); if (clipRays) { glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); } else { glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); } //glEnable(GL_BLEND); //glColor4f(1f, 0f, 0f, 1f); glPointSize(6f); // Draw outer skull points if (clipRays) { glDrawArrays(GL_POINTS, 0, 1024); } // Draw inner skull points glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16*6, 16*3); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16*6, 16*3); if (clipRays) { glDrawArrays(GL_POINTS, 0, 1024); } if (clipRays) { // Draw normal flags glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, outSSBo); glVertexPointer(4, GL_FLOAT, 16, 0); glBindBuffer(GL_ARRAY_BUFFER, colSSBo); glColorPointer(4, GL_FLOAT, 16, 0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); org.lwjgl.opengl.GL11.glLineWidth(1.2f); if (!showEnvelope) { glDrawArrays(GL_LINES, 0, 1024*6); } } // Draw skull strike discs if (!clipRays) { Main.glPushAttrib(GL_LIGHTING_BIT); glDisable(GL_LIGHTING); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glVertexPointer(4, GL_FLOAT, 12*4, 0); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glNormalPointer(GL_FLOAT, 12*4, 16); glBindBuffer(GL_ARRAY_BUFFER, outDiscSSBo); glColorPointer(4, GL_FLOAT, 12*4, 32); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 1024*3*20); Main.glPopAttrib(); } else { Main.glPushAttrib(GL_COLOR_BUFFER_BIT); org.lwjgl.opengl.GL11.glLineWidth(1.0f); glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo); glVertexPointer(4, GL_FLOAT, 8*4, 0); glBindBuffer(GL_ARRAY_BUFFER, outRaysSSBo); glColorPointer(4, GL_FLOAT, 8*4, 16); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glDisable(GL_BLEND); glDrawArrays(GL_LINES, 0, 1024*2); Main.glPopAttrib(); } Main.glPopAttrib(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); } }
package org.voltdb.iv2; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.ExecutionException; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.json_voltpatches.JSONObject; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.HostMessenger; import org.voltcore.messaging.Mailbox; import org.voltcore.messaging.Subject; import org.voltcore.messaging.VoltMessage; import org.voltcore.utils.CoreUtils; import org.voltcore.zk.MapCache; import org.voltcore.zk.MapCacheReader; import org.voltdb.messaging.Iv2InitiateTaskMessage; import org.voltdb.messaging.Iv2RepairLogRequestMessage; import org.voltdb.messaging.Iv2RepairLogResponseMessage; import org.voltdb.messaging.RejoinMessage; import org.voltdb.VoltDB; import org.voltdb.VoltZK; /** * InitiatorMailbox accepts initiator work and proxies it to the * configured InitiationRole. */ public class InitiatorMailbox implements Mailbox { static boolean LOG_TX = false; static boolean LOG_RX = false; VoltLogger hostLog = new VoltLogger("HOST"); VoltLogger tmLog = new VoltLogger("TM"); private final int m_partitionId; private final InitiatorMessageHandler m_msgHandler; private final HostMessenger m_messenger; private final RepairLog m_repairLog; private final RejoinProducer m_rejoinProducer; private final MapCacheReader m_masterMapCache; private long m_hsId; private Term m_term; private Set<Long> m_replicas = null; // hacky temp txnid AtomicLong m_txnId = new AtomicLong(0); synchronized public void setTerm(Term term) { m_term = term; } public InitiatorMailbox(int partitionId, InitiatorMessageHandler msgHandler, HostMessenger messenger, RepairLog repairLog, RejoinProducer rejoinProducer) { m_partitionId = partitionId; m_msgHandler = msgHandler; m_messenger = messenger; m_repairLog = repairLog; m_rejoinProducer = rejoinProducer; m_masterMapCache = new MapCache(m_messenger.getZK(), VoltZK.iv2masters); try { m_masterMapCache.start(false); } catch (InterruptedException ignored) { // not blocking. shouldn't interrupt. } catch (ExecutionException crashme) { // this on the other hand seems tragic. VoltDB.crashLocalVoltDB("Error constructiong InitiatorMailbox.", false, crashme); } } public void shutdown() throws InterruptedException { m_masterMapCache.shutdown(); } // Provide the starting replica configuration (for startup) public synchronized void setReplicas(List<Long> replicas) { Iv2Trace.logTopology(getHSId(), replicas, m_partitionId); m_msgHandler.updateReplicas(replicas); } // Change the replica set configuration (during or after promotion) public synchronized void updateReplicas(List<Long> replicas) { Iv2Trace.logTopology(getHSId(), replicas, m_partitionId); // If a replica set has been configured and it changed during // promotion, must cancel the term if (m_replicas != null && m_term != null) { m_term.cancel(); } m_replicas = new TreeSet<Long>(); m_replicas.addAll(replicas); m_msgHandler.updateReplicas(replicas); } public long getMasterHsId(int partitionId) { try { JSONObject master = m_masterMapCache.get(Integer.toString(partitionId)); long masterHsId = Long.valueOf(master.getLong("hsid")); return masterHsId; } catch (Exception e) { VoltDB.crashLocalVoltDB("Failed to deserialize map cache reader object.", false, e); } // unreachable. return Long.MIN_VALUE; } @Override public void send(long destHSId, VoltMessage message) { logTxMessage(message); message.m_sourceHSId = this.m_hsId; m_messenger.send(destHSId, message); } @Override public void send(long[] destHSIds, VoltMessage message) { logTxMessage(message); message.m_sourceHSId = this.m_hsId; m_messenger.send(destHSIds, message); } @Override public synchronized void deliver(VoltMessage message) { logRxMessage(message); if (message instanceof Iv2RepairLogRequestMessage) { handleLogRequest(message); return; } else if (message instanceof Iv2RepairLogResponseMessage) { m_term.deliver(message); return; } else if (message instanceof RejoinMessage) { m_rejoinProducer.deliver((RejoinMessage)message); return; } m_repairLog.deliver(message); m_msgHandler.deliver(message); } @Override public VoltMessage recv() { return null; } @Override public void deliverFront(VoltMessage message) { throw new UnsupportedOperationException("unimplemented"); } @Override public VoltMessage recvBlocking() { throw new UnsupportedOperationException("unimplemented"); } @Override public VoltMessage recvBlocking(long timeout) { throw new UnsupportedOperationException("unimplemented"); } @Override public VoltMessage recv(Subject[] s) { throw new UnsupportedOperationException("unimplemented"); } @Override public VoltMessage recvBlocking(Subject[] s) { throw new UnsupportedOperationException("unimplemented"); } @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { throw new UnsupportedOperationException("unimplemented"); } @Override public long getHSId() { return m_hsId; } @Override public void setHSId(long hsId) { this.m_hsId = hsId; } /** Produce the repair log. This is idempotent. */ void handleLogRequest(VoltMessage message) { List<RepairLog.Item> logs = m_repairLog.contents(); int ofTotal = logs.size(); int seq = 1; Iv2RepairLogRequestMessage req = (Iv2RepairLogRequestMessage)message; tmLog.info("SP " + CoreUtils.hsIdToString(getHSId()) + " handling repair log request id " + req.getRequestId() + " for " + CoreUtils.hsIdToString(message.m_sourceHSId) + ". Responding with " + ofTotal + " repair log parts."); if (logs.isEmpty()) { // respond with an ack that the log is empty. // maybe better if seq 0 is always the ack with null payload? Iv2RepairLogResponseMessage response = new Iv2RepairLogResponseMessage( req.getRequestId(), 0, // sequence 0, // total expected Long.MIN_VALUE, // spHandle null); // no payload. just an ack. send(message.m_sourceHSId, response); } else { for (RepairLog.Item log : logs) { Iv2RepairLogResponseMessage response = new Iv2RepairLogResponseMessage( req.getRequestId(), seq, ofTotal, log.getSpHandle(), log.getMessage()); send(message.m_sourceHSId, response); seq++; } } return; } /** * Create a real repair message from the msg repair log contents and * instruct the message handler to execute a repair. */ void repairReplicasWith(List<Long> needsRepair, Iv2RepairLogResponseMessage msg) { VoltMessage repairWork = msg.getPayload(); if (repairWork instanceof Iv2InitiateTaskMessage) { Iv2InitiateTaskMessage m = (Iv2InitiateTaskMessage)repairWork; Iv2InitiateTaskMessage work = new Iv2InitiateTaskMessage(getHSId(), getHSId(), m); m_msgHandler.handleIv2InitiateTaskMessageRepair(needsRepair, work); } } void logRxMessage(VoltMessage message) { Iv2Trace.logInitiatorRxMsg(message, m_hsId); if (LOG_RX) { hostLog.info("RX HSID: " + CoreUtils.hsIdToString(m_hsId) + ": " + message); } } void logTxMessage(VoltMessage message) { if (LOG_TX) { hostLog.info("TX HSID: " + CoreUtils.hsIdToString(m_hsId) + ": " + message); } } }
package org.nschmidt.ldparteditor.data; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow; import org.nschmidt.ldparteditor.text.StringHelper; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; public class HistoryManager { private DatFile df; private boolean hasNoThread = true; private final AtomicBoolean isRunning = new AtomicBoolean(true); private final AtomicInteger action = new AtomicInteger(0); private final ProgressMonitorDialog[] m = new ProgressMonitorDialog[1]; private final SynchronousQueue<Integer> sq = new SynchronousQueue<Integer>(); private final Lock lock = new ReentrantLock(); private Queue<Object[]> workQueue = new ConcurrentLinkedQueue<Object[]>(); public HistoryManager(DatFile df) { this.df = df; } public void pushHistory(String text, int selectionStart, int selectionEnd, GData[] data, boolean[] selectedData, Vertex[] selectedVertices, int topIndex) { if (df.isReadOnly()) return; if (hasNoThread) { hasNoThread = false; new Thread(new Runnable() { @Override public void run() { int pointer = 0; int pointerMax = 0; final ArrayList<Integer> historySelectionStart = new ArrayList<Integer>(); final ArrayList<Integer> historySelectionEnd = new ArrayList<Integer>(); final ArrayList<Integer> historyTopIndex = new ArrayList<Integer>(); final ArrayList<int[]> historyText = new ArrayList<int[]>(); final ArrayList<boolean[]> historySelectedData = new ArrayList<boolean[]>(); final ArrayList<Vertex[]> historySelectedVertices = new ArrayList<Vertex[]>(); while (isRunning.get() && Editor3DWindow.getAlive().get()) { try { Object[] newEntry = workQueue.poll(); if (newEntry != null) { final int[] result; String text = (String) newEntry[0]; GData[] data = (GData[]) newEntry[3]; if (text != null) { result = StringHelper.compress(text); } else if (data != null) { StringBuilder sb = new StringBuilder(); int size = data.length - 1; if (size > 0) { final String ld = StringHelper.getLineDelimiter(); for (int i = 0; i < size; i++) { sb.append(data[i].toString()); sb.append(ld); } sb.append(data[size].toString()); } result = StringHelper.compress(sb.toString()); } else { // throw new AssertionError("There must be data to backup!"); //$NON-NLS-1$ continue; } if (pointer != pointerMax) { // Delete old entries removeFromListAboveOrEqualIndex(historySelectionStart, pointer); removeFromListAboveOrEqualIndex(historySelectionEnd, pointer); removeFromListAboveOrEqualIndex(historySelectedData, pointer); removeFromListAboveOrEqualIndex(historySelectedVertices, pointer); removeFromListAboveOrEqualIndex(historyText, pointer); removeFromListAboveOrEqualIndex(historyTopIndex, pointer); pointerMax = pointer; } // Dont store more than hundred undo/redo entries if (pointerMax > 100) { int delta = pointerMax - 100; removeFromListLessIndex(historySelectionStart, delta); removeFromListLessIndex(historySelectionEnd, delta); removeFromListLessIndex(historySelectedData, delta); removeFromListLessIndex(historySelectedVertices, delta); removeFromListLessIndex(historyText, delta); removeFromListLessIndex(historyTopIndex, delta); pointerMax = pointerMax - delta; if (pointer > 100) { pointer = pointer - delta; } } historySelectionStart.add((Integer) newEntry[1]); historySelectionEnd.add((Integer) newEntry[2]); historySelectedData.add((boolean[]) newEntry[4]); historySelectedVertices.add((Vertex[]) newEntry[5]); historyTopIndex.add((Integer) newEntry[6]); historyText.add(result); // 1. Cleanup duplicated text entries if (pointer > 0) { int pStart = historySelectionStart.get(pointer - 1); int[] previous; int k = 1; while ((previous = historyText.get(pointer - k)) == null) { if (k == pointer) break; k++; } if (previous != null) { if (previous.length == result.length) { boolean match = true; for (int i = 0; i < previous.length; i++) { int v1 = previous[i]; int v2 = result[i]; if (v1 != v2) { match = false; break; } } if (match && !Editor3DWindow.getWindow().isAddingSomething()) { if (pStart != -1) { if ((Integer) newEntry[2] == 0) { // Skip saving this entry since only the cursor was moved removeFromListAboveOrEqualIndex(historySelectionStart, pointer); removeFromListAboveOrEqualIndex(historySelectionEnd, pointer); removeFromListAboveOrEqualIndex(historySelectedData, pointer); removeFromListAboveOrEqualIndex(historySelectedVertices, pointer); removeFromListAboveOrEqualIndex(historyText, pointer); removeFromListAboveOrEqualIndex(historyTopIndex, pointer); } else { // Remove the previous entry, because it only contains a new text selection historySelectionStart.remove(pointer - 1); historySelectionEnd.remove(pointer - 1); historySelectedData.remove(pointer - 1); historySelectedVertices.remove(pointer - 1); historyTopIndex.remove(pointer - 1); if (historyText.get(pointer - 1) == null) { historyText.remove(pointer - 1); historyText.remove(pointer); historyText.add(null); } else { historyText.remove(pointer - 1); } } pointerMax pointer } } } } } // FIXME 2. There is still more cleanup work to do pointerMax++; pointer++; NLogger.debug(getClass(), "Added undo/redo data"); //$NON-NLS-1$ if (workQueue.isEmpty()) Thread.sleep(100); } else { final int action2 = action.get(); int delta = 0; if (action2 > 0) { boolean doRestore = false; switch (action2) { case 1: // Undo if (pointer > 0) { if (pointerMax == pointer && pointer > 1) pointer NLogger.debug(getClass(), "Requested undo. " + (pointer - 1)); //$NON-NLS-1$ pointer delta = -1; doRestore = true; } break; case 2: // Redo if (pointer < pointerMax - 1) { NLogger.debug(getClass(), "Requested redo. " + (pointer + 1) + ' ' + pointerMax); //$NON-NLS-1$ pointer++; delta = 1; doRestore = true; } break; default: break; } if (doRestore) { df.getVertexManager().setSkipSyncWithTextEditor(true); final boolean openTextEditor = historySelectionStart.get(pointer) != -1; boolean hasTextEditor = false; for (EditorTextWindow w : Project.getOpenTextWindows()) { for (final CTabItem t : w.getTabFolder().getItems()) { final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null && txtDat.equals(df)) { hasTextEditor = true; break; } } if (hasTextEditor) break; } while (!hasTextEditor && historySelectionStart.get(pointer) != -1 && pointer > 0 && pointer < pointerMax - 1) { pointer += delta; } final int pointer2 = pointer; int[] text = null; int k = 0; while ((text = historyText.get(pointer2 - k)) == null) { k++; if (pointer2 == k) break; } if (text == null) { action.set(0); return; } sq.offer(10); final String decompressed = StringHelper.decompress(text); Display.getDefault().syncExec(new Runnable() { @Override public void run() { GDataCSG.resetCSG(); GDataCSG.forceRecompile(); Project.getUnsavedFiles().add(df); df.setText(decompressed); sq.offer(20); m[0].getShell().redraw(); m[0].getShell().update(); m[0].getShell().getDisplay().readAndDispatch(); df.parseForData(false); sq.offer(60); m[0].getShell().redraw(); m[0].getShell().update(); m[0].getShell().getDisplay().readAndDispatch(); boolean hasTextEditor = false; try { for (EditorTextWindow w : Project.getOpenTextWindows()) { for (final CTabItem t : w.getTabFolder().getItems()) { final DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj(); if (txtDat != null && txtDat.equals(df)) { int ti = ((CompositeTab) t).getTextComposite().getTopIndex(); Point r = ((CompositeTab) t).getTextComposite().getSelectionRange(); if (openTextEditor) { r.x = historySelectionStart.get(pointer2); r.y = historySelectionEnd.get(pointer2); ti = historyTopIndex.get(pointer2); } ((CompositeTab) t).getState().setSync(true); ((CompositeTab) t).getTextComposite().setText(decompressed); ((CompositeTab) t).getTextComposite().setTopIndex(ti); try { ((CompositeTab) t).getTextComposite().setSelectionRange(r.x, r.y); } catch (IllegalArgumentException consumed) {} ((CompositeTab) t).getTextComposite().redraw(); ((CompositeTab) t).getControl().redraw(); ((CompositeTab) t).getTextComposite().update(); ((CompositeTab) t).getControl().update(); ((CompositeTab) t).getState().setSync(false); hasTextEditor = true; break; } } if (hasTextEditor) break; } } catch (Exception consumed) { NLogger.debug(getClass(), consumed); } final VertexManager vm = df.getVertexManager(); vm.clearSelection2(); final Vertex[] verts = historySelectedVertices.get(pointer2); if (verts != null) { for (Vertex vertex : verts) { vm.getSelectedVertices().add(vertex); } } boolean[] selection = historySelectedData.get(pointer2); if (selection != null) { int i = 0; final HashBiMap<Integer, GData> map = df.getDrawPerLine_NOCLONE(); TreeSet<Integer> ts = new TreeSet<Integer>(map.keySet()); for (Integer key : ts) { if (selection[i]) { GData gd = map.getValue(key); vm.getSelectedData().add(gd); switch (gd.type()) { case 1: vm.getSelectedSubfiles().add((GData1) gd); break; case 2: vm.getSelectedLines().add((GData2) gd); break; case 3: vm.getSelectedTriangles().add((GData3) gd); break; case 4: vm.getSelectedQuads().add((GData4) gd); break; case 5: vm.getSelectedCondlines().add((GData5) gd); break; default: break; } } i++; } ThreadsafeHashMap<GData, Set<VertexInfo>> llv = vm.getLineLinkedToVertices(); for (GData1 g1 : vm.getSelectedSubfiles()) { final Set<VertexInfo> vis = llv.get(g1); if (vis != null) { for (VertexInfo vi : vis) { vm.getSelectedVertices().add(vi.vertex); GData gd = vi.getLinkedData(); vm.getSelectedData().add(gd); switch (gd.type()) { case 2: vm.getSelectedLines().add((GData2) gd); break; case 3: vm.getSelectedTriangles().add((GData3) gd); break; case 4: vm.getSelectedQuads().add((GData4) gd); break; case 5: vm.getSelectedCondlines().add((GData5) gd); break; default: break; } } } } } vm.updateUnsavedStatus(); vm.setModified_NoSync(); vm.setUpdated(true); vm.setSkipSyncWithTextEditor(false); // vm.setSkipSyncWithTextEditor(false); // if (hasTextEditor) { // vm.setModified_NoSync(); // vm.syncWithTextEditors(false); // } else { // vm.setModified(true, false); // if (openTextEditor || hasTextEditor) { // vm.setUpdated(true); Editor3DWindow.getWindow().updateTree_unsavedEntries(); sq.offer(10); } }); } action.set(0); sq.offer(0); } else { if (workQueue.isEmpty()) Thread.sleep(100); } } } catch (InterruptedException e) { } catch (Exception e) { NLogger.debug(getClass(), e); } } // TODO Cleanup the data here } }).start(); } while (!workQueue.offer(new Object[]{text, selectionStart, selectionEnd, data, selectedData, selectedVertices, topIndex})) { try { Thread.sleep(100); } catch (InterruptedException e) {} } } public void deleteHistory() { isRunning.set(false); } public void undo() { if (lock.tryLock()) { try { action(1); } finally { lock.unlock(); } } else { NLogger.debug(getClass(), "Undo was skipped due to synchronisation."); //$NON-NLS-1$ } } public void redo() { if (lock.tryLock()) { try { action(2); } finally { lock.unlock(); } } else { NLogger.debug(getClass(), "Redo was skipped due to synchronisation."); //$NON-NLS-1$ } } private void action(final int mode) { if (df.isReadOnly() || !df.getVertexManager().isUpdated() && WorkbenchManager.getUserSettingState().getSyncWithTextEditor().get()) return; if (action.get() == 0) { BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { @Override public void run() { action.set(mode); Display.getCurrent().readAndDispatch(); } }); } BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { @Override public void run() { try { final ProgressMonitorDialog mon = new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()); mon.run(true, false, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { m[0] = mon; monitor.beginTask("Loading Data...", 100); //$NON-NLS-1$ I18N while (action.get() > 0) { Integer inc = sq.poll(1000, TimeUnit.MILLISECONDS); if (inc != null) { monitor.worked(inc); } } } }); } catch (Exception ex) { NLogger.debug(getClass(), ex); } } }); df.getVertexManager().setSelectedBgPicture(null); df.getVertexManager().setSelectedBgPictureIndex(0); Editor3DWindow.getWindow().updateBgPictureTab(); NLogger.debug(getClass(), "done."); //$NON-NLS-1$ } private void removeFromListAboveOrEqualIndex(List<?> l, int i) { i for (int j = l.size() - 1; j > i; j l.remove(j); } } private void removeFromListLessIndex(List<?> l, int i) { i for (int j = i - 1; j > -1; j l.remove(j); } } public void setDatFile(DatFile df) { this.df = df; } public Lock getLock() { return lock; } }
package org.voltdb.jdbc; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; public class JDBC4Connection implements java.sql.Connection, IVoltDBConnection { public static final String COMMIT_THROW_EXCEPTION = "jdbc.committhrowexception"; public static final String ROLLBACK_THROW_EXCEPTION = "jdbc.rollbackthrowexception"; public static final String QUERYTIMEOUT_UNIT = "jdbc.querytimeout.unit"; protected final JDBC4ClientConnection NativeConnection; protected final String User; protected TimeUnit queryTimeOutUnit = TimeUnit.SECONDS; private boolean isClosed = false; private Properties props; private boolean autoCommit = true; public JDBC4Connection(JDBC4ClientConnection connection, Properties props) { this.NativeConnection = connection; this.props = props; this.User = this.props.getProperty("user", ""); if (this.props.getProperty(JDBC4Connection.QUERYTIMEOUT_UNIT, "Seconds").equalsIgnoreCase("milliseconds")) { this.queryTimeOutUnit = TimeUnit.MILLISECONDS; } } private void checkClosed() throws SQLException { if (this.isClosed()) throw SQLError.get(SQLError.CONNECTION_CLOSED); } // Clears all warnings reported for this Connection object. @Override public void clearWarnings() throws SQLException { checkClosed(); } // Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released. @Override public void close() throws SQLException { try { isClosed = true; JDBC4ClientConnectionPool.dispose(NativeConnection); } catch(Exception x) { throw SQLError.get(x); } } // Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object. @Override public void commit() throws SQLException { checkClosed(); if (props.getProperty(COMMIT_THROW_EXCEPTION, "true").equalsIgnoreCase("true")) { throw SQLError.noSupport(); } } // Factory method for creating Array objects. @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Constructs an object that implements the Blob interface. @Override public Blob createBlob() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Constructs an object that implements the Clob interface. @Override public Clob createClob() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Constructs an object that implements the NClob interface. @Override public NClob createNClob() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Constructs an object that implements the SQLXML interface. @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a Statement object for sending SQL statements to the database. @Override public Statement createStatement() throws SQLException { checkClosed(); try { return new JDBC4Statement(this); } catch(Exception x) { throw SQLError.get(x); } } private static void checkCreateStatementSupported( int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { if ( ( (resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE && resultSetType != ResultSet.TYPE_FORWARD_ONLY)) || resultSetConcurrency != ResultSet.CONCUR_READ_ONLY || resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) { throw SQLError.noSupport(); } } /** * Check if the createStatement() options are supported * * The following flags are supported: * - The type must either be TYPE_SCROLL_INSENSITIVE or TYPE_FORWARD_ONLY. * - The concurrency must be CONCUR_READ_ONLY. * * @param resultSetType JDBC result set type option * @param resultSetConcurrency JDBC result set concurrency option * @throws SQLException if not supported */ private static void checkCreateStatementSupported( int resultSetType, int resultSetConcurrency) throws SQLException { checkCreateStatementSupported(resultSetType, resultSetConcurrency, ResultSet.CLOSE_CURSORS_AT_COMMIT); } // Creates a Statement object that will generate ResultSet objects with the given type and concurrency. @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); // Reject options that don't coincide with normal VoltDB behavior. checkCreateStatementSupported(resultSetType, resultSetConcurrency); return createStatement(); } // Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability. @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); // Reject options that don't coincide with normal VoltDB behavior. checkCreateStatementSupported(resultSetType, resultSetConcurrency, resultSetHoldability); return createStatement(); } // Factory method for creating Struct objects. @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the current auto-commit mode for this Connection object. // We are always auto-committing, but if let's be consistent with the lying. @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } // Retrieves this Connection object's current catalog name. @Override public String getCatalog() throws SQLException { checkClosed(); return ""; } // Returns a list containing the name and current value of each client info property supported by the driver. @Override public Properties getClientInfo() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Returns the value of the client info property specified by name. @Override public String getClientInfo(String name) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the current holdability of ResultSet objects created using this Connection object. @Override public int getHoldability() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a DatabaseMetaData object that contains metadata about the database to which this Connection object represents a connection. @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new JDBC4DatabaseMetaData(this); } // Retrieves this Connection object's current transaction isolation level. @Override public int getTransactionIsolation() throws SQLException { checkClosed(); return TRANSACTION_SERIALIZABLE; } // Retrieves the Map object associated with this Connection object. @Override public Map<String,Class<?>> getTypeMap() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the first warning reported by calls on this Connection object. @Override public SQLWarning getWarnings() throws SQLException { checkClosed(); return null; } // Retrieves whether this Connection object has been closed. @Override public boolean isClosed() throws SQLException { return isClosed; } // Retrieves whether this Connection object is in read-only mode. @Override public boolean isReadOnly() throws SQLException { checkClosed(); return false; } // Returns true if the connection has not been closed and is still valid. @Override public boolean isValid(int timeout) throws SQLException { return !isClosed; } // Converts the given SQL statement into the system's native SQL grammar. @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); return sql; // Well... } // Creates a CallableStatement object for calling database stored procedures. @Override public CallableStatement prepareCall(String sql) throws SQLException { checkClosed(); return new JDBC4CallableStatement(this, sql); } // Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency. @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { if (resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE && resultSetConcurrency == ResultSet.CONCUR_READ_ONLY) return prepareCall(sql); checkClosed(); throw SQLError.noSupport(); } // Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency. @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a PreparedStatement object for sending parameterized SQL statements to the database. @Override public PreparedStatement prepareStatement(String sql) throws SQLException { checkClosed(); return new JDBC4PreparedStatement(this, sql); } // Creates a default PreparedStatement object that has the capability to retrieve auto-generated keys. @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array. @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency. @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { if ((resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE || resultSetType == ResultSet.TYPE_FORWARD_ONLY) && resultSetConcurrency == ResultSet.CONCUR_READ_ONLY) { return prepareStatement(sql); } checkClosed(); throw SQLError.noSupport(); } // Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability. @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array. @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Removes the specified Savepoint and subsequent Savepoint objects from the current transaction. @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object. @Override public void rollback() throws SQLException { checkClosed(); if (props.getProperty(ROLLBACK_THROW_EXCEPTION, "true").equalsIgnoreCase("true")) { throw SQLError.noSupport(); } } // Undoes all changes made after the given Savepoint object was set. @Override public void rollback(Savepoint savepoint) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Sets this connection's auto-commit mode to the given state. @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Always true - error out only if the client is trying to set somethign else if (!autoCommit && (props.getProperty(COMMIT_THROW_EXCEPTION, "true").equalsIgnoreCase("true"))) { throw SQLError.noSupport(); } else { this.autoCommit = autoCommit; } } // Sets the given catalog name in order to select a subspace of this Connection object's database in which to work. @Override public void setCatalog(String catalog) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Sets the value of the connection's client info properties. @Override public void setClientInfo(Properties properties) { // No-op (key client properties cannot be changed after the connection has been opened anyways!) } // Sets the value of the client info property specified by name to the value specified by value. @Override public void setClientInfo(String name, String value) { // No-op (key client properties cannot be changed after the connection has been opened anyways!) } // Changes the default holdability of ResultSet objects created using this Connection object to the given holdability. @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Puts this connection in read-only mode as a hint to the driver to enable database optimizations. @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (!Boolean.parseBoolean(props.getProperty("enableSetReadOnly","false"))){ throw SQLError.noSupport(); } } // Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it. @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it. @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Attempts to change the transaction isolation level for this Connection object to the one given. @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (level == TRANSACTION_SERIALIZABLE) return; throw SQLError.noSupport(); } // Installs the given TypeMap object as the type map for this Connection object. @Override public void setTypeMap(Map<String,Class<?>> map) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an object that does. @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } // Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy. @Override public <T> T unwrap(Class<T> iface) throws SQLException { try { return iface.cast(this); } catch (ClassCastException cce) { throw SQLError.get(SQLError.ILLEGAL_ARGUMENT, iface.toString()); } } /** * Gets the new version of the performance statistics for this connection only. * @return A {@link ClientStatsContext} that correctly represents the client statistics. */ @Override public ClientStatsContext createStatsContext() { return this.NativeConnection.getClientStatsContext(); } // Save statistics to a file @Override public void saveStatistics(ClientStats stats, String file) throws IOException { this.NativeConnection.saveStatistics(stats, file); } public void setSchema(String schema) throws SQLException { throw SQLError.noSupport(); } public String getSchema() throws SQLException { throw SQLError.noSupport(); } public void abort(Executor executor) throws SQLException { throw SQLError.noSupport(); } public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { throw SQLError.noSupport(); } public int getNetworkTimeout() throws SQLException { throw SQLError.noSupport(); } @Override public void writeSummaryCSV(ClientStats stats, String path) throws IOException { this.NativeConnection.writeSummaryCSV(stats, path); } }
// ZAP: 2011/04/16 i18n package org.parosproxy.paros.view; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.Hashtable; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.AbstractDialog; import org.parosproxy.paros.model.Model; import org.zaproxy.zap.extension.help.ExtensionHelp; import org.zaproxy.zap.utils.ZapTextField; public class AbstractParamDialog extends AbstractDialog { private static final long serialVersionUID = -5223178126156052670L; private Object paramObject = null; private Hashtable<String, AbstractParamPanel> tablePanel = new Hashtable<String, AbstractParamPanel>(); private int exitResult = JOptionPane.CANCEL_OPTION; private JPanel jContentPane = null; private JButton btnOK = null; private JButton btnCancel = null; private JButton btnHelp = null; private JPanel jPanel = null; private JSplitPane jSplitPane = null; private JTree treeParam = null; private JPanel jPanel1 = null; private JPanel panelParam = null; private JPanel panelHeadline = null; private ZapTextField txtHeadline = null; private DefaultTreeModel treeModel = null; // @jve:decl-index=0:parse,visual-constraint="14,12" private DefaultMutableTreeNode rootNode = null; // @jve:decl-index=0:parse,visual-constraint="10,50" private JScrollPane jScrollPane = null; private JScrollPane jScrollPane1 = null; // ZAP: show the last selected panel private String nameLastSelectedPanel = null; private ShowHelpAction showHelpAction = null; // ZAP: Added logger private static Logger log = Logger.getLogger(AbstractParamDialog.class); public AbstractParamDialog() { super(); initialize(); } /** * @param arg0 * @throws HeadlessException */ public AbstractParamDialog(Frame parent, boolean modal, String title, String rootName) throws HeadlessException { super(parent, modal); initialize(); this.setTitle(title); getRootNode().setUserObject(rootName); } /** * This method initializes this * * @return void */ private void initialize() { // enables the options dialog to be in front, but an modal dialog // stays on top of the main application window, but doesn't block childs // Examples of childs: help window and client certificate viewer this.setModalityType(ModalityType.DOCUMENT_MODAL); this.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) { this.setSize(500, 375); } this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); this.setContentPane(getJContentPane()); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private javax.swing.JPanel getJContentPane() { if (jContentPane == null) { java.awt.GridBagConstraints gridBagConstraints1 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints14 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints13 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints12 = new GridBagConstraints(); javax.swing.JLabel jLabel = new JLabel(); jContentPane = new javax.swing.JPanel(); jContentPane.setLayout(new GridBagLayout()); jLabel.setName("jLabel"); jLabel.setText(""); gridBagConstraints12.gridx = 0; gridBagConstraints12.gridy = 1; gridBagConstraints12.ipadx = 0; gridBagConstraints12.ipady = 0; gridBagConstraints12.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints12.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints12.insets = new java.awt.Insets(2,2,2,2); gridBagConstraints12.weightx = 1.0D; gridBagConstraints13.gridx = 1; gridBagConstraints13.gridy = 1; gridBagConstraints13.ipadx = 0; gridBagConstraints13.ipady = 0; gridBagConstraints13.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints13.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints13.insets = new java.awt.Insets(2,2,2,2); gridBagConstraints14.gridx = 2; gridBagConstraints14.gridy = 1; gridBagConstraints14.ipadx = 0; gridBagConstraints14.ipady = 0; gridBagConstraints14.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints14.insets = new java.awt.Insets(2,2,2,2); gridBagConstraints1.weightx = 1.0; gridBagConstraints1.weighty = 1.0; gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints1.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints1.gridwidth = 3; gridBagConstraints1.gridx = 0; gridBagConstraints1.gridy = 0; jContentPane.add(getJSplitPane(), gridBagConstraints1); jContentPane.add(jLabel, gridBagConstraints12); jContentPane.add(getBtnOK(), gridBagConstraints13); jContentPane.add(getBtnCancel(), gridBagConstraints14); } return jContentPane; } /** * This method initializes btnOK * * @return javax.swing.JButton */ private JButton getBtnOK() { if (btnOK == null) { btnOK = new JButton(); btnOK.setName("btnOK"); btnOK.setText(Constant.messages.getString("all.button.ok")); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { try { validateParam(); saveParam(); exitResult = JOptionPane.OK_OPTION; AbstractParamDialog.this.setVisible(false); } catch (Exception ex) { View.getSingleton().showWarningDialog(ex.getMessage()); } } }); } return btnOK; } /** * This method initializes btnCancel * * @return javax.swing.JButton */ protected JButton getBtnCancel() { if (btnCancel == null) { btnCancel = new JButton(); btnCancel.setName("btnCancel"); btnCancel.setText(Constant.messages.getString("all.button.cancel")); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { exitResult = JOptionPane.CANCEL_OPTION; AbstractParamDialog.this.setVisible(false); } }); } return btnCancel; } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { java.awt.GridBagConstraints gridBagConstraints7 = new GridBagConstraints(); java.awt.GridBagConstraints gridBagConstraints5 = new GridBagConstraints(); gridBagConstraints5.gridwidth = 2; java.awt.GridBagConstraints gridBagConstraints2 = new GridBagConstraints(); jPanel = new JPanel(); jPanel.setLayout(new GridBagLayout()); jPanel.setName("jPanel"); gridBagConstraints2.weightx = 1.0; gridBagConstraints2.weighty = 1.0; gridBagConstraints2.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints5.gridx = 0; gridBagConstraints5.gridy = 1; gridBagConstraints5.ipadx = 0; gridBagConstraints5.ipady = 0; gridBagConstraints5.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints5.weightx = 1.0D; gridBagConstraints5.weighty = 1.0D; gridBagConstraints5.insets = new Insets(2, 5, 5, 0); gridBagConstraints5.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints7.weightx = 1.0; gridBagConstraints7.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints7.gridx = 0; gridBagConstraints7.gridy = 0; gridBagConstraints7.insets = new Insets(2, 5, 5, 0); jPanel.add(getPanelHeadline(), gridBagConstraints7); jPanel.add(getPanelParam(), gridBagConstraints5); GridBagConstraints gbc_button = new GridBagConstraints(); gbc_button.insets = new Insets(0, 5, 0, 5); gbc_button.gridx = 1; gbc_button.gridy = 0; jPanel.add(getHelpButton(), gbc_button); } return jPanel; } /** * This method initializes jSplitPane * * @return javax.swing.JSplitPane */ private JSplitPane getJSplitPane() { if (jSplitPane == null) { jSplitPane = new JSplitPane(); jSplitPane.setContinuousLayout(true); jSplitPane.setVisible(true); jSplitPane.setRightComponent(getJPanel1()); jSplitPane.setDividerLocation(175); jSplitPane.setDividerSize(3); jSplitPane.setResizeWeight(0.3D); jSplitPane.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.LOWERED)); jSplitPane.setLeftComponent(getJScrollPane()); } return jSplitPane; } /** * This method initializes treeParam * * @return javax.swing.JTree */ private JTree getTreeParam() { if (treeParam == null) { treeParam = new JTree(); treeParam.setModel(getTreeModel()); treeParam.setShowsRootHandles(true); treeParam.setRootVisible(true); treeParam.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) getTreeParam().getLastSelectedPathComponent(); if (node == null) return; String name = (String) node.getUserObject(); showParamPanel(name); } }); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(null); renderer.setOpenIcon(null); renderer.setClosedIcon(null); treeParam.setCellRenderer(renderer); treeParam.setRowHeight(18); } return treeParam; } /** * This method initializes jPanel1 * * @return javax.swing.JPanel */ private JPanel getJPanel1() { if (jPanel1 == null) { jPanel1 = new JPanel(); jPanel1.setLayout(new CardLayout()); jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0)); jPanel1.add(getJScrollPane1(), getJScrollPane1().getName()); } return jPanel1; } /** * This method initializes panelParam * * @return javax.swing.JPanel */ protected JPanel getPanelParam() { if (panelParam == null) { panelParam = new JPanel(); panelParam.setLayout(new CardLayout()); panelParam.setPreferredSize(new java.awt.Dimension(300,300)); panelParam.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0)); } return panelParam; } /** * @return */ private JPanel getPanelHeadline() { if (panelHeadline == null) { panelHeadline = new JPanel(); panelHeadline.setLayout(new BorderLayout(0, 0)); txtHeadline = getTxtHeadline(); panelHeadline.add(txtHeadline, BorderLayout.CENTER); JButton button = getHelpButton(); panelHeadline.add(button, BorderLayout.EAST); } return panelHeadline; } /** * This method initializes txtHeadline * * @return javax.swing.ZapTextField */ private ZapTextField getTxtHeadline() { if (txtHeadline == null) { txtHeadline = new ZapTextField(); txtHeadline.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED)); txtHeadline.setEditable(false); txtHeadline.setEnabled(false); txtHeadline.setBackground(java.awt.Color.white); txtHeadline.setFont(new java.awt.Font("Default", java.awt.Font.BOLD, 12)); } return txtHeadline; } /** * This method initializes treeModel * * @return javax.swing.tree.DefaultTreeModel */ private DefaultTreeModel getTreeModel() { if (treeModel == null) { treeModel = new DefaultTreeModel(getRootNode()); treeModel.setRoot(getRootNode()); } return treeModel; } /** * This method initializes rootNode * * @return javax.swing.tree.DefaultMutableTreeNode */ protected DefaultMutableTreeNode getRootNode() { if (rootNode == null) { rootNode = new DefaultMutableTreeNode("Root"); } return rootNode; } private DefaultMutableTreeNode addParamNode(String[] paramSeq) { String param = null; DefaultMutableTreeNode parent = getRootNode(); DefaultMutableTreeNode child = null; DefaultMutableTreeNode result = null; for (int i=0; i<paramSeq.length; i++) { param = paramSeq[i]; result = null; for (int j=0; j<parent.getChildCount(); j++) { child = (DefaultMutableTreeNode) parent.getChildAt(j); if (child.toString().equalsIgnoreCase(param)) { result = child; break; } } if (result == null) { result = new DefaultMutableTreeNode(param); parent.add(result); } parent = result; } return parent; } /** * If multiple name use the same panel * @param parentParams * @param name * @param panel */ // ZAP: Added sort option public void addParamPanel(String[] parentParams, String name, AbstractParamPanel panel, boolean sort) { if (parentParams != null) { DefaultMutableTreeNode parent = addParamNode(parentParams); DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(name); boolean added = false; if (sort) { for (int i=0; i < parent.getChildCount(); i++) { if (name.compareToIgnoreCase(parent.getChildAt(i).toString()) < 0) { parent.insert(newNode, i); added = true; break; } } } if (! added) { parent.add(newNode); } } else { // No need to create node. This is the root panel. } panel.setName(name); getPanelParam().add(panel, name); tablePanel.put(name, panel); } public void addParamPanel(String[] parentParams, AbstractParamPanel panel, boolean sort) { addParamPanel(parentParams, panel.getName(), panel, sort); } // ZAP: Made public so that other classes can specify which panel is displayed public void showParamPanel(String name) { if (name == null || name.equals("")) return; // exit if panel name not found. AbstractParamPanel panel = tablePanel.get(name); if (panel == null) return; // ZAP: show the last selected panel nameLastSelectedPanel = name; getPanelHeadline(); getTxtHeadline().setText(name); getHelpButton().setVisible(panel.getHelpIndex() != null); getShowHelpAction().setHelpIndex(panel.getHelpIndex()); CardLayout card = (CardLayout) getPanelParam().getLayout(); card.show(getPanelParam(), name); } public void initParam(Object obj) { paramObject = obj; Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while(en.hasMoreElements()) { panel = en.nextElement(); panel.initParam(obj); } } /** * This method is to be overrided by subclass. * */ public void validateParam() throws Exception { Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while(en.hasMoreElements()) { panel = en.nextElement(); panel.validateParam(paramObject); } } /** * This method is to be overrided by subclass. * */ public void saveParam() throws Exception { Enumeration<AbstractParamPanel> en = tablePanel.elements(); AbstractParamPanel panel = null; while(en.hasMoreElements()) { panel = en.nextElement(); panel.saveParam(paramObject); } } protected void expandRoot() { getTreeParam().expandPath(new TreePath(getRootNode())); } public int showDialog(boolean showRoot) { return showDialog(showRoot, null); } // ZAP: Added option to specify panel - note this only supports one level at the moment // ZAP: show the last selected panel public int showDialog(boolean showRoot, String panel) { expandRoot(); try { DefaultMutableTreeNode node = null; if (panel != null) { node = getTreeNodeFromPanelName(panel); } if (node == null) { if (nameLastSelectedPanel != null) { node = getTreeNodeFromPanelName(nameLastSelectedPanel); } else if (showRoot) { node = (DefaultMutableTreeNode) getTreeModel().getRoot(); } else { node = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildAt(0); } } showParamPanel(node.toString()); getTreeParam().setSelectionPath(new TreePath(node.getPath())); } catch (Exception e) { // ZAP: log errors log.error(e.getMessage(), e); } this.setVisible(true); return exitResult; } // ZAP: show the last selected panel private DefaultMutableTreeNode getTreeNodeFromPanelName(String panel) { DefaultMutableTreeNode node = null; Enumeration<DefaultMutableTreeNode> children = ((DefaultMutableTreeNode) getTreeModel().getRoot()).children(); while (children.hasMoreElements()) { DefaultMutableTreeNode child = children.nextElement(); if (panel.equals(child.toString())) { node = child; break; } } return node; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setViewportView(getTreeParam()); jScrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(0,0,0,0)); } return jScrollPane; } /** * This method initializes jScrollPane1 * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane1() { if (jScrollPane1 == null) { jScrollPane1 = new JScrollPane(); jScrollPane1.setName("jScrollPane1"); jScrollPane1.setViewportView(getJPanel()); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_NEVER); } return jScrollPane1; } /** * This method initializes the help button, if any button can be applied * @return */ private JButton getHelpButton() { if (btnHelp == null) { btnHelp = new JButton(); btnHelp.setBorder(null); btnHelp.setIcon(new ImageIcon(getClass().getResource("/resource/icon/16/201.png"))); // help icon btnHelp.addActionListener(getShowHelpAction()); btnHelp.setToolTipText(Constant.messages.getString("menu.help")); } return btnHelp; } private ShowHelpAction getShowHelpAction() { if (showHelpAction == null) { showHelpAction = new ShowHelpAction(); } return showHelpAction; } /** * Displays the current help by index ... */ private static final class ShowHelpAction implements ActionListener { private String helpIndex = null; @Override public void actionPerformed(ActionEvent e) { if (helpIndex != null) { ExtensionHelp.showHelp(helpIndex); } } public void setHelpIndex(String helpIndex) { this.helpIndex = helpIndex; } } } // @jve:decl-index=0:visual-constraint="73,11"
package org.usfirst.frc.team166.robot.subsystems; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Preferences; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team166.robot.PIDSpeedController; import org.usfirst.frc.team166.robot.RobotMap; public class Lift extends Subsystem { DigitalInput boundaryLimit; Talon motor; Encoder encoder; Solenoid brake; LiftMovement movementState; PIDSpeedController pid; String subsystemName; // This enum describes the movement state of a lift. public enum LiftMovement { Stopped, Up, Down } // This enum describes which carriage is pushing during a collision public enum WhichCarriagePushing { RC, Tote, None, Both } // Constructor public Lift(int motorChannel, int brakeChannel, int encoderChannelA, int encoderChannelB, int boundaryLimitChannel, String subsystem) { motor = new Talon(motorChannel); brake = new Solenoid(brakeChannel); encoder = new Encoder(encoderChannelA, encoderChannelB); boundaryLimit = new DigitalInput(boundaryLimitChannel); LiveWindow.addActuator(subsystem, "Motor", motor); LiveWindow.addActuator(subsystem, "Brake", brake); LiveWindow.addSensor(subsystem, "Encoder", encoder); LiveWindow.addSensor(subsystem, "Boundary Limit Switch", boundaryLimit); pid = new PIDSpeedController(encoder, motor, subsystem, "Speed Control"); subsystemName = subsystem; } public void moveUp() { releaseBrake(); pid.set(getLiftSpeed()); } public void moveDown() { releaseBrake(); pid.set(-getLiftSpeed()); } public void stop() { pid.set(0); setBrake(); } // Move lift to given position public void moveLiftToPosition(double position) { double tolerance = Preferences.getInstance().getDouble(RobotMap.Prefs.LiftPosTolerance, 10); if (encoder.getDistance() > position + tolerance) { pid.set(-getLiftSpeed()); } else if (encoder.getDistance() < position - tolerance) { pid.set(getLiftSpeed()); } } public boolean isAtTargetPos(double position) { double tolerance = Preferences.getInstance().getDouble(RobotMap.Prefs.LiftPosTolerance, 10); return (encoder.getDistance() < position + tolerance && encoder.getDistance() > position - tolerance); } // Given lift move states, decides which carriage is pushing in a collision, and sets WhichCarriageMoving public static WhichCarriagePushing collisionMovement(LiftMovement rcMoveState, LiftMovement toteMoveState) { if (rcMoveState == LiftMovement.Stopped && toteMoveState == LiftMovement.Up) return WhichCarriagePushing.Tote; else if (rcMoveState == LiftMovement.Down && toteMoveState == LiftMovement.Stopped) return WhichCarriagePushing.RC; else if (rcMoveState == LiftMovement.Down && toteMoveState == LiftMovement.Up) return WhichCarriagePushing.Both; else return WhichCarriagePushing.None; } // Set Speed PID constants from preferences public void setPIDConstants() { double p = Preferences.getInstance().getDouble(subsystemName + RobotMap.Prefs.LiftSpeedP, 0); double i = Preferences.getInstance().getDouble(subsystemName + RobotMap.Prefs.LiftSpeedI, 0); double d = Preferences.getInstance().getDouble(subsystemName + RobotMap.Prefs.LiftSpeedD, 0); double f = Preferences.getInstance().getDouble(subsystemName + RobotMap.Prefs.LiftSpeedF, 0); pid.setConstants(p, i, d, f); encoder.setDistancePerPulse(Preferences.getInstance().getDouble( subsystemName + RobotMap.Prefs.LiftDistPerPulse, 0)); } // Returns whether or not the lift boundary limit switch is hit public boolean isBoundaryHit() { return boundaryLimit.get(); } public LiftMovement getMoveState() { return movementState; } // Activate brake private void setBrake() { brake.set(true); } // Deactivate brake public void releaseBrake() { brake.set(false); } public void resetEncoder() { encoder.reset(); } // Get the max of the preference and zero so a negative doesn't change directions private double getLiftSpeed() { return Math.max(Preferences.getInstance().getDouble(RobotMap.Prefs.LiftSpeed, 0), 0); } @Override public void initDefaultCommand() { } }
package org.usfirst.frc3219.TREAD.subsystems; import org.usfirst.frc3219.TREAD.RobotMap; import org.usfirst.frc3219.TREAD.commands.GearPiston; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; public class GearSlot extends Subsystem { private Solenoid piston; private boolean out = false; @Override protected void initDefaultCommand() { piston = RobotMap.gearPiston; out = piston.get(); //this.setDefaultCommand(new GearPiston(false)); } public void changePosition() { out = !out; piston.set(out); } public void setPosition(boolean pos) { if (out != pos) { piston.set(pos); out = pos; } } public static void initializeMotors() { RobotMap.gearPiston = new Solenoid(RobotMap.GEAR_SOLENOID_INDEX); } }
package protocolsupport.protocol; import java.nio.charset.StandardCharsets; import protocolsupport.protocol.DataStorage.ProtocolVersion; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.CorruptedFrameException; public class InitialPacketDecoder extends ChannelInboundHandlerAdapter { @Override public void channelRead(final ChannelHandlerContext channelHandlerContext, final Object inputObj) throws Exception { try { ByteBuf input = (ByteBuf) inputObj; if (input.readableBytes() == 0) { return; } //detect protocol ProtocolVersion handshakeversion = ProtocolVersion.UNKNOWN; input.markReaderIndex(); int firstbyte = input.readUnsignedByte(); if (firstbyte == 0xFE) { //1.6 ping or 1.5 ping (should we check if FE is actually a part of a varint length?) try { if (input.readUnsignedByte() == 1) { if (input.readableBytes() == 0) { //1.5.2 handshakeversion = ProtocolVersion.MINECRAFT_1_5_2; input.resetReaderIndex(); } else if ( input.readUnsignedByte() == 0xFA && "MC|PingHost".equals(new String(input.readBytes(input.readUnsignedShort() * 2).array(), StandardCharsets.UTF_16BE)) ) { input.readUnsignedShort(); handshakeversion = ProtocolVersion.fromId(input.readUnsignedByte()); input.resetReaderIndex(); } } } catch (IndexOutOfBoundsException ex) { input.resetReaderIndex(); } } else if (firstbyte == 0x02) { //1.6 or 1.5.2 handshake handshakeversion = ProtocolVersion.fromId(input.readUnsignedByte()); input.resetReaderIndex(); } else { //1.7 handshake input.resetReaderIndex(); input.markReaderIndex(); ByteBuf data = getVarIntPrefixedData(input); if (data != null) { handshakeversion = read1_7_1_8Handshake(data); } input.resetReaderIndex(); } //if we detected the protocol than we save it and process data if (handshakeversion != ProtocolVersion.UNKNOWN) { DataStorage.setVersion(channelHandlerContext.channel().remoteAddress(), handshakeversion); rebuildPipeLine(channelHandlerContext, input, handshakeversion); } } catch (Throwable t) { channelHandlerContext.channel().close(); } } private void rebuildPipeLine(final ChannelHandlerContext ctx, final ByteBuf input, ProtocolVersion version) throws Exception { ctx.channel().pipeline().remove(InitialPacketDecoder.class); switch (version) { case MINECRAFT_1_8: { protocolsupport.protocol.v_1_8.PipeLineBuilder.buildPipeLine(ctx); break; } case MINECRAFT_1_7_5: case MINECRAFT_1_7_10: { protocolsupport.protocol.v_1_7.PipeLineBuilder.buildPipeLine(ctx); break; } case MINECRAFT_1_6_2: case MINECRAFT_1_6_4: { protocolsupport.protocol.v_1_6.PipeLineBuilder.buildPipeLine(ctx); break; } case MINECRAFT_1_5_2: { protocolsupport.protocol.v_1_5.PipeLineBuilder.buildPipeLine(ctx); break; } default: { throw new RuntimeException("Not supported yet"); } } ctx.channel().pipeline().firstContext().fireChannelRead(input); } private ByteBuf getVarIntPrefixedData(final ByteBuf byteBuf) { final byte[] array = new byte[3]; for (int i = 0; i < array.length; ++i) { if (!byteBuf.isReadable()) { return null; } array[i] = byteBuf.readByte(); if (array[i] >= 0) { final int length = readVarInt(Unpooled.wrappedBuffer(array)); if (byteBuf.readableBytes() < length) { return null; } return byteBuf.readBytes(length); } } throw new CorruptedFrameException("Packet length is wider than 21 bit"); } private ProtocolVersion read1_7_1_8Handshake(ByteBuf data) { if (readVarInt(data) == 0x00) { return ProtocolVersion.fromId(readVarInt(data)); } return ProtocolVersion.UNKNOWN; } private int readVarInt(ByteBuf data) { int value = 0; int length = 0; byte b0; do { b0 = data.readByte(); value |= (b0 & 0x7F) << length++ * 7; if (length > 5) { throw new RuntimeException("VarInt too big"); } } while ((b0 & 0x80) == 0x80); return value; } }
package protocolsupport.protocol.utils.types; import java.text.MessageFormat; import protocolsupport.utils.CollectionsUtils; import protocolsupport.utils.CollectionsUtils.ArrayMap; public enum GameMode { NOT_SET(-1), SURVIVAL(0), CREATIVE(1), ADVENTURE(2), SPECTATOR(3); private static final ArrayMap<GameMode> byId = CollectionsUtils.makeEnumMappingArrayMap(GameMode.class, GameMode::getId); private final int id; GameMode(int id) { this.id = id; } public int getId() { return id; } public static GameMode getById(int id) { GameMode gm = byId.get(id); if (gm == null) { throw new IllegalArgumentException(MessageFormat.format("Unknown gamemode network id {0}", id)); } return gm; } }
package gov.nih.nci.calab.dto.workflow; import java.util.List; public class AssayBean { private String assayId; private String assayName; private String assayType; private String assayStr; private List<RunBean> runBeans; public AssayBean() { super(); } public AssayBean(String assayId, String assayName, String assayType) { super(); // TODO Auto-generated constructor stub this.assayId = assayId; this.assayName = assayName; this.assayType = assayType; } public String getAssayId() { return assayId; } public void setAssayId(String assayId) { this.assayId = assayId; } public String getAssayName() { return assayName; } public void setAssayName(String assayName) { this.assayName = assayName; } public String getAssayType() { return assayType; } public void setAssayType(String assayType) { this.assayType = assayType; } public String getAssayStr() { return this.assayType + " : " + this.assayName; } // public void setAssayStr(String assayStr) { // this.assayStr = assayStr; public List<RunBean> getRunBeans() { return runBeans; } public void setRunBeans(List<RunBean> runBeans) { this.runBeans = runBeans; } }
package gr.phaistosnetworks.tank; import org.xerial.snappy.Snappy; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; /** * Purpose: To perform magic tricks on bytes. */ public class ByteManipulator { /** * Constructor that sets the byte array to be manipulated. * * @param input the byte array to be manipulated; */ public ByteManipulator(byte[] input) { this.input = input; this.offset = 0; } /** * Constructor that sets the byte array from ByteBuffer. * * @param input the ByteBuffer to be manipulated; */ public ByteManipulator(ByteBuffer input, int bbLength) { this.input = new byte[bbLength]; input.get(this.input); this.offset = 0; } /** * Appends a byte array to the current one. * * @param toAppend the byte array to append. */ public void append(byte[] toAppend) { byte [] souma = new byte[input.length + toAppend.length]; for (int i = 0; i < input.length; i++) { souma[i] = input[i]; } for (int i = 0; i < toAppend.length; i++) { souma[input.length + i] = toAppend[i]; } this.input = souma; } /** * Appends a ByteBuffer to the current Byte array. * * @param toAppend the ByteBuffer to append. */ public void append(ByteBuffer toAppend, int bbLength) { byte [] souma = new byte[input.length + bbLength]; for (int i = 0; i < input.length; i++) { souma[i] = input[i]; } for (int i = 0; i < bbLength; i++) { souma[input.length + i] = toAppend.get(); } this.input = souma; } /** * Returns the next length bytes from the current byte array. * There is no health check. If you request more bytes than available, boom * * @param length the amount of bytes to return * @return a byte array containing the requested length of bytes */ public byte[] getNextBytes(int length) { byte [] bar = new byte[length]; for (int i = 0; i < length; i++) { bar[i] = input[offset + i]; } offset += length; return bar; } /** * Compress data using the snappy library. * * @param data the data to compress * @return the compressed data. */ public static byte[] snappyCompress(byte [] data) throws IOException { return Snappy.compress(data); } /** * Uncompress the next length bytes using the snappy library. * * @param length the amount of bytes to uncompress * @return the uncompressed data. */ public byte[] snappyUncompress(long length) throws IOException { byte [] toUnCompress = new byte[(int)length]; for (int i = 0; i < length; i++) { toUnCompress[i] = input[offset + i]; } offset += length; return Snappy.uncompress(toUnCompress); } /** * Serializes a long into a byte array with length * * @param length the length of the returned byte array * @param data the long to process. * @return the serialized data. */ public static byte[] serialize(long data, int length) { byte[] output = new byte[length]; long shift = 0L; for (int i = 0; i < length; i++) { shift = i * Byte.SIZE; output[i] = (byte) (data >> shift); } return output; } /** * Deserializes the next length bytes and returns a long. * * @param length the amount of bytes to deserialize. * @return the value of those bytes. */ public long deSerialize(int length) { long result = 0L; for (int i = 0, n = 0; i != length; ++i, n += Byte.SIZE) { long mask = input[offset + i] & BYTE_MAX; result |= (mask << n); } offset += length; return result; } /** * Sets the leftmost bit to 0 * int is used due to need of unsigned bytes. * * @param toFlip the byte to flip * @return int containing the byte. */ private int flipped(byte toFlip) { return asInt(toFlip & ~(1 << VARINT_BYTE_SHIFT_ONE)); } /** * Flips the leftmost bit of the last byte of a long. * * @param toFlip the long that needs it's last byte flipped. * @return the flipped byte */ private static byte asFlipped(long toFlip) { return (byte)(toFlip | (1 << VARINT_BYTE_SHIFT_ONE)); } /** * Returns the integer value of a byte, as if it was unsigned. * * @param val the value to get integer value for. * @return positive integer value of that byte. */ private int asInt(int val) { if (val < 0) { return (val + BYTE_MAX + 1); } else { return val; } } /** * Reads a varint from the next unprocessed bytes of the current array. * * @return the value of the varint */ public long getVarInt() { long result = 0; int length = 0; if (asInt(input[offset]) > VARINT_BYTE_MAX) { if (asInt(input[offset + 1]) > VARINT_BYTE_MAX) { if (asInt(input[offset + 2]) > VARINT_BYTE_MAX) { if (asInt(input[offset + 3]) > VARINT_BYTE_MAX) { length = 5; result |= flipped(input[offset]) | (flipped(input[offset + 1]) << VARINT_BYTE_SHIFT_ONE) | (flipped(input[offset + 2]) << VARINT_BYTE_SHIFT_TWO) | (flipped(input[offset + 3]) << VARINT_BYTE_SHIFT_THREE) | (asInt(input[offset + 4]) << VARINT_BYTE_SHIFT_FOUR); } else { length = 4; result |= flipped(input[offset]) | (flipped(input[offset + 1]) << VARINT_BYTE_SHIFT_ONE) | (flipped(input[offset + 2]) << VARINT_BYTE_SHIFT_TWO) | (asInt(input[offset + 3]) << VARINT_BYTE_SHIFT_THREE); } } else { length = 3; result |= flipped(input[offset]) | (flipped(input[offset + 1]) << VARINT_BYTE_SHIFT_ONE) | (asInt(input[offset + 2]) << VARINT_BYTE_SHIFT_TWO); } } else { length = 2; result |= flipped(input[offset]) | (asInt(input[offset + 1]) << VARINT_BYTE_SHIFT_ONE); } } else { result |= asInt(input[offset]); length = 1; } offset += length; return result; } /** * Transforms a long into a varint byte array. * The implementation is based on @mpapadakis varint conversion. * It is hard coded up to 5 bytes long, so it can support 32bit unsigned integers. * Anything more than that and it will blow up in your face. * * @param num the number to be transformed * @return the varint */ public static byte[] getVarInt(long num) throws TankException { if (num > UINT32_MAX) { throw new TankException("Number Too Large (max " + UINT32_MAX + "): " + num); } byte[] result = new byte[0]; if (num < (1 << VARINT_BYTE_SHIFT_ONE)) { result = new byte[1]; result[0] = (byte)num; } else if (num < (1 << VARINT_BYTE_SHIFT_TWO)) { result = new byte[2]; result[0] = asFlipped(num); result[1] = (byte)(num >> VARINT_BYTE_SHIFT_ONE); } else if (num < (1 << VARINT_BYTE_SHIFT_THREE)) { result = new byte[3]; result[0] = asFlipped(num); result[1] = asFlipped(num >> VARINT_BYTE_SHIFT_ONE); result[2] = (byte)(num >> VARINT_BYTE_SHIFT_TWO); } else if (num < (1 << VARINT_BYTE_SHIFT_FOUR)) { result = new byte[4]; result[0] = asFlipped(num); result[1] = asFlipped(num >> VARINT_BYTE_SHIFT_ONE); result[2] = asFlipped(num >> VARINT_BYTE_SHIFT_TWO); result[3] = (byte)(num >> VARINT_BYTE_SHIFT_THREE); } else { result = new byte[5]; result[0] = asFlipped(num); result[1] = asFlipped(num >> VARINT_BYTE_SHIFT_ONE); result[2] = asFlipped(num >> VARINT_BYTE_SHIFT_TWO); result[3] = asFlipped(num >> VARINT_BYTE_SHIFT_THREE); result[4] = (byte)(num >> VARINT_BYTE_SHIFT_FOUR); } return result; } /** * Returns a String using the str8 notation. */ public String getStr8() { int length = asInt(input[offset]); offset++; byte [] op = new byte[length]; for (int i = 0; i < length; i++) { op[i] = input[offset + i]; } offset += length; return new String(op); } /** * Returns a byte array in str8 notation of the given String. * * @param data the string to encode */ public static byte[] getStr8(String data) throws TankException, UnsupportedEncodingException { return getStr8(data.getBytes("ASCII")); } /** * Returns a byte array in str8 notation of the given byte[]. * * @param data the byte[] to encode */ public static byte[] getStr8(byte[] data) throws TankException { if (data.length > BYTE_MAX) { throw new TankException("Str8 too long (max " + BYTE_MAX + " chars): " + new String(data)); } int length = data.length; byte [] out = new byte[length + 1]; out[0] = (byte)length; int pos = 1; for (byte b : data) { out[pos++] = b; } return out; } /** * Returns the amount of unprocessed bytes left. */ public int getRemainingLength() { return input.length - offset; } /** * Flushes processed bytes from byte array. */ @Deprecated public void flushOffset() { offsetMark = offset; byte [] newInput = new byte[getRemainingLength()]; for (int i = 0; i < getRemainingLength(); i++) { newInput[i] = input[offset + i]; } input = newInput; offset = 0; } /** * Retuns the current count of processed bytes. */ public int getOffset() { return offset; } /** * Marks the current offset position. */ public void markOffset() { offsetMark = offset; } /** * Returns the current count of processed bytes since the Mark. */ public int getMarkedOffset() { return offset - offsetMark; } /** * Resets current processed byte counter. */ public void resetOffset() { offset = 0; offsetMark = 0; } /** * prints all bytes in current byte array. */ public void printBytes() { offset = 0; for (int i = 0 ; i < input.length ; i++) { System.out.format("%d ", input[i]); } } private byte [] input; private int offset; private int offsetMark; private static final byte VARINT_BYTE_SHIFT_ONE = 7; private static final byte VARINT_BYTE_SHIFT_TWO = 14; private static final byte VARINT_BYTE_SHIFT_THREE = 21; private static final byte VARINT_BYTE_SHIFT_FOUR = 28; private static final byte VARINT_BYTE_MAX = 127; private static final int BYTE_MAX = 255; private static final long UINT32_MAX = 4294967295L; }
package info.justaway; import android.app.Dialog; import android.content.DialogInterface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.Gravity; import android.widget.ImageView; import android.widget.LinearLayout; import java.io.File; import twitter4j.User; import static android.app.AlertDialog.Builder; public class UpdateProfileImageFragment extends DialogFragment { private File imgPath; private Uri uri; public UpdateProfileImageFragment(File imgPath, Uri uri) { this.imgPath = imgPath; this.uri = uri; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new Builder(getActivity()); builder.setTitle(""); // LinearLayout LinearLayout layout = new LinearLayout(getActivity()); layout.setGravity(Gravity.CENTER); ImageView image = new ImageView(getActivity()); image.setScaleType(ImageView.ScaleType.CENTER_CROP); image.setLayoutParams(new LinearLayout.LayoutParams( 340, 340)); JustawayApplication.getApplication().displayImage(uri.toString(), image); layout.addView(image); builder.setView(layout); builder.setPositiveButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new UpdateProfileImageTask().execute(); dismiss(); } }); builder.setNegativeButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); } private class UpdateProfileImageTask extends AsyncTask<Void, Void, User> { @Override protected User doInBackground(Void... params) { try { User user = JustawayApplication.getApplication().getTwitter().updateProfileImage(imgPath); return user; } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(User user) { // dismissProgressDialog(); JustawayApplication application = JustawayApplication.getApplication(); if (user != null) { application.showToast(""); application.setUser(user); } else { application.showToast(""); } } } }
package jayavery.geomastery.main; import java.util.stream.Collectors; import jayavery.geomastery.crafting.CompostManager; import jayavery.geomastery.crafting.CookingManager; import jayavery.geomastery.crafting.CraftingManager; import jayavery.geomastery.items.ItemEdibleDecayable; import jayavery.geomastery.items.ItemSimple; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; /** Stores and registers all Geomastery recipes and crafting/cooking managers. */ public class GeoRecipes { public static final CraftingManager INVENTORY = new CraftingManager(); public static final CraftingManager KNAPPING = new CraftingManager(); public static final CraftingManager WOODWORKING = new CraftingManager(); public static final CraftingManager TEXTILES = new CraftingManager(); public static final CraftingManager CANDLEMAKER = new CraftingManager(); public static final CraftingManager FORGE = new CraftingManager(); public static final CraftingManager MASON = new CraftingManager(); public static final CraftingManager ARMOURER = new CraftingManager(); public static final CraftingManager SAWPIT = new CraftingManager(); // To use for recipe checks public static final CookingManager CAMPFIRE_ALL = new CookingManager(3); public static final CookingManager POTFIRE_ALL = new CookingManager(3); public static final CookingManager CLAY_ALL = new CookingManager(2); public static final CookingManager STONE_ALL = new CookingManager(1); // To define minimum recipe levels, e.g. for JEI public static final CookingManager CAMPFIRE_ONLY = new CookingManager(3); public static final CookingManager POTFIRE_ONLY = new CookingManager(3); public static final CookingManager CLAY_ONLY = new CookingManager(2); public static final CookingManager STONE_ONLY = new CookingManager(1); public static final CookingManager DRYING = new CookingManager(1); public static final CompostManager COMPOST = new CompostManager(); /** All metals usable in crafting for reference in multiple recipes. */ private static final Item[] METALS = {GeoItems.INGOT_COPPER, GeoItems.INGOT_TIN, GeoItems.INGOT_STEEL}; /** All skins for reference in multiple recipes. */ private static final Item[] SKINS = {GeoItems.SKIN_BEAR, GeoItems.SKIN_COW, GeoItems.SKIN_PIG, GeoItems.SKIN_SHEEP, GeoItems.SKIN_WOLF}; /** All items that can be rot. */ private static final Item[] ROTTABLES = GeoItems.ITEMS.stream().filter((i) -> i instanceof ItemEdibleDecayable).collect(Collectors.toSet()).toArray(new Item[0]); /** Cooking managers for campfire and higher furnace levels. */ private static final CookingManager[] CAMPFIRE_PLUS = {CAMPFIRE_ONLY, CAMPFIRE_ALL, POTFIRE_ALL, CLAY_ALL, STONE_ALL}; /** Cooking managers for cookfire and higher furnace levels. */ private static final CookingManager[] POTFIRE_PLUS = {POTFIRE_ONLY, POTFIRE_ALL, CLAY_ALL, STONE_ALL}; /** Cooking managers for clay furnace and higher furnace levels. */ private static final CookingManager[] CLAY_PLUS = {CLAY_ONLY, CLAY_ALL, STONE_ALL}; /** Cooking managers for stone furnace only. */ private static final CookingManager[] STONE_PLUS = {STONE_ONLY, STONE_ALL}; public static void init() { Geomastery.LOG.info("Setting up crafting and cooking recipes"); setupInventory(); setupKnapping(); setupWoodworking(); setupTextiles(); setupCandlemaker(); setupForge(); setupMason(); setupArmourer(); setupSawpit(); setupCampfire(); setupPotfire(); setupClay(); setupStone(); setupDrying(); setupCompost(); } /** Adds all recipes to inventory. */ private static void setupInventory() { INVENTORY.addShapedRecipe(new ItemStack(GeoItems.HOE_ANTLER), "A", 'A', GeoItems.SHOVEL_ANTLER); INVENTORY.addShapedRecipe(new ItemStack(Items.FISHING_ROD), "SS ", " TT", 'S', Items.STICK, 'T', GeoItems.TWINE_HEMP); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.SPEAR_WOOD), "S", "S", 'S', Items.STICK); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.BOW_CRUDE), "S ", "ST", 'S', Items.STICK, 'T', GeoItems.TWINE_HEMP); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.ARROW_WOOD, 5), "S", "F", 'S', Items.STICK, 'F', Items.FEATHER); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.POT_CLAY), "C C", " C ", 'C', GeoItems.CLAY); INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.CRAFTING_KNAPPING), "FFF", 'F', Items.FLINT); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_CANDLEMAKER), "PPP", "PPP", 'P', GeoItems.POLE); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_TEXTILES), "BPP", "PPP",'B', Items.BONE, 'P', GeoItems.POLE); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_SAWPIT), "PSP", " S ", 'P', GeoItems.POLE, 'S', GeoItems.INGOT_STEEL); INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.FURNACE_CAMPFIRE), "S S", "SSS", 'S', Items.STICK); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.FURNACE_CLAY), "C C", "MMM", 'C', GeoItems.LOOSE_CLAY, 'M', GeoItems.MUDBRICKS); INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.DRYING), "PPP", 'P', GeoItems.POLE); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.BED_LEAF), "LLL", 'L', GeoItems.LEAVES); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.WALL_MUD, 2), "M", "M", 'M', GeoItems.MUDBRICKS); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CLAY, 6), "C", 'C', GeoItems.LOOSE_CLAY); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.LOOSE_CLAY), "CCC", "CCC", 'C', GeoItems.CLAY); INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.FURNACE_POTFIRE), "SPS", "SSS", 'S', Items.STICK, 'P', GeoItems.POT_CLAY); for (Item rottable : ROTTABLES) { INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.COMPOSTHEAP), "PRP", "PPP", 'P', GeoItems.POLE, 'R', ItemSimple.rottenStack(rottable, 1)); } for (Item skin : SKINS) { INVENTORY.addShapedRecipe(new ItemStack(GeoBlocks.BASKET), "SHS", " S ", 'S', Items.STICK, 'H', skin); } for (Item metal : METALS) { INVENTORY.addShapedRecipe(new ItemStack(GeoItems.FURNACE_STONE), "S S", "SMS", 'S', GeoItems.RUBBLE, 'M', metal); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_TEXTILES), "MPP", "PPP", 'M', metal, 'P', GeoItems.POLE); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_WOODWORKING), "PMM", "PPP", 'P', GeoItems.POLE, 'M', metal); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_MASON), "MSS", "PPP", 'M', metal, 'S', GeoItems.RUBBLE, 'P', GeoItems.POLE); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_ARMOURER), "MSP", "LBP", 'M', metal, 'S', GeoItems.RUBBLE, 'P', GeoItems.POLE, 'L', Items.LEATHER, 'B', GeoItems.BEESWAX); INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_ARMOURER), "MSP", "LBP", 'M', metal, 'S', GeoItems.RUBBLE, 'P', GeoItems.POLE, 'L', Items.LEATHER, 'B', GeoItems.TALLOW); for (Item metal2 : METALS) { INVENTORY.addShapedRecipe(new ItemStack(GeoItems.CRAFTING_FORGE), "MNS", "PPP", 'M', metal, 'N', metal2, 'S', GeoItems.RUBBLE, 'P', GeoItems.POLE); } } } /** Adds all recipes to knapping block. */ private static void setupKnapping() { KNAPPING.addShapedRecipe(new ItemStack(GeoItems.HUNTINGKNIFE_FLINT), "F", "F", 'F', Items.FLINT); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.AXE_FLINT), "F", "S", "S", 'F', GeoItems.AXEHEAD_FLINT, 'S', Items.STICK); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.PICKAXE_FLINT), "F", "S", "S", 'F', GeoItems.PICKHEAD_FLINT, 'S', Items.STICK); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.SHEARS_FLINT), "F ", "FF", 'F', Items.FLINT); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.SPEAR_FLINT), "F", "S", "S", 'F', GeoItems.SPEARHEAD_FLINT, 'S', Items.STICK); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.ARROW_FLINT, 5), "F", "S", "E", 'F', GeoItems.ARROWHEAD_FLINT, 'S', Items.STICK, 'E', Items.FEATHER); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.WALL_ROUGH, 2), "R", "R", 'R', GeoItems.RUBBLE); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.ARROWHEAD_FLINT), "F", 'F', Items.FLINT); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.AXEHEAD_FLINT), "F ", "FF", "F ", 'F', Items.FLINT); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.PICKHEAD_FLINT), " F ", "FFF", " F ", 'F', Items.FLINT); KNAPPING.addShapedRecipe(new ItemStack(GeoItems.SPEARHEAD_FLINT), " F ", " F ", "F F", 'F', Items.FLINT); } /** Adds all recipes to woodworking bench. */ private static void setupWoodworking() { WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SHOVEL_WOOD), "P", "P", "P", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.BOW_WAR), "P ", "TP", "P ", 'P', GeoItems.POLE, 'T', GeoItems.TWINE_HEMP); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HUNTINGKNIFE_COPPER), "B", "P", 'B', GeoItems.KNIFEBLADE_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.MACHETE_COPPER), "B", "P", 'B', GeoItems.MACHETEBLADE_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.PICKAXE_COPPER), "H", "P", "P", 'H', GeoItems.PICKHEAD_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SPEAR_COPPER), "H", "P", "P", 'H', GeoItems.SPEARHEAD_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.AXE_COPPER), "H", "P", "P", 'H', GeoItems.AXEHEAD_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HOE_COPPER), "H", "P", "P", 'H', GeoItems.HOEHEAD_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SICKLE_COPPER), "B", "P", 'B', GeoItems.SICKLEBLADE_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SHOVEL_COPPER), "H", "P", "P", 'H', GeoItems.SHOVELHEAD_COPPER, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.ARROW_COPPER, 5), "A", "S", "F", 'A', GeoItems.ARROWHEAD_COPPER, 'S', Items.STICK, 'F', Items.FEATHER); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HUNTINGKNIFE_BRONZE), "B", "P", 'B', GeoItems.KNIFEBLADE_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.MACHETE_BRONZE), "B", "P", 'B', GeoItems.MACHETEBLADE_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.PICKAXE_BRONZE), "H", "P", "P", 'H', GeoItems.PICKHEAD_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SPEAR_BRONZE), "H", "P", "P", 'H', GeoItems.SPEARHEAD_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.AXE_BRONZE), "H", "P", "P", 'H', GeoItems.AXEHEAD_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HOE_BRONZE), "H", "P", "P", 'H', GeoItems.HOEHEAD_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SICKLE_BRONZE), "B", "P", 'B', GeoItems.SICKLEBLADE_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SHOVEL_BRONZE), "H", "P", "P", 'H', GeoItems.SHOVELHEAD_BRONZE, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.ARROW_BRONZE, 5), "A", "S", "F", 'A', GeoItems.ARROWHEAD_BRONZE, 'S', Items.STICK, 'F', Items.FEATHER); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HUNTINGKNIFE_STEEL), "B", "P", 'B', GeoItems.KNIFEBLADE_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.MACHETE_STEEL), "B", "P", 'B', GeoItems.MACHETEBLADE_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.PICKAXE_STEEL), "H", "P", "P", 'H', GeoItems.PICKHEAD_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SPEAR_STEEL), "H", "P", "P", 'H', GeoItems.SPEARHEAD_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.AXE_STEEL), "H", "P", "P", 'H', GeoItems.AXEHEAD_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.HOE_STEEL), "H", "P", "P", 'H', GeoItems.HOEHEAD_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SICKLE_STEEL), "B", "P", 'B', GeoItems.SICKLEBLADE_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SHOVEL_STEEL), "H", "P", "P", 'H', GeoItems.SHOVELHEAD_STEEL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.ARROW_STEEL, 5), "A", "S", "F", 'A', GeoItems.ARROWHEAD_STEEL, 'S', Items.STICK, 'F', Items.FEATHER); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.SHIELD_WOOD), " P ", "PPP", " P ", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.WALL_POLE, 2), "PPP", "PPP", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.STAIRS_POLE, 2), " P", " PP", "PPP", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.STAIRS_WOOD, 2), " T", " TT", "TTT", 'T', GeoItems.TIMBER); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.DOOR_POLE), "PP", "PP", "PP", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.DOOR_WOOD), "SS", "SS", "SS", 'S', GeoItems.TIMBER); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.BOX), "PTP", "PPP", 'P', GeoItems.POLE, 'T', GeoItems.TALLOW); WOODWORKING.addShapedRecipe(new ItemStack(Blocks.LADDER, 8), "P P", "PPP", "P P", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.BED_SIMPLE), "CCC", "WWW", "PPP", 'C', GeoItems.COTTON, 'W', GeoItems.WOOL, 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.PITCHROOF_CLAY, 2), "SC ", " SC", " S", 'S', GeoItems.TIMBER, 'C', GeoItems.LOOSE_CLAY); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.FRAME, 3), "SSS", " S ", 'S', GeoItems.TIMBER); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.VAULT_FRAME, 3), "S ", " S ", " S", 'S', GeoItems.TIMBER); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.WINDOW, 4), "S S", " G ", "S S", 'S', GeoItems.TIMBER, 'G', GeoItems.GLASS); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.FLOOR_POLE, 4), "PPP", 'P', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoItems.FLOOR_WOOD, 4), "TTT", 'T', GeoItems.TIMBER); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.FLATROOF_POLE, 2), "TTT", "T T", 'T', GeoItems.POLE); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.WALL_LOG, 4), "L", "L", 'L', GeoItems.LOG); WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.FENCE, 4), "PPP", " P ", 'P', GeoItems.POLE); for (Item metal : METALS) { WOODWORKING.addShapedRecipe(new ItemStack(GeoBlocks.CHEST), "SSS", "SMS", "SSS", 'S', GeoItems.TIMBER, 'M', metal); } } /** Adds all recipes to textiles table. */ private static void setupTextiles() { TEXTILES.addShapedRecipe(new ItemStack(GeoItems.BED_COTTON), "CCC", "CCC", 'C', GeoItems.COTTON); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.BED_WOOL), "WWW", "WWW", 'W', GeoItems.WOOL); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.COTTON_CHEST), "C C", "CCC", "CCC", 'C', GeoItems.COTTON); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.COTTON_LEGS), "CCC", "C C", "C C", 'C', GeoItems.COTTON); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.COTTON_HEAD), "CCC", "C C", 'C', GeoItems.COTTON); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.COTTON_FEET), "C C", "C C", 'C', GeoItems.COTTON); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.WOOL_CHEST), "W W", "WWW", "WWW", 'W', GeoItems.WOOL); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.WOOL_LEGS), "WWW", "W W", "W W", 'W', GeoItems.WOOL); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.WOOL_HEAD), "WWW", "W W", 'W', GeoItems.WOOL); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.WOOL_FEET), "W W", "W W", 'W', GeoItems.WOOL); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.LEATHER_CHEST), "L L", "LLL", "LLL", 'L', Items.LEATHER); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.LEATHER_LEGS), "LLL", "L L", "L L", 'L', Items.LEATHER); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.LEATHER_HEAD), "LLL", "L L", 'L', Items.LEATHER); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.LEATHER_FEET), "L L", "L L", 'L', Items.LEATHER); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.BACKPACK), "L L", "LLL", 'L', Items.LEATHER); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.YOKE), "LPL", "LLL", 'L', Items.LEATHER, 'P', GeoItems.POLE); for (Item skin : new Item[] {GeoItems.SKIN_BEAR, GeoItems.SKIN_WOLF, GeoItems.SKIN_SHEEP}) { TEXTILES.addShapedRecipe(new ItemStack(GeoItems.FUR_HEAD), "SSS", "S S", 'S', skin); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.FUR_CHEST), "S S", "SSS", "SSS", 'S', skin); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.FUR_LEGS), "SSS", "S S", "S S", 'S', skin); TEXTILES.addShapedRecipe(new ItemStack(GeoItems.FUR_FEET), "S S", "S S", 'S', skin); } } /** Adds all recipes to candlemaker's bench. */ private static void setupCandlemaker() { CANDLEMAKER.addShapedRecipe(new ItemStack(GeoBlocks.CANDLE_TALLOW, 12), "T", "T", 'T', GeoItems.TALLOW); CANDLEMAKER.addShapedRecipe(new ItemStack(GeoBlocks.CANDLE_BEESWAX, 12), "B", "B", 'B', GeoItems.BEESWAX); CANDLEMAKER.addShapedRecipe(new ItemStack(GeoBlocks.TORCH_TALLOW, 4), "T", "S", 'T', GeoItems.TALLOW, 'S', Items.STICK); CANDLEMAKER.addShapedRecipe(new ItemStack(GeoBlocks.LAMP_CLAY), "H", "T", "C", 'H', GeoItems.TWINE_HEMP, 'T', GeoItems.TALLOW, 'C', GeoItems.CLAY); } /** Adds all recipes to forge. */ private static void setupForge() { FORGE.addShapedRecipe(new ItemStack(GeoItems.SHEARS_COPPER), "C ", "CC", 'C', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SHEARS_BRONZE), "T ", "CC", 'T', GeoItems.INGOT_TIN, 'C', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SHEARS_STEEL), "S ", "SS", 'S', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.KNIFEBLADE_COPPER, 2), "M", "M", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.MACHETEBLADE_COPPER), "MMM", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.PICKHEAD_COPPER), " M ", "MMM", " M ", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.ARROWHEAD_COPPER, 24), "M ", " M", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SPEARHEAD_COPPER, 1), " M ", " M ", "M M", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.AXEHEAD_COPPER), "M ", "MM", "M ", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.HOEHEAD_COPPER), " M ", "MMM", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SICKLEBLADE_COPPER), "MM ", " M", " M", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SHOVELHEAD_COPPER), "MM", "MM", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.SWORDBLADE_COPPER), "M", "M", "M", 'M', GeoItems.INGOT_COPPER); FORGE.addShapedRecipe(new ItemStack(GeoItems.KNIFEBLADE_BRONZE, 2), "T", "M", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.MACHETEBLADE_BRONZE), "TMM", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.PICKHEAD_BRONZE), " T ", "MMM", " M ", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.ARROWHEAD_BRONZE, 24), "T ", " M", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.SPEARHEAD_BRONZE, 1), " T ", " M ", "M M", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.AXEHEAD_BRONZE), "T ", "MM", "M ", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.HOEHEAD_BRONZE), " T ", "MMM", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.SICKLEBLADE_BRONZE), "TM ", " M", " M", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.SHOVELHEAD_BRONZE), "TM", "MM", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.SWORDBLADE_BRONZE), "T", "M", "M", 'M', GeoItems.INGOT_COPPER, 'T', GeoItems.INGOT_TIN); FORGE.addShapedRecipe(new ItemStack(GeoItems.KNIFEBLADE_STEEL, 2), "M", "M", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.MACHETEBLADE_STEEL), "MMM", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.PICKHEAD_STEEL), " M ", "MMM", " M ", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.ARROWHEAD_STEEL, 24), "M ", " M", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.SPEARHEAD_STEEL, 1), " M ", " M ", "M M", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.AXEHEAD_STEEL), "M ", "MM", "M ", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.HOEHEAD_STEEL), " M ", "MMM", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.SICKLEBLADE_STEEL), "MM ", " M", " M", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.SHOVELHEAD_STEEL), "MM", "MM", 'M', GeoItems.INGOT_STEEL); FORGE.addShapedRecipe(new ItemStack(GeoItems.SWORDBLADE_STEEL), "M", "M", "M", 'M', GeoItems.INGOT_STEEL); } /** Adds all recipes to mason. */ private static void setupMason() { MASON.addShapedRecipe(new ItemStack(GeoItems.WALL_BRICK, 2), "B", "B", 'B', Items.BRICK); MASON.addShapedRecipe(new ItemStack(GeoItems.WALL_STONE, 2), "S", "S", 'S', GeoItems.DRESSEDSTONE); MASON.addShapedRecipe(new ItemStack(GeoBlocks.STAIRS_STONE, 2), " S", "SS", 'S', GeoItems.DRESSEDSTONE); MASON.addShapedRecipe(new ItemStack(GeoBlocks.STAIRS_BRICK, 2), " B", "BB", 'B', Items.BRICK); MASON.addShapedRecipe(new ItemStack(GeoItems.VAULT_STONE, 2), "SS", "S ", 'S', GeoItems.DRESSEDSTONE); MASON.addShapedRecipe(new ItemStack(GeoItems.VAULT_BRICK, 2), "BB", "B ", 'B', Items.BRICK); MASON.addShapedRecipe(new ItemStack(GeoItems.SLAB_STONE, 2), "SSS", 'S', GeoItems.DRESSEDSTONE); MASON.addShapedRecipe(new ItemStack(GeoItems.SLAB_BRICK, 2), "BBB", 'B', Items.BRICK); MASON.addShapedRecipe(new ItemStack(GeoItems.DRESSEDSTONE, 2), "RR", "RR", 'R', GeoItems.RUBBLE); } /** Adds all recipes to armourer. */ private static void setupArmourer() { ARMOURER.addShapedRecipe(new ItemStack(GeoItems.SWORD_COPPER), "B", "L", "P", 'B', GeoItems.SWORDBLADE_COPPER, 'L', Items.LEATHER, 'P', GeoItems.POLE); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.SWORD_BRONZE), "B", "L", "P", 'B', GeoItems.SWORDBLADE_BRONZE, 'L', Items.LEATHER, 'P', GeoItems.POLE); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.SWORD_STEEL), "B", "L", "P", 'B', GeoItems.SWORDBLADE_STEEL, 'L', Items.LEATHER, 'P', GeoItems.POLE); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.SHIELD_STEEL), "SP ", "PPP", " PS", 'S', GeoItems.INGOT_STEEL, 'P', GeoItems.POLE); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELMAIL_CHEST), "S S", "SSS", "SSS", 'S', GeoItems.INGOT_STEEL); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELMAIL_LEGS), "SSS", "S S", "S S", 'S', GeoItems.INGOT_STEEL); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELMAIL_FEET), "S S", "S S", 'S', GeoItems.INGOT_STEEL); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELMAIL_HEAD), "SSS", "S S", 'S', GeoItems.INGOT_STEEL); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELPLATE_CHEST), "SLS", "SSS", "SSS", 'S', GeoItems.INGOT_STEEL, 'L', Items.LEATHER); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELPLATE_LEGS), "SSS", "SLS", "S S", 'S', GeoItems.INGOT_STEEL, 'L', Items.LEATHER); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELPLATE_FEET), "S S", "SLS", 'S', GeoItems.INGOT_STEEL, 'L', Items.LEATHER); ARMOURER.addShapedRecipe(new ItemStack(GeoItems.STEELPLATE_HEAD), "SSS", "SLS", 'S', GeoItems.INGOT_STEEL, 'L', Items.LEATHER); } /** Adds all recipes to sawpit. */ private static void setupSawpit() { SAWPIT.addShapedRecipe(new ItemStack(GeoItems.TIMBER, 3), "T", 'T', GeoItems.THICKLOG); SAWPIT.addShapedRecipe(new ItemStack(GeoItems.TIMBER, 3), "LLL", 'L', GeoItems.LOG); SAWPIT.addShapedRecipe(new ItemStack(GeoItems.BEAM_SHORT), "LL", 'L', GeoItems.LOG); SAWPIT.addShapedRecipe(new ItemStack(GeoItems.BEAM_LONG), "TTT", 'T', GeoItems.THICKLOG); } /** Adds all recipes to campfire and higher levels. */ private static void setupCampfire() { for (CookingManager recipes : CAMPFIRE_PLUS) { recipes.addCookingRecipe(new ItemStack(GeoItems.BEEF_RAW), new ItemStack(GeoItems.BEEF_COOKED), 120); recipes.addCookingRecipe(new ItemStack(GeoItems.PORK_RAW), new ItemStack(GeoItems.PORK_COOKED), 100); recipes.addCookingRecipe(new ItemStack(GeoItems.MUTTON_RAW), new ItemStack(GeoItems.MUTTON_COOKED), 80); recipes.addCookingRecipe(new ItemStack(GeoItems.RABBIT_RAW), new ItemStack(GeoItems.RABBIT_COOKED), 40); recipes.addCookingRecipe(new ItemStack(GeoItems.CHICKEN_RAW), new ItemStack(GeoItems.CHICKEN_COOKED), 60); recipes.addCookingRecipe(new ItemStack(GeoItems.FISH_RAW), new ItemStack(GeoItems.FISH_COOKED), 40); recipes.addCookingRecipe(new ItemStack(GeoItems.POTATO), new ItemStack(GeoItems.POTATO_COOKED), 120); recipes.addFuel(new ItemStack(Items.STICK), 200); recipes.addFuel(new ItemStack(GeoItems.POLE), 500); recipes.addFuel(new ItemStack(GeoItems.LOG), 1000); recipes.addFuel(new ItemStack(GeoItems.THICKLOG), 2000); } } /** Adds all recipes to cookfire and higher levels. */ private static void setupPotfire() { for (CookingManager recipes : POTFIRE_PLUS) { recipes.addCookingRecipe(new ItemStack(Items.REEDS), new ItemStack(GeoItems.SUGAR), 60); recipes.addCookingRecipe(new ItemStack(GeoItems.CHICKPEAS), new ItemStack(GeoItems.CHICKPEAS_BOILED), 60); recipes.addCookingRecipe(new ItemStack(GeoItems.RICE), new ItemStack(GeoItems.RICE_BOILED), 60); } POTFIRE_ALL.addCookingRecipe(new ItemStack(GeoItems.WHEAT), new ItemStack(GeoItems.WHEAT_BOILED), 60); } /** Adds all recipes to clay furnace and higher levels. */ private static void setupClay() { for (CookingManager recipes : CLAY_PLUS) { recipes.addCookingRecipe(new ItemStack(GeoItems.WHEAT), new ItemStack(GeoItems.BREAD), 60); recipes.addCookingRecipe(new ItemStack(GeoItems.ORE_COPPER), new ItemStack(GeoItems.INGOT_COPPER), 300); recipes.addCookingRecipe(new ItemStack(GeoItems.ORE_TIN), new ItemStack(GeoItems.INGOT_TIN), 300); recipes.addCookingRecipe(new ItemStack(GeoItems.POLE), new ItemStack(Items.COAL, 1, 1),60); recipes.addCookingRecipe(new ItemStack(GeoItems.LOG), new ItemStack(Items.COAL, 3, 1), 180); recipes.addCookingRecipe(new ItemStack(GeoItems.THICKLOG), new ItemStack(Items.COAL, 6, 1), 360); recipes.addCookingRecipe(new ItemStack(GeoItems.LOOSE_CLAY), new ItemStack(Items.BRICK), 200); recipes.addFuel(new ItemStack(GeoItems.PEAT_DRY), 2400); recipes.addFuel(new ItemStack(Items.COAL, 1, 1), 3000); } } /** Adds all recipes to stone furnace and higher levels. */ private static void setupStone() { for (CookingManager recipes : STONE_PLUS) { recipes.addCookingRecipe(new ItemStack(GeoItems.ORE_IRON), new ItemStack(GeoItems.INGOT_STEEL), 400); recipes.addCookingRecipe(new ItemStack(GeoItems.ORE_SILVER), new ItemStack(GeoItems.INGOT_SILVER), 300); recipes.addCookingRecipe(new ItemStack(GeoItems.ORE_GOLD), new ItemStack(Items.GOLD_INGOT), 200); recipes.addCookingRecipe(new ItemStack(GeoItems.LOOSE_SAND), new ItemStack(GeoItems.GLASS), 200); recipes.addFuel(new ItemStack(Items.COAL, 1, 0), 4000); } } /** Adds all recipes to drying rack. */ private static void setupDrying() { DRYING.addCookingRecipe(new ItemStack(GeoItems.LOOSE_DIRT), new ItemStack(GeoItems.MUDBRICKS), 4000); DRYING.addCookingRecipe(new ItemStack(GeoItems.PEAT_WET), new ItemStack(GeoItems.PEAT_DRY), 4000); for (Item skin : SKINS) { DRYING.addCookingRecipe(new ItemStack(skin), new ItemStack(Items.LEATHER), 4000); } } /** Adds all recipes to compost heap. */ private static void setupCompost() { COMPOST.addWet(GeoItems.ITEMS.stream().filter((i) -> i instanceof ItemEdibleDecayable).map(ItemStack::new).collect(Collectors.toSet()).toArray(new ItemStack[0])); COMPOST.addWet(new ItemStack(GeoItems.WOOL), new ItemStack(Items.BONE)); COMPOST.addDry(new ItemStack(GeoItems.LEAVES), new ItemStack(Items.STICK), new ItemStack(GeoItems.LOG), new ItemStack(GeoItems.POLE), new ItemStack(GeoItems.THICKLOG), new ItemStack(Items.REEDS)); } }
package org.jaxen.expr; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jaxen.Context; import org.jaxen.ContextSupport; import org.jaxen.JaxenException; import org.jaxen.UnresolvableException; import org.jaxen.Navigator; import org.jaxen.expr.iter.IterableAxis; import org.jaxen.saxpath.Axis; import org.jaxen.util.IdentityHashMap; /** * Expression object that represents any flavor * of name-test steps within an XPath. * <p> * This includes simple steps, such as "foo", * non-default-axis steps, such as "following-sibling::foo" * or "@foo", and namespace-aware steps, such * as "foo:bar". * * @author bob mcwhirter (bob@werken.com) * @author Stephen Colebourne */ public class DefaultNameStep extends DefaultStep implements NameStep { /** Dummy object used to convert HashMap to HashSet */ private final static Object PRESENT = new Object(); /** * Our prefix, bound through the current Context. * The empty-string ("") if no prefix was specified. * Decidedly NOT-NULL, due to SAXPath constraints. * This is the 'foo' in 'foo:bar'. */ private String prefix; /** * Our local-name. * This is the 'bar' in 'foo:bar'. */ private String localName; /** Quick flag denoting if the local name was '*' */ private boolean matchesAnyName; /** Quick flag denoting if we have a namespace prefix **/ private boolean hasPrefix; /** * Constructor. * * @param axis the axis to work through * @param prefix the name prefix * @param localName the local name * @param predicateSet the set of predicates */ public DefaultNameStep(IterableAxis axis, String prefix, String localName, PredicateSet predicateSet) { super(axis, predicateSet); this.prefix = prefix; this.localName = localName; this.matchesAnyName = "*".equals(localName); this.hasPrefix = (this.prefix != null && this.prefix.length() > 0); } /** * Gets the namespace prefix. * * @return the prefix */ public String getPrefix() { return this.prefix; } /** * Gets the local name. * * @return the local name */ public String getLocalName() { return this.localName; } /** * Does this step match any name (xpath of '*'). * * @return true if it matches any name */ public boolean isMatchesAnyName() { return matchesAnyName; } /** * Gets the step as a fully defined xpath. * * @return the full xpath for this step */ public String getText() { StringBuffer buf = new StringBuffer(64); buf.append(getAxisName()).append("::"); if (getPrefix() != null && getPrefix().length() > 0) { buf.append(getPrefix()).append(':'); } return buf.append(getLocalName()).append(super.getText()).toString(); } /** * Evaluate the context node set to find the new node set. * <p> * This method overrides the version in DefaultStep for performance. */ public List evaluate(Context context) throws JaxenException { List contextNodeSet = context.getNodeSet(); int contextSize = contextNodeSet.size(); // optimize for context size 0 if (contextSize == 0) { return Collections.EMPTY_LIST; } ContextSupport support = context.getContextSupport(); boolean namedAccess = (!matchesAnyName && getIterableAxis().supportsNamedAccess(support)); // optimize for context size 1 (common case, avoids lots of object creation) if (contextSize == 1) { Object contextNode = contextNodeSet.get(0); if (namedAccess) { // get the iterator over the nodes and check it String uri = support.translateNamespacePrefixToUri(prefix); Iterator axisNodeIter = getIterableAxis().namedAccessIterator( contextNode, support, localName, prefix, uri); if (axisNodeIter == null || axisNodeIter.hasNext() == false) { return Collections.EMPTY_LIST; } // convert iterator to list for predicate test // no need to filter as named access guarantees this List newNodeSet = new ArrayList(); while (axisNodeIter.hasNext()) { newNodeSet.add(axisNodeIter.next()); } // evaluate the predicates return getPredicateSet().evaluatePredicates(newNodeSet, support); } else { // get the iterator over the nodes and check it Iterator axisNodeIter = axisIterator(contextNode, support); if (axisNodeIter == null || axisNodeIter.hasNext() == false) { return Collections.EMPTY_LIST; } // run through iterator, filtering using matches() // adding to list for predicate test List newNodeSet = new ArrayList(); while (axisNodeIter.hasNext()) { Object eachAxisNode = axisNodeIter.next(); if (matches(eachAxisNode, support)) { newNodeSet.add(eachAxisNode); } } // evaluate the predicates return getPredicateSet().evaluatePredicates(newNodeSet, support); } } // full case Map unique = new IdentityHashMap(); List interimSet = new ArrayList(contextSize); List newNodeSet = new ArrayList(contextSize); if (namedAccess) { String uri = support.translateNamespacePrefixToUri(prefix); for (int i = 0; i < contextSize; ++i) { Object eachContextNode = contextNodeSet.get(i); Iterator axisNodeIter = getIterableAxis().namedAccessIterator( eachContextNode, support, localName, prefix, uri); if (axisNodeIter == null || axisNodeIter.hasNext() == false) { continue; } // ensure only one of each node in the result while (axisNodeIter.hasNext()) { Object eachAxisNode = axisNodeIter.next(); if (unique.put(eachAxisNode, PRESENT) == null) { interimSet.add(eachAxisNode); } } // evaluate the predicates newNodeSet.addAll(getPredicateSet().evaluatePredicates(interimSet, support)); interimSet.clear(); } } else { for (int i = 0; i < contextSize; ++i) { Object eachContextNode = contextNodeSet.get(i); Iterator axisNodeIter = axisIterator(eachContextNode, support); if (axisNodeIter == null || axisNodeIter.hasNext() == false) { continue; } // ensure only unique matching nodes in the result while (axisNodeIter.hasNext()) { Object eachAxisNode = axisNodeIter.next(); if (matches(eachAxisNode, support)) { if (unique.put(eachAxisNode, PRESENT) == null) { interimSet.add(eachAxisNode); } } } // evaluate the predicates newNodeSet.addAll(getPredicateSet().evaluatePredicates(interimSet, support)); interimSet.clear(); } } return newNodeSet; } /** * Checks whether the node matches this step. * * @param node the node to check * @param contextSupport the context support * @return true if matches */ public boolean matches(Object node, ContextSupport contextSupport) throws JaxenException { Navigator nav = contextSupport.getNavigator(); String myUri = null; String nodeName = null; String nodeUri = null; if (nav.isElement(node)) { nodeName = nav.getElementName(node); nodeUri = nav.getElementNamespaceUri(node); } else if (nav.isText(node)) { return false; } else if (nav.isAttribute(node)) { if (getAxis() != Axis.ATTRIBUTE) { return false; } nodeName = nav.getAttributeName(node); nodeUri = nav.getAttributeNamespaceUri(node); } else if (nav.isDocument(node)) { return false; } else if (nav.isNamespace(node)) { if (matchesAnyName && getAxis() != Axis.NAMESPACE) { // Only works for namespace::* return false; } nodeName = nav.getNamespacePrefix(node); } else { return false; } if (hasPrefix) { myUri = contextSupport.translateNamespacePrefixToUri(this.prefix); if (myUri == null) { throw new UnresolvableException("Cannot resolve namespace prefix '"+this.prefix+"'"); } } else if (matchesAnyName) { return true; } // If we map to a non-empty namespace and the node does not // or vice-versa, fail-fast. if (hasNamespace(myUri) != hasNamespace(nodeUri)) { return false; } // To fail-fast, we check the equality of // local-names first. Shorter strings compare // quicker. if (matchesAnyName || nodeName.equals(getLocalName())) { return matchesNamespaceURIs(myUri, nodeUri); } return false; } /** * Checks whether the URI represents a namespace. * * @param uri the URI to check * @return true if non-null and non-empty */ private boolean hasNamespace(String uri) { return (uri != null && uri.length() > 0); } /** * Compares two namespace URIs, handling null. * * @param uri1 the first URI * @param uri2 the second URI * @return true if equal, where null=="" */ protected boolean matchesNamespaceURIs(String uri1, String uri2) { if (uri1 == uri2) { return true; } if (uri1 == null) { return (uri2.length() == 0); } if (uri2 == null) { return (uri1.length() == 0); } return uri1.equals(uri2); } /** * Visitor pattern for the step. * * @param visitor the visitor object */ public void accept(Visitor visitor) { visitor.visit(this); } /** * Returns a full information debugging string. * * @return a debugging string */ public String toString() { return "[(DefaultNameStep): " + getPrefix() + ":" + getLocalName() + "[" + super.toString() + "]]"; } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.dictionary; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import opennlp.tools.dictionary.serializer.Attributes; import opennlp.tools.dictionary.serializer.DictionarySerializer; import opennlp.tools.dictionary.serializer.Entry; import opennlp.tools.dictionary.serializer.EntryInserter; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.StringList; /** * This class is a dictionary. */ public class Dictionary implements Iterable<StringList> { private static class StringListWrapper { private final StringList stringList; private final boolean isCaseSensitive; private StringListWrapper(StringList stringList, boolean isCaseSensitive) { this.stringList = stringList; this.isCaseSensitive = isCaseSensitive; } private StringList getStringList() { return stringList; } public boolean equals(Object obj) { boolean result; if (obj == this) { result = true; } else if (obj instanceof StringListWrapper) { StringListWrapper other = (StringListWrapper) obj; if (isCaseSensitive) { result = this.stringList.equals(other.getStringList()); } else { result = this.stringList.compareToIgnoreCase(other.getStringList()); } } else { result = false; } return result; } public int hashCode() { // if lookup is too slow optimize this return this.stringList.toString().toLowerCase().hashCode(); } public String toString() { return this.stringList.toString(); } } private Set<StringListWrapper> entrySet = new HashSet<StringListWrapper>(); private boolean caseSensitive; /** * Initializes an empty {@link Dictionary}. */ public Dictionary() { this(false); } public Dictionary(boolean caseSensitive) { this.caseSensitive = caseSensitive; } /** * Initializes the {@link Dictionary} from an existing dictionary resource. * * @param in * @throws IOException * @throws InvalidFormatException */ public Dictionary(InputStream in) throws IOException, InvalidFormatException { this(in,false); } public Dictionary(InputStream in, boolean caseSensitive) throws IOException, InvalidFormatException { this.caseSensitive = caseSensitive; DictionarySerializer.create(in, new EntryInserter() { public void insert(Entry entry) { put(entry.getTokens()); } }); } /** * Adds the tokens to the dictionary as one new entry. * * @param tokens the new entry */ public void put(StringList tokens) { entrySet.add(new StringListWrapper(tokens, caseSensitive)); } /** * Checks if this dictionary has the given entry. * * @param tokens * * @return true if it contains the entry otherwise false */ public boolean contains(StringList tokens) { return entrySet.contains(new StringListWrapper(tokens, caseSensitive)); } /** * Removes the given tokens form the current instance. * * @param tokens */ public void remove(StringList tokens) { entrySet.remove(new StringListWrapper(tokens, caseSensitive)); } /** * Retrieves an Iterator over all tokens. * * @return token-{@link Iterator} */ public Iterator<StringList> iterator() { final Iterator<StringListWrapper> entries = entrySet.iterator(); return new Iterator<StringList>() { public boolean hasNext() { return entries.hasNext(); } public StringList next() { return entries.next().getStringList(); } public void remove() { entries.remove(); }}; } /** * Retrieves the number of tokens in the current instance. * * @return number of tokens */ public int size() { return entrySet.size(); } /** * Writes the current instance to the given {@link OutputStream}. * * @param out * @throws IOException */ public void serialize(OutputStream out) throws IOException { Iterator<Entry> entryIterator = new Iterator<Entry>() { private Iterator<StringList> dictionaryIterator = Dictionary.this.iterator(); public boolean hasNext() { return dictionaryIterator.hasNext(); } public Entry next() { StringList tokens = (StringList) dictionaryIterator.next(); return new Entry(tokens, new Attributes()); } public void remove() { throw new UnsupportedOperationException(); } }; DictionarySerializer.serialize(out, entryIterator); } public boolean equals(Object obj) { boolean result; if (obj == this) { result = true; } else if (obj != null && obj instanceof Dictionary) { Dictionary dictionary = (Dictionary) obj; result = entrySet.equals(dictionary.entrySet); } else { result = false; } return result; } public int hashCode() { return entrySet.hashCode(); } public String toString() { return entrySet.toString(); } /** * Reads a dictionary which has one entry per line. The tokens inside an * entry are whitespace delimited. * * @param in * * @return the parsed dictionary * * @throws IOException */ public static Dictionary parseOneEntryPerLine(Reader in) throws IOException { BufferedReader lineReader = new BufferedReader(in); Dictionary dictionary = new Dictionary(); String line; while ((line = lineReader.readLine()) != null) { StringTokenizer whiteSpaceTokenizer = new StringTokenizer(line, " "); String tokens[] = new String[whiteSpaceTokenizer.countTokens()]; if (tokens.length > 0) { int tokenIndex = 0; while (whiteSpaceTokenizer.hasMoreTokens()) { tokens[tokenIndex++] = whiteSpaceTokenizer.nextToken(); } dictionary.put(new StringList(tokens)); } } return dictionary; } }
package org.apache.commons.lang; import java.util.Iterator; import java.util.StringTokenizer; import org.apache.commons.lang.math.NumberUtils; public class StringUtils { /** * <p>The maximum size to which the padding constant(s) can expand.</p> */ private static int PAD_LIMIT = 8192; /** * <p>A <code>String</code> containing all blank characters.</p> * * <p>Used for efficient blank padding. The length of the string expands as needed.</p> */ private static String blanks = new String(" "); /** * <p>An array of <code>String</code>s used for padding.</p> * * <p>Used for efficient blank padding. The length of each string expands as needed.</p> */ private final static String[] padding = new String[Character.MAX_VALUE]; // String.concat about twice as fast as StringBuffer.append /** * <p><code>StringUtils<code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>StringUtils.trim(" foo ");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public StringUtils() { } // Empty /** * <p>Removes control characters, including whitespace, from both * ends of this String, handling <code>null</code> by returning * an empty String.</p> * * <pre> * StringUtils.clean("abc") = "abc" * StringUtils.clean(" abc ") = "abc" * StringUtils.clean(" ") = "" * StringUtils.clean("") = "" * StringUtils.clean(null) = "" * </pre> * * @see java.lang.String#trim() * @param str the String to clean, may be null * @return the trimmed text, never <code>null</code> * @deprecated Use the clearer named {@link #trimToEmpty(String)}. * Method will be removed in Commons Lang 3.0. */ public static String clean(String str) { return (str == null ? "" : str.trim()); } /** * <p>Removes control characters, including whitespace, from both * ends of this String, handling <code>null</code> by returning * <code>null</code>.</p> * * <p>The string is trimmed using {@link String#trim()}.</p> * * <pre> * StringUtils.trim("abc") = "abc" * StringUtils.trim(" abc ") = "abc" * StringUtils.trim(" ") = "" * StringUtils.trim("") = "" * StringUtils.trim(null) = null * </pre> * * @see java.lang.String#trim() * @param str the String to be trimmed, may be null * @return the trimmed text, * <code>null</code> if a null string input */ public static String trim(String str) { return (str == null ? null : str.trim()); } /** * <p>Removes control characters, including whitespace, from both * ends of this string returning <code>null</code> if the string is * empty after the trim or if it is <code>null</code>. * * <p>The string is trimmed using {@link String#trim()}.</p> * * <pre> * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" * StringUtils.trimToNull(" ") = null * StringUtils.trimToNull("") = null * StringUtils.trimToNull(null) = null * </pre> * * @see java.lang.String#trim() * @param str the String to be trimmed, may be null * @return the trimmed string, * <code>null</code> if a whitespace, empty or null string input */ public static String trimToNull(String str) { String ts = trim(str); return (ts == null || ts.length() == 0 ? null : ts); } /** * <p>Removes control characters, including whitespace, from both * ends of this string returning an empty string ("") if the string * is empty after the trim or if it is <code>null</code>. * * <p>The string is trimmed using {@link String#trim()}.</p> * * <pre> * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" * StringUtils.trimToEmpty(" ") = "" * StringUtils.trimToEmpty("") = "" * StringUtils.trimToEmpty(null) = "" * </pre> * * @see java.lang.String#trim() * @param str the String to be trimmed, may be null * @return the trimmed string, or an empty string if null input */ public static String trimToEmpty(String str) { return (str == null ? "" : str.trim()); } /** * <p>Deletes all 'space' characters from a String.</p> * * <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code> * in line with the deprecated {@link Character#isSpace(char)}.</p> * * @param str the String to delete spaces from, may be null * @return the String without spaces, <code>null</code> if null string input */ public static String deleteSpaces(String str) { if (str == null) { return null; } return CharSetUtils.delete(str, " \t\r\n\b"); } /** * <p>Deletes all whitespaces from a String.</p> * * <p>Whitespace is defined by * {@link Character#isWhitespace(char)}.</p> * * @param str the String to delete whitespace from, may be null * @return the String without whitespaces, <code>null</code> if null string input */ public static String deleteWhitespace(String str) { if (str == null) { return null; } StringBuffer buffer = new StringBuffer(); int sz = str.length(); for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { buffer.append(str.charAt(i)); } } return buffer.toString(); } // Empty checks /** * <p>Checks if a String is <code>null</code> or empty ("").</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in version 2.0. * It no longer trims the String. * That functionality is available in isEmptyTrimmed().</p> * * @param str the String to check, may be null * @return <code>true</code> if the String is <code>null</code> or empty */ public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } /** * <p>Checks if a String is not <code>null</code> and not empty ("").</p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is not <code>null</code> and not empty */ public static boolean isNotEmpty(String str) { return (str != null && str.length() > 0); } /** * <p>Checks if a trimmed String is <code>null</code> or empty ("").</p> * * <pre> * StringUtils.isNotEmpty(null) = true * StringUtils.isNotEmpty("") = true * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = false * StringUtils.isNotEmpty(" bob ") = false * </pre> * * @see java.lang.String#trim() * @param str the String to check, may be null * @return <code>true</code> if the String is <code>null</code> * or empty after trim() */ public static boolean isEmptyTrimmed(String str) { return (str == null || str.trim().length() == 0); } /** * <p>Checks if a trimmed String is not <code>null</code> and not empty ("").</p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = false * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @see java.lang.String#trim() * @param str the String to check, may be null * @return <code>true</code> if the String is not <code>null</code> * and not empty after trim() */ public static boolean isNotEmptyTrimmed(String str) { return (str != null && str.trim().length() > 0); } // Equals and IndexOf /** * <p>Compares two Strings, returning <code>true</code> if they are equal.</p> * * <p><code>null</code>s are handled without exceptions. Two <code>null</code> * references are considered to be equal. The comparison is case sensitive.</p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, "abc") = false * StringUtils.equals("abc", null) = false * StringUtils.equals("abc", "abc") = true * StringUtils.equals("abc", "ABC") = false * </pre> * * @see java.lang.String#equals(Object) * @param str1 the first string, may be null * @param str2 the second string, may be null * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static boolean equals(String str1, String str2) { return (str1 == null ? str2 == null : str1.equals(str2)); } /** * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring * the case.</p> * * <p><code>Nulls</code> are handled without exceptions. Two <code>null</code> * references are considered equal. Comparison is case insensitive.</p> * * <pre> * StringUtils.equalsIgnoreCase(null, null) = true * StringUtils.equalsIgnoreCase(null, "abc") = false * StringUtils.equalsIgnoreCase("abc", null) = false * StringUtils.equalsIgnoreCase("abc", "abc") = true * StringUtils.equalsIgnoreCase("abc", "ABC") = true * </pre> * * @see java.lang.String#equalsIgnoreCase(String) * @param str1 the first string, may be null * @param str2 the second string, may be null * @return <code>true</code> if the Strings are equal, case insensitive, or * both <code>null</code> */ public static boolean equalsIgnoreCase(String str1, String str2) { return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2)); } /** * <p>Find the first index of any of a set of potential substrings.</p> * * <p><code>null</code> String will return <code>-1</code>.</p> * * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the first index of any of the searchStrs in str, -1 if no match * @throws NullPointerException if any of searchStrs[i] is <code>null</code> */ public static int indexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { tmp = str.indexOf(searchStrs[i]); if (tmp == -1) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? -1 : ret; } /** * <p>Find the latest index of any of a set of potential substrings.</p> * * <p><code>null</code> string will return <code>-1</code>.</p> * * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the last index of any of the Strings, -1 if no match * @throws NullPointerException if any of searchStrs[i] is <code>null</code> */ public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { tmp = str.lastIndexOf(searchStrs[i]); if (tmp > ret) { ret = tmp; } } return ret; } // Substring /** * <p>Gets a substring from the specified string avoiding exceptions.</p> * * <p>A negative start position can be used to start <code>n</code> * characters from the end of the String.</p> * * <pre> * StringUtils.substring(null, 0) = null * StringUtils.substring("abc", 0) = "abc" * StringUtils.substring("abc", 2) = "c" * StringUtils.substring("abc", 4) = "" * StringUtils.substring("abc", -2) = "bc" * StringUtils.substring("abc", -4) = "abc" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @return substring from start position, <code>null</code> if null string input */ public static String substring(String str, int start) { if (str == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return ""; } return str.substring(start); } /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start/end <code>n</code> * characters from the end of the String.</p> * * <pre> * StringUtils.substring(null, 0, 2) = null * StringUtils.substring("abc", 0, 2) = "ab" * StringUtils.substring("abc", 2, 0) = "" * StringUtils.substring("abc", 2, 4) = "c" * StringUtils.substring("abc", 4, 6) = "" * StringUtils.substring("abc", -2, -1) = "b" * StringUtils.substring("abc", -4, 2) = "ab" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the string by this many characters * @param end the position to end at (exclusive), negative means * count back from the end of the String by this many characters * @return substring from start position to end positon, <code>null</code> if null string input */ public static String substring(String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { // check this works. end = str.length(); } // if start is greater than end, return "" if (start > end) { return ""; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } public static String left(String str, int len) { if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if ((str == null) || (str.length() <= len)) { return str; } else { return str.substring(0, len); } } public static String right(String str, int len) { if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if ((str == null) || (str.length() <= len)) { return str; } else { return str.substring(str.length() - len); } } public static String mid(String str, int pos, int len) { if ((pos < 0) || (str != null && pos > str.length())) { throw new StringIndexOutOfBoundsException("String index " + pos + " is out of bounds"); } if (len < 0) { throw new IllegalArgumentException("Requested String length " + len + " is less than zero"); } if (str == null) { return null; } if (str.length() <= (pos + len)) { return str.substring(pos); } else { return str.substring(pos, pos + len); } } // Splitting /** * <p>Splits the provided text into an array, using whitespace as the * separator.</p> * * <p>The separator is not included in the returned String array.</p> * * <pre> * StringUtils.split(null) = [] * StringUtils.split("abc def") = [abc, def] * </pre> * * @param str the String to parse, may be null * @return an array of parsed Strings, empty array if null input */ public static String[] split(String str) { return split(str, null, -1); } /** * <p>Splits the provided text into an array, using the specified separators.</p> * * <p>The separator is not included in the returned String array.</p> * * <pre> * StringUtils.split(null, null) = [] * StringUtils.split("abc def", null) = [abc, def] * StringUtils.split("abc def", " ") = [abc, def] * StringUtils.split("ab:cd:ef", ":") = [ab, cd, ef] * </pre> * * @param str the String to parse, may be null * @param separators the characters used as the delimiters, * <code>null</code> splits on whitespace * @return an array of parsed Strings, empty array if null input */ public static String[] split(String str, String separators) { return split(str, separators, -1); } /** * <p>Splits the provided text into a array, based on a given separator.</p> * * <p>The separator is not included in the returned String array. The * maximum number of splits to perfom can be controlled. A <code>null</code> * separator will cause parsing to be on whitespace.</p> * * <p>This is useful for quickly splitting a String directly into * an array of tokens, instead of an enumeration of tokens (as * <code>StringTokenizer</code> does).</p> * * <pre> * StringUtils.split(null, null, 0) = [] * StringUtils.split("ab de fg", null, 0) = [ab, cd, ef] * StringUtils.split("ab:cd:ef", ":", 0) = [ab, cd, ef] * StringUtils.split("ab:cd:ef", ":", 2) = [ab, cdef] * </pre> * * @param str the string to parse, may be null * @param separators the characters used as the delimiters, * <code>null</code> splits on whitespace * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit. * @return an array of parsed Strings, empty array if null input */ public static String[] split(String str, String separator, int max) { if (str == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } StringTokenizer tok = null; if (separator == null) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. tok = new StringTokenizer(str); } else { tok = new StringTokenizer(str, separator); } int listSize = tok.countTokens(); if (max > 0 && listSize > max) { listSize = max; } String[] list = new String[listSize]; int i = 0; int lastTokenBegin = 0; int lastTokenEnd = 0; while (tok.hasMoreTokens()) { if (max > 0 && i == listSize - 1) { // In the situation where we hit the max yet have // tokens left over in our input, the last list // element gets all remaining text. String endToken = tok.nextToken(); lastTokenBegin = str.indexOf(endToken, lastTokenEnd); list[i] = str.substring(lastTokenBegin); break; } else { list[i] = tok.nextToken(); lastTokenBegin = str.indexOf(list[i], lastTokenEnd); lastTokenEnd = lastTokenBegin + list[i].length(); } i++; } return list; } // Joining /** * <p>Concatenates elements of an array into a single String.</p> * * <p>The difference from join is that concatenate has no delimiter.</p> * * @param array the array of values to concatenate. * @return the concatenated string. */ public static String concatenate(Object[] array) { return join(array, null); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. A * <code>null</code> separator is the same as a blank String.</p> * * @param array the array of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Object[] array, String separator) { int arraySize = array.length; // ArraySize == 0: Len = 0 // ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator)) // (Assuming that all strings are roughly equally long) int bufSize = ((arraySize == 0) ? 0 : arraySize * (array[0].toString().length() + ((separator != null) ? separator.length(): 0))); StringBuffer buf = new StringBuffer(bufSize); for (int i = 0; i < arraySize; i++) { if ((separator != null) && (i > 0)) { buf.append(separator); } buf.append(array[i]); } return buf.toString(); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. * * @param array the array of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Object[] array, char separator) { int arraySize = array.length; int bufSize = (arraySize == 0 ? 0 : (array[0].toString().length() + 1) * arraySize); StringBuffer buf = new StringBuffer(bufSize); for (int i = 0; i < arraySize; i++) { if (i > 0) { buf.append(separator); } buf.append(array[i]); } return buf.toString(); } /** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. A * <code>null</code> separator is the same as a blank String.</p> * * @param iterator the <code>Iterator</code> of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Iterator iterator, String separator) { StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small while (iterator.hasNext()) { buf.append(iterator.next()); if ((separator != null) && iterator.hasNext()) { buf.append(separator); } } return buf.toString(); } /** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. * * @param iterator the <code>Iterator</code> of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Iterator iterator, char separator) { StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small while (iterator.hasNext()) { buf.append(iterator.next()); if (iterator.hasNext()) { buf.append(separator); } } return buf.toString(); } // Replacing /** * <p>Replace a String with another String inside a larger String, once.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @return the text with any replacements processed */ public static String replaceOnce(String text, String repl, String with) { return replace(text, repl, with, 1); } /** * <p>Replace all occurances of a String within another String.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @return the text with any replacements processed */ public static String replace(String text, String repl, String with) { return replace(text, repl, with, -1); } /** * <p>Replace a String with another String inside a larger String, * for the first <code>max</code> values of the search String.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * @param text text to search and replace in * @param repl String to search for * @param with String to replace with * @param max maximum number of values to replace, or <code>-1</code> if no maximum * @return the text with any replacements processed */ public static String replace(String text, String repl, String with, int max) { if (text == null || repl == null || with == null || repl.length() == 0) { return text; } StringBuffer buf = new StringBuffer(text.length()); int start = 0, end = 0; while ((end = text.indexOf(repl, start)) != -1) { buf.append(text.substring(start, end)).append(with); start = end + repl.length(); if (--max == 0) { break; } } buf.append(text.substring(start)); return buf.toString(); } /** * <p>Overlay a part of a String with another String.</p> * * @param text String to do overlaying in * @param overlay String to overlay * @param start int to start overlaying at * @param end int to stop overlaying before * @return String with overlayed text * @throws NullPointerException if text or overlay is <code>null</code> */ public static String overlayString(String text, String overlay, int start, int end) { return new StringBuffer(start + overlay.length() + text.length() - end + 1) .append(text.substring(0, start)) .append(overlay) .append(text.substring(end)) .toString(); } // Centering /** * <p>Center a String in a larger String of size <code>n</code>.<p> * * <p>Uses spaces as the value to buffer the String with. * Equivalent to <code>center(str, size, " ")</code>.</p> * * @param str String to center * @param size int size of new String * @return String containing centered String * @throws NullPointerException if str is <code>null</code> */ public static String center(String str, int size) { return center(str, size, " "); } /** * <p>Center a String in a larger String of size <code>n</code>.</p> * * <p>Uses a supplied String as the value to buffer the String with.</p> * * @param str String to center * @param size int size of new String * @param delim String to buffer the new String with * @return String containing centered String * @throws NullPointerException if str or delim is <code>null</code> * @throws ArithmeticException if delim is the empty String */ public static String center(String str, int size, String delim) { int sz = str.length(); int p = size - sz; if (p < 1) { return str; } str = leftPad(str, sz + p / 2, delim); str = rightPad(str, size, delim); return str; } // Chomping /** * <p>Remove one newline from end of a String if it's there, * otherwise leave it alone. A newline is &quot;<code>\n</code>&quot;, * &quot;<code>\r</code>&quot;, or &quot;<code>\r\n</code>&quot;.</p> * * <p>Note that this behavior has changed from 1.0. It * now more closely matches Perl chomp. For the previous behavior, * use {@link #slice(String)}.</p> * * @param str String to chomp a newline from * @return String without newline * @throws NullPointerException if str is <code>null</code> */ public static String chomp(String str) { if (str.length() == 0) { return str; } if (str.length() == 1) { if ("\r".equals(str) || "\n".equals(str)) { return ""; } else { return str; } } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); if (last == '\n') { if (str.charAt(lastIdx - 1) == '\r') { lastIdx } } else if (last == '\r') { } else { lastIdx++; } return str.substring(0, lastIdx); } /** * <p>Remove <code>separator</code> from the end of * <code>str</code> if it's there, otherwise leave it alone.</p> * * <p>Note that this behavior has changed from 1.0. It * now more closely matches Perl chomp. For the previous behavior, * use {@link #slice(String,String)}.</p> * * @param str string to chomp from * @param separator separator string * @return String without trailing separator * @throws NullPointerException if str is <code>null</code> */ public static String chomp(String str, String separator) { if (str.length() == 0) { return str; } if (str.endsWith(separator)) { return str.substring(0, str.length() - separator.length()); } return str; } /** * <p>Remove any &quot;\n&quot; if and only if it is at the end * of the supplied String.</p> * * @param str String to chomp from * @return String without chomped ending * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str) { return chompLast(str, "\n"); } /** * <p>Remove a value if and only if the String ends with that value.</p> * * @param str String to chomp from * @param sep String to chomp * @return String without chomped ending * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #chomp(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str, String sep) { if (str.length() == 0) { return str; } String sub = str.substring(str.length() - sep.length()); if (sep.equals(sub)) { return str.substring(0, str.length() - sep.length()); } else { return str; } } /** * <p>Remove everything and return the last value of a supplied String, and * everything after it from a String. * [That makes no sense. Just use sliceRemainder() :-)]</p> * * @param str String to chomp from * @param sep String to chomp * @return String chomped * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #sliceRemainder(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String getChomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return ""; } } /** * <p>Remove the first value of a supplied String, and everything before it * from a String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String without chomped beginning * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #sliceFirstRemainder(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String prechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(idx + sep.length()); } else { return str; } } /** * <p>Remove and return everything before the first value of a * supplied String from another String.</p> * * @param str String to chomp from * @param sep String to chomp * @return String prechomped * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #sliceFirst(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String getPrechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(0, idx + sep.length()); } else { return ""; } } // Chopping /** * <p>Remove the last character from a String.</p> * * <p>If the String ends in <code>\r\n</code>, then remove both * of them.</p> * * @param str String to chop last character from * @return String without last character * @throws NullPointerException if str is <code>null</code> */ public static String chop(String str) { if ("".equals(str)) { return ""; } if (str.length() == 1) { return ""; } int lastIdx = str.length() - 1; String ret = str.substring(0, lastIdx); char last = str.charAt(lastIdx); if (last == '\n') { if (ret.charAt(lastIdx - 1) == '\r') { return ret.substring(0, lastIdx - 1); } } return ret; } /** * <p>Remove <code>\n</code> from end of a String if it's there. * If a <code>\r</code> precedes it, then remove that too.</p> * * @param str String to chop a newline from * @return String without newline * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chopNewline(String str) { int lastIdx = str.length() - 1; if (lastIdx <= 0) { return ""; } char last = str.charAt(lastIdx); if (last == '\n') { if (str.charAt(lastIdx - 1) == '\r') { lastIdx } } else { lastIdx++; } return str.substring(0, lastIdx); } // Slicing /** * <p>Remove the last newline, and everything after it from a String.</p> * * <p><em>(This method was formerly named chomp or chopNewline.)</em></p> * * @param str String to slice the newline from * @return String without sliced newline * @throws NullPointerException if str is <code>null</code> */ public static String slice(String str) { return slice(str, "\n"); } /** * <p>Find the last occurence of a separator String; * remove it and everything after it.</p> * * <p><em>(This method was formerly named chomp.)</em></p> * * @param str String to slice from * @param sep String to slice * @return String without sliced ending * @throws NullPointerException if str or sep is <code>null</code> */ public static String slice(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx != -1) { return str.substring(0, idx); } else { return str; } } /** * <p>Find the last occurence of a separator String, and return * everything after it.</p> * * <p><em>(This method was formerly named getchomp. Also, now it does not * include the separator in the return value.)</em></p> * * @param str String to slice from * @param sep String to slice * @return String sliced * @throws NullPointerException if str or sep is <code>null</code> */ public static String sliceRemainder(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return ""; } else if (idx != -1) { return str.substring(idx + sep.length()); } else { return ""; } } /** * <p>Find the first occurence of a separator String, and return * everything after it.</p> * * <p><em>(This method was formerly named prechomp. Also, previously * it included the separator in the return value; now it does not.)</em></p> * * @param str String to slice from * @param sep String to slice * @return String without sliced beginning * @throws NullPointerException if str or sep is <code>null</code> */ public static String sliceFirstRemainder(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(idx + sep.length()); } else { return str; } } /** * <p>Find the first occurence of a separator string; * return everything before it (but not including the separator).</p> * * <p><em>(This method was formerly named getPrechomp. Also, it used to * include the separator, but now it does not.)</em></p> * * @param str String to slice from * @param sep String to slice * @return String presliced * @throws NullPointerException if str or sep is <code>null</code> */ public static String sliceFirst(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(0, idx); } else { return ""; } } // Conversion /** * <p>Escapes any values it finds into their String form.</p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * <p>As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(java.lang.String)} * behind the scenes. * </p> * @see StringEscapeUtils#escapeJava(java.lang.String) * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link StringEscapeUtils#escapeJava(java.lang.String)} * This method will be removed in Commons Lang 3.0 */ public static String escape(String str) { return StringEscapeUtils.escapeJava(str); } /** * <p>Unescapes any Java literals found in the String. For example, * it will turn a sequence of <code>'\'</code> and <code>'n'</code> * into a newline character, unless the <code>'\'</code> is preceded * by another <code>'\'</code>.</p> * * <p>As of Lang 2.0, this calls {@link StringEscapeUtils#unescapeJava(java.lang.String)} * behind the scenes.</p> * * @see StringEscapeUtils#unescapeJava(java.lang.String) * @deprecated Use {@link StringEscapeUtils#unescapeJava(java.lang.String)} * This method will be removed in Commons Lang 3.0 */ public static String unescape(String str) { return StringEscapeUtils.unescapeJava(str); } // Padding /** * <p>Repeat a String <code>n</code> times to form a * new string.</p> * * @param str String to repeat * @param repeat number of times to repeat str * @return String with repeated String * @throws NegativeArraySizeException if <code>repeat < 0</code> * @throws NullPointerException if str is <code>null</code> */ public static String repeat(String str, int repeat) { if (str.length() == 1 && repeat <= PAD_LIMIT) { return padding(repeat, str.charAt(0)); } StringBuffer buffer = new StringBuffer(repeat * str.length()); for (int i = 0; i < repeat; i++) { buffer.append(str); } return buffer.toString(); } /** * <p>Returns blank padding with a given length.</p> * * @param repeat number of times to repeat a blank * @return String with repeated character * @throws IndexOutOfBoundsException if repeat < 0 */ private static String padding(int repeat) { while (blanks.length() < repeat) { blanks = blanks.concat(blanks); } return blanks.substring(0, repeat); } /** * <p>Returns padding using the specified delimiter repeated * to a given length.</p> * * @param repeat number of times to repeat delim * @param delim character to repeat * @return String with repeated character * @throws NullPointerException if delim is <code>null</code> * @throws IndexOutOfBoundsException if repeat < 0 */ private static String padding(int repeat, char delim) { if (padding[delim] == null) { padding[delim] = String.valueOf(delim); } while (padding[delim].length() < repeat) { padding[delim] = padding[delim].concat(padding[delim]); } return padding[delim].substring(0, repeat); } /** * <p>Right pad a String with spaces.</p> * * <p>The String is padded to the size of <code>n</code>.</p> * * @param str String to pad out * @param size number of times to repeat str * @return right padded String or original String if no padding is necessary * @throws NullPointerException if str is <code>null</code> */ public static String rightPad(String str, int size) { int pads = size - str.length(); if (pads <= 0) { return str; // returns original string when possible } if (pads > PAD_LIMIT) { return rightPad(str, size, ' '); } return str + padding(pads); } /** * <p>Right pad a String with a specified character.</p> * * <p>The String is padded to the size of <code>n</code>.</p> * * @param str String to pad out * @param size size to pad to * @param delim character to pad with * @return right padded String or original String if no padding is necessary * @throws NullPointerException if str or delim is <code>null<code> */ public static String rightPad(String str, int size, char delim) { int pads = size - str.length(); if (pads <= 0) { return str; // returns original string when possible } if (pads > PAD_LIMIT) { return rightPad(str, size, String.valueOf(delim)); } return str + padding(pads, delim); } /** * <p>Right pad a String with a specified string.</p> * * <p>The String is padded to the size of <code>n</code>.</p> * * @param str String to pad out * @param size size to pad to * @param delim String to pad with * @return right padded String or original String if no padding is necessary * @throws NullPointerException if str or delim is <code>null<code> * @throws ArithmeticException if delim is the empty String */ public static String rightPad(String str, int size, String delim) { if (delim.length() == 1 && size - str.length() <= PAD_LIMIT) { return rightPad(str, size, delim.charAt(0)); } size = (size - str.length()) / delim.length(); if (size > 0) { str += repeat(delim, size); } return str; } /** * <p>Left pad a String with spaces.</p> * * <p>The String is padded to the size of <code>n<code>.</p> * * @param str String to pad out * @param size size to pad to * @return left padded String or original String if no padding is necessary * @throws NullPointerException if str or delim is <code>null<code> */ public static String leftPad(String str, int size) { int pads = size - str.length(); if (pads <= 0) { return str; // returns original string when possible } if (pads > PAD_LIMIT) { return leftPad(str, size, ' '); } return padding(pads).concat(str); } /** * <p>Left pad a String with a specified character.</p> * * <p>Pad to a size of <code>n</code>.</p> * * @param str String to pad out * @param size size to pad to * @param delim character to pad with * @return left padded String or original String if no padding is necessary * @throws NullPointerException if str or delim is <code>null</code> */ public static String leftPad(String str, int size, char delim) { int pads = size - str.length(); if (pads <= 0) { return str; // returns original string when possible } if (pads > PAD_LIMIT) { return leftPad(str, size, ' '); } return padding(pads, delim).concat(str); } /** * <p>Left pad a String with a specified string.</p> * * <p>Pad to a size of <code>n</code>.</p> * * @param str String to pad out * @param size size to pad to * @param delim String to pad with * @return left padded String or original String if no padding is necessary * @throws NullPointerException if str or delim is null * @throws ArithmeticException if delim is the empty string */ public static String leftPad(String str, int size, String delim) { if (delim.length() == 1 && size - str.length() <= PAD_LIMIT) return leftPad(str, size, delim.charAt(0)); size = (size - str.length()) / delim.length(); if (size > 0) { str = repeat(delim, size) + str; } return str; } // Stripping /** * <p>Remove whitespace from the front and back of a String.</p> * * @param str the String to remove whitespace from * @return the stripped String */ public static String strip(String str) { return strip(str, null); } /** * <p>Remove a specified String from the front and back of a * String.</p> * * <p>If whitespace is wanted to be removed, used the * {@link #strip(java.lang.String)} method.</p> * * @param str the String to remove a string from * @param delim the String to remove at start and end * @return the stripped String */ public static String strip(String str, String delim) { str = stripStart(str, delim); return stripEnd(str, delim); } /** * <p>Strip whitespace from the front and back of every String * in the array.</p> * * @param strs the Strings to remove whitespace from * @return the stripped Strings */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** * <p>Strip the specified delimiter from the front and back of * every String in the array.</p> * * @param strs the Strings to remove a String from * @param delimiter the String to remove at start and end * @return the stripped Strings */ public static String[] stripAll(String[] strs, String delimiter) { if ((strs == null) || (strs.length == 0)) { return strs; } int sz = strs.length; String[] newArr = new String[sz]; for (int i = 0; i < sz; i++) { newArr[i] = strip(strs[i], delimiter); } return newArr; } /** * <p>Strip any of a supplied String from the end of a String.</p> * * <p>If the strip String is <code>null</code>, whitespace is * stripped.</p> * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ public static String stripEnd(String str, String strip) { if (str == null) { return null; } int end = str.length(); if (strip == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end } } else { while ((end != 0) && (strip.indexOf(str.charAt(end - 1)) != -1)) { end } } return str.substring(0, end); } /** * <p>Strip any of a supplied String from the start of a String.</p> * * <p>If the strip String is <code>null</code>, whitespace is * stripped.</p> * * @param str the String to remove characters from * @param strip the String to remove * @return the stripped String */ public static String stripStart(String str, String strip) { if (str == null) { return null; } int start = 0; int sz = str.length(); if (strip == null) { while ((start != sz) && Character.isWhitespace(str.charAt(start))) { start++; } } else { while ((start != sz) && (strip.indexOf(str.charAt(start)) != -1)) { start++; } } return str.substring(start); } // Case conversion /** * <p>Convert a String to upper case, <code>null</code> String * returns <code>null</code>.</p> * * @param str the String to uppercase * @return the upper cased String */ public static String upperCase(String str) { if (str == null) { return null; } return str.toUpperCase(); } /** * <p>Convert a String to lower case, <code>null</code> String * returns <code>null</code>.</p> * * @param str the string to lowercase * @return the lower cased String */ public static String lowerCase(String str) { if (str == null) { return null; } return str.toLowerCase(); } /** * <p>Uncapitalise a String.</p> * * <p>That is, convert the first character into lower-case. * <code>null</code> is returned as <code>null</code>.</p> * * @param str the String to uncapitalise * @return uncapitalised String */ public static String uncapitalise(String str) { if (str == null) { return null; } else if (str.length() == 0) { return ""; } else { return new StringBuffer(str.length()) .append(Character.toLowerCase(str.charAt(0))) .append(str.substring(1)) .toString(); } } /** * <p>Capitalise a String.</p> * * <p>That is, convert the first character into title-case. * <code>null</code> is returned as <code>null</code>.</p> * * @param str the String to capitalise * @return capitalised String */ public static String capitalise(String str) { if (str == null) { return null; } else if (str.length() == 0) { return ""; } else { return new StringBuffer(str.length()) .append(Character.toTitleCase(str.charAt(0))) .append(str.substring(1)) .toString(); } } /** * <p>Swaps the case of String.</p> * * <p>Properly looks after making sure the start of words * are Titlecase and not Uppercase.</p> * * <p><code>null</code> is returned as <code>null</code>.</p> * * @param str the String to swap the case of * @return the modified String */ public static String swapCase(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean whitespace = false; char ch = 0; char tmp = 0; for (int i = 0; i < sz; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { if (whitespace) { tmp = Character.toTitleCase(ch); } else { tmp = Character.toUpperCase(ch); } } else { tmp = ch; } buffer.append(tmp); whitespace = Character.isWhitespace(ch); } return buffer.toString(); } /** * <p>Capitalise all the words in a String.</p> * * <p>Uses {@link Character#isWhitespace(char)} as a * separator between words.</p> * * <p><code>null</code> will return <code>null</code>.</p> * * @param str the String to capitalise * @return capitalised String */ public static String capitaliseAllWords(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean space = true; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch)) { buffer.append(ch); space = true; } else if (space) { buffer.append(Character.toTitleCase(ch)); space = false; } else { buffer.append(ch); } } return buffer.toString(); } /** * <p>Uncapitalise all the words in a string.</p> * * <p>Uses {@link Character#isWhitespace(char)} as a * separator between words.</p> * * <p><code>null</code> will return <code>null</code>.</p> * * @param str the string to uncapitalise * @return uncapitalised string */ public static String uncapitaliseAllWords(String str) { if (str == null) { return null; } int sz = str.length(); StringBuffer buffer = new StringBuffer(sz); boolean space = true; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (Character.isWhitespace(ch)) { buffer.append(ch); space = true; } else if (space) { buffer.append(Character.toLowerCase(ch)); space = false; } else { buffer.append(ch); } } return buffer.toString(); } // Nested extraction /** * <p>Get the String that is nested in between two instances of the * same String.</p> * * <p>If <code>str</code> is <code>null</code>, will * return <code>null</code>.</p> * * @param str the String containing nested-string * @param tag the String before and after nested-string * @return the String that was nested, or <code>null</code> * @throws NullPointerException if tag is <code>null</code> */ public static String getNestedString(String str, String tag) { return getNestedString(str, tag, tag); } /** * <p>Get the String that is nested in between two Strings.</p> * * @param str the String containing nested-string * @param open the String before nested-string * @param close the String after nested-string * @return the String that was nested, or <code>null</code> * @throws NullPointerException if open or close is <code>null</code> */ public static String getNestedString(String str, String open, String close) { if (str == null) { return null; } int start = str.indexOf(open); if (start != -1) { int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } /** * <p>How many times is the substring in the larger String.</p> * * <p><code>null</code> returns <code>0</code>.</p> * * @param str the String to check * @param sub the substring to count * @return the number of occurances, 0 if the String is <code>null</code> * @throws NullPointerException if sub is <code>null</code> */ public static int countMatches(String str, String sub) { if (sub.equals("")) { return 0; } if (str == null) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != -1) { count++; idx += sub.length(); } return count; } // Character Tests /** * <p>Checks if the String contains only unicode letters.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters, and is non-null */ public static boolean isAlpha(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetter(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only whitespace.</p> * * <p><code>null</code> will return <code>false</code>. An * empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains whitespace, and is non-null */ public static boolean isWhitespace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isWhitespace(str.charAt(i)) == false) ) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters and * space (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An * empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters and space, * and is non-null */ public static boolean isAlphaSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters or digits.</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters or digits, * and is non-null */ public static boolean isAlphanumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetterOrDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters, digits * or space (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains letters, digits or space, * and is non-null */ public static boolean isAlphanumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits or space * (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. An empty * String will return <code>true</code>.</p> * * @param str the String to check * @return <code>true</code> if only contains digits or space, * and is non-null */ public static boolean isNumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only certain chars.</p> * * @param str the String to check * @param validChars a string of valid chars * @return true if it only contains valid chars and is non-null */ public static boolean containsOnly(String str, String validChars) { if (str == null || validChars == null) { return false; } return containsOnly(str, validChars.toCharArray()); } /** * <p>Checks if the String contains only certain chars.</p> * * @param str the String to check * @param validChars an array of valid chars * @return true if it only contains valid chars and is non-null */ /* rewritten public static boolean containsOnly(String str, char[] validChars) { if (str == null || validChars == null) { return false; } int strSize = str.length(); int validSize = validChars.length; for (int i = 0; i < strSize; i++) { char ch = str.charAt(i); boolean contains = false; for (int j = 0; j < validSize; j++) { if (validChars[j] == ch) { contains = true; break; } } if (contains == false) { return false; } } return true; } */ /** * <p>Checks that the String does not contain certain chars.</p> * * @param str the String to check * @param invalidChars a string of invalid chars * @return true if it contains none of the invalid chars, or is null */ public static boolean containsNone(String str, String invalidChars) { if (str == null || invalidChars == null) { return true; } return containsNone(str, invalidChars.toCharArray()); } /** * <p>Checks that the String does not contain certain chars.</p> * * @param str the String to check * @param invalidChars an array of invalid chars * @return true if it contains none of the invalid chars, or is null */ public static boolean containsNone(String str, char[] invalidChars) { if (str == null || invalidChars == null) { return true; } int strSize = str.length(); int validSize = invalidChars.length; for (int i = 0; i < strSize; i++) { char ch = str.charAt(i); for (int j = 0; j < validSize; j++) { if (invalidChars[j] == ch) { return false; } } } return true; } /** * <p>Checks if the String contains only certain chars.</p> * * @param str the String to check * @param valid an array of valid chars * @return true if it only contains valid chars and is non-null */ public static boolean containsOnly(String str, char[] valid) { // All these pre-checks are to maintain API with an older version if( (valid == null) || (str == null) ) { return false; } if(str.length() == 0) { return true; } if(valid.length == 0) { return false; } return indexOfAnyBut(str, valid) == -1; } /** * <p>Search a String to find the first index of any * character not in the given set of characters.</p> * * @param str the String to check * @param searchChars the chars to search for * @return the index of any of the chars * @throws NullPointerException if either str or searchChars is <code>null</code> */ public static int indexOfAnyBut(String str, char[] searchChars) { if(searchChars == null) { return -1; } return indexOfAnyBut(str, new String(searchChars)); } /** * <p>Search a String to find the first index of any * character not in the given set of characters.</p> * * @param str the String to check * @param searchChars a String containing the chars to search for * @return the last index of any of the chars * @throws NullPointerException if either str or searchChars is <code>null</code> */ public static int indexOfAnyBut(String str, String searchChars) { if (str == null || searchChars == null) { return -1; } for (int i = 0; i < str.length(); i ++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; } // Defaults /** * <p>Returns either the passed in <code>Object</code> as a String, * or, if the <code>Object</code> is <code>null</code>, an empty * String.</p> * * @param obj the Object to check * @return the passed in Object's toString, or blank if it was * <code>null</code> */ public static String defaultString(Object obj) { return defaultString(obj, ""); } /** * <p>Returns either the passed in <code>Object</code> as a String, * or, if the <code>Object</code> is <code>null</code>, a passed * in default String.</p> * * @param obj the Object to check * @param defaultString the default String to return if str is * <code>null</code> * @return the passed in string, or the default if it was * <code>null</code> */ public static String defaultString(Object obj, String defaultString) { return (obj == null) ? defaultString : obj.toString(); } // Reversing /** * <p>Reverse a String.</p> * * <p><code>null</code> String returns <code>null</code>.</p> * * @param str the String to reverse * @return the reversed String */ public static String reverse(String str) { if (str == null) { return null; } return new StringBuffer(str).reverse().toString(); } /** * <p>Reverses a String that is delimited by a specific character.</p> * * <p>The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is <code>'.'</code>).</p> * * @param str the String to reverse * @param delimiter the delimiter to use * @return the reversed String */ public static String reverseDelimitedString(String str, String delimiter) { // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, delimiter); ArrayUtils.reverse(strs); return join(strs, delimiter); } // Abbreviating public static String abbreviate(String s, int maxWidth) { return abbreviate(s, 0, maxWidth); } /** * <p>Turn "Now is the time for all good men" into "...is the time for..."</p> * * <p>Works like <code>abbreviate(String, int)</code>, but allows you to specify * a "left edge" offset. Note that this left edge is not necessarily going to * be the leftmost character in the result, or the first character following the * ellipses, but it will appear somewhere in the result. * * <p>In no case will it return a string of length greater than * <code>maxWidth</code>.</p> * * @param offset left edge of source string * @param maxWidth maximum length of result string */ public static String abbreviate(String s, int offset, int maxWidth) { if (maxWidth < 4) throw new IllegalArgumentException("Minimum abbreviation width is 4"); if (s.length() <= maxWidth) return s; if (offset > s.length()) offset = s.length(); if ((s.length() - offset) < (maxWidth-3)) offset = s.length() - (maxWidth-3); if (offset <= 4) return s.substring(0, maxWidth-3) + "..."; if (maxWidth < 7) throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); if ((offset + (maxWidth-3)) < s.length()) return "..." + abbreviate(s.substring(offset), maxWidth-3); return "..." + s.substring(s.length() - (maxWidth-3)); } // Difference /** * <p>Compare two strings, and return the portion where they differ. * (More precisely, return the remainder of the second string, * starting from where it's different from the first.)</p> * * <p> * For example, <code>difference("i am a machine", "i am a robot") -> "robot"</code> * * @return the portion of s2 where it differs from s1; returns the empty string ("") if they are equal */ public static String difference(String s1, String s2) { int at = differenceAt(s1, s2); if (at == -1) { return ""; } return s2.substring(at); } /** * <p>Compare two strings, and return the index at which the strings begin to differ.</p> * * <p>For example, <code>differenceAt("i am a machine", "i am a robot") -> 7</code></p> * * @return the index where s2 and s1 begin to differ; -1 if they are equal */ public static int differenceAt(String s1, String s2) { int i; for (i=0; i<s1.length() && i<s2.length(); ++i) { if (s1.charAt(i) != s2.charAt(i)) { break; } } if (i<s2.length() || i<s1.length()) { return i; } return -1; } // Misc public static int getLevenshteinDistance(String s, String t) { int d[][]; // matrix int n; // length of s int m; // length of t int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost // Step 1 n = s.length(); m = t.length(); if (n == 0) { return m; } if (m == 0) { return n; } d = new int[n + 1][m + 1]; // Step 2 for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (i = 1; i <= n; i++) { s_i = s.charAt(i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); // Step 5 if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 d[i][j] = NumberUtils.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); } } // Step 7 return d[n][m]; } }
package org.deuce.transaction.tl2cm; import org.deuce.transaction.tl2cm.field.ReadFieldAccess; import org.deuce.transform.Exclude; /** * Represents the transaction read set. Based on Guy Korland's work on <code>org.deuce.transaction.tl2.*</code> * * @author Yoav Cohen, yoav.cohen@cs.tau.ac.il */ @Exclude public class ReadSet{ private static final int DEFAULT_CAPACITY = 1024; private ReadFieldAccess[] readSet = new ReadFieldAccess[DEFAULT_CAPACITY]; private int nextAvaliable = 0; private ReadFieldAccess currentReadFieldAccess = null; public ReadSet(){ fillArray( 0); } public void clear() { nextAvaliable = 0; } private void fillArray( int offset){ for( int i=offset ; i < readSet.length ; ++i){ readSet[i] = new ReadFieldAccess(); } } public ReadFieldAccess getNext() { if( nextAvaliable >= readSet.length){ int orignLength = readSet.length; ReadFieldAccess[] tmpReadSet = new ReadFieldAccess[ 2*orignLength]; System.arraycopy(readSet, 0, tmpReadSet, 0, orignLength); readSet = tmpReadSet; fillArray( orignLength); } currentReadFieldAccess = readSet[ nextAvaliable++]; return currentReadFieldAccess; } public ReadFieldAccess getCurrent(){ return currentReadFieldAccess; } public boolean validate(int version) { for (int i = 0; i < nextAvaliable; i++) { ReadFieldAccess field = readSet[i]; int hash = field.hashCode(); long lock = LockTable.getLock(hash); int lockVersion = LockTable.getVersion(lock); if (lockVersion > version || LockTable.isLocked(lock)) { return false; } } return true; } public int size() { return nextAvaliable; } public interface ReadSetListener{ void execute( ReadFieldAccess read); } }