answer
stringlengths
17
10.2M
package org.caleydo.view.rnb.internal.toolbar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.caleydo.core.data.collection.EDimension; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.core.view.opengl.layout2.basic.GLButton; import org.caleydo.core.view.opengl.layout2.basic.GLButton.ISelectionCallback; import org.caleydo.core.view.opengl.layout2.manage.ButtonBarBuilder; import org.caleydo.core.view.opengl.layout2.manage.ButtonBarBuilder.EButtonBarLayout; import org.caleydo.core.view.opengl.layout2.manage.GLElementFactories.GLElementSupplier; import org.caleydo.core.view.opengl.layout2.manage.GLElementFactorySwitcher; import org.caleydo.view.rnb.api.model.EDirection; import org.caleydo.view.rnb.internal.Block; import org.caleydo.view.rnb.internal.Node; import org.caleydo.view.rnb.internal.NodeGroup; import org.caleydo.view.rnb.internal.NodeSelections; import org.caleydo.view.rnb.internal.Resources; import org.caleydo.view.rnb.internal.UndoStack; import org.caleydo.view.rnb.internal.undo.ChangeVisTypeToCmd; import org.caleydo.view.rnb.internal.undo.ExplodeSlicesCmd; import org.caleydo.view.rnb.internal.undo.LimitToNodeCmd; import org.caleydo.view.rnb.internal.undo.MergeGroupsCmd; import org.caleydo.view.rnb.internal.undo.RemoveBlockCmd; import org.caleydo.view.rnb.internal.undo.RemoveNodeCmd; import org.caleydo.view.rnb.internal.undo.RemoveNodeGroupCmd; import org.caleydo.view.rnb.internal.undo.RemoveSliceCmd; import org.caleydo.view.rnb.internal.undo.SortByNodesCmd; import org.caleydo.view.rnb.internal.undo.TransposeBlocksCmd; import org.caleydo.view.rnb.internal.undo.TransposeNodeViewCmd; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multiset; /** * @author Samuel Gratzl * */ public class NodeTools extends AItemTools { private final Set<NodeGroup> selection; public NodeTools(UndoStack undo, NodeGroup group) { this(undo, Collections.singleton(group)); } /** * @param selection */ public NodeTools(UndoStack undo, Set<NodeGroup> selection) { super(undo); this.selection = selection; if (selection.size() == 1) { createSingle(selection.iterator().next()); } else createMulti(); } /** * @return the selection, see {@link #selection} */ public Set<NodeGroup> getSelection() { return selection; } private void createMulti() { Set<Node> nodes = NodeSelections.getFullNodes(selection); Set<Block> blocks = NodeSelections.getFullBlocks(selection); if (nodes.size() == 1) { Node node = nodes.iterator().next(); addSingleNode(node); if (blocks.size() == 1) // a single node with a single block addBlockActions(blocks); if (node.groupCount() == selection.size()) { if (blocks.size() == 0) addButton("Transpose View", Resources.ICON_TRANSPOSE); addButton("Remove Node", Resources.ICON_DELETE_ALL); } } else if (!nodes.isEmpty() && blocks.isEmpty()) { addMultiNodes(nodes); addButton("Remove Nodes", Resources.ICON_DELETE_ALL); } else if (!blocks.isEmpty()) { if (areAllSingleBlocks(blocks)) { outer: for (EDimension dim : EDimension.values()) { for (Block block : blocks) { if (!((Node) block.get(0)).has(dim)) continue outer; } if (dim.isHorizontal()) { addButton("Sort Dims", Resources.ICON_SORT_DIM); addButton("Stratify Dims", Resources.ICON_SORT_DIM); } else { addButton("Sort Recs", Resources.ICON_SORT_REC); addButton("Stratify Recs", Resources.ICON_SORT_REC); } } } addBlockActions(blocks); addButton("Transpose Blocks", Resources.ICON_TRANSPOSE); addMultiNodes(nodes); if (blocks.size() == 1) addButton("Remove Block", Resources.ICON_DELETE); else addButton("Remove Blocks", Resources.ICON_DELETE_ALL); } else { Node node = NodeSelections.getSingleNode(selection, false); if (node != null) { EDimension dim = node.getSingleGroupingDimension(); if (dim != null) addButton("Merge Groups", dim.select(Resources.ICON_MERGE_DIM, Resources.ICON_MERGE_REC)); } } } void addBlockActions(Set<Block> blocks) { for (EDimension dim : EDimension.values()) { boolean canExplode = true; for (Block block : blocks) { canExplode = canExplode && block.canExplode(dim); } if (!canExplode) continue; if (dim.isHorizontal()) addButton("Explode Dim", Resources.ICON_EXPLODE_DIM); else addButton("Explode Rec", Resources.ICON_EXPLODE_REC); } } /** * @param blocks * @return */ private static boolean areAllSingleBlocks(Set<Block> blocks) { for (Block b : blocks) if (b.size() != 1) return false; return true; } private void addMultiNodes(Set<Node> nodes) { ButtonBarBuilder b = new ButtonBarBuilder(); b.layoutAs(EButtonBarLayout.SLIDE_DOWN); b.customCallback(new ChangeVisTypeTo(nodes)); GLElementFactorySwitcher start = nodes.iterator().next().getRepresentableSwitcher(); if (nodes.size() == 1) { this.add(b.build(start, start.getActiveId())); } else { Collection<GLElementSupplier> s = Lists.newArrayList(start); Multiset<String> actives = HashMultiset.create(); for (Node node : nodes) { final GLElementFactorySwitcher swi = node.getRepresentableSwitcher(); Set<String> ids = getIds(swi); for (Iterator<GLElementSupplier> it = s.iterator(); it.hasNext();) { if (!ids.contains(it.next().getId())) it.remove(); } actives.add(swi.getActiveId()); } if (s.isEmpty()) return; String initialID = mostFrequent(actives); this.add(b.build(s, initialID)); } } /** * @param actives * @return */ private static <T> T mostFrequent(Multiset<T> sets) { if (sets.isEmpty()) return null; Set<T> elems = sets.elementSet(); T maxV = elems.iterator().next(); int max = sets.count(maxV); for (T elem : elems) { int c = sets.count(elem); if (c > max) { max = c; maxV = elem; } } return maxV; } private Set<String> getIds(final GLElementFactorySwitcher switcher) { final Set<String> ids = new HashSet<>(); for (GLElementSupplier s : switcher) ids.add(s.getId()); return ids; } /** * @param next */ private void createSingle(NodeGroup group) { Node node = group.getNode(); addSingleNode(node); final int ngroups = node.groupCount(); final int nnodes = node.getBlock().size(); if (nnodes > 1 && ngroups == 1) addButton("Transpose View", Resources.ICON_TRANSPOSE); if (group.canBeRemoved()) addButton("Remove Group", Resources.ICON_DELETE); else addButton("Remove Node", Resources.ICON_DELETE_ALL); if (ngroups > 1) { addButton("Select All In Node", Resources.ICON_SELECT_ALL); } if (nnodes > 1) { addButton("Select All In Block", Resources.ICON_SELECT_ALL); } if (group.getNeighbor(EDirection.WEST) != null || group.getNeighbor(EDirection.EAST) != null) addButton("Select Hor", Resources.ICON_SELECT_DIM); if (group.getNeighbor(EDirection.NORTH) != null || group.getNeighbor(EDirection.SOUTH) != null) addButton("Select Ver", Resources.ICON_SELECT_REC); GLElement parameter = group.createVisParameter(); if (parameter != null) this.add(parameter); } /** * @param node */ private void addSingleNode(Node node) { if (node.has(EDimension.DIMENSION)) { addButton("Sort Dim", Resources.ICON_SORT_DIM); if (node.getUnderlyingData(EDimension.DIMENSION).getGroups().size() > 1) addButton("Stratify Dim", Resources.ICON_STRATIFY_DIM); } if (node.has(EDimension.RECORD)) { addButton("Sort Rec", Resources.ICON_SORT_REC); if (node.getUnderlyingData(EDimension.RECORD).getGroups().size() > 1) addButton("Stratify Rec", Resources.ICON_STRATIFY_REC); } final boolean recAlone = node.isAlone(EDimension.RECORD); if (node.has(EDimension.DIMENSION) && !recAlone) { addButton("Limit Dim", Resources.ICON_LIMIT_DATA_DIM); } final boolean dimAlone = node.isAlone(EDimension.DIMENSION); if (node.has(EDimension.RECORD) && !dimAlone) { addButton("Limit Rec", Resources.ICON_LIMIT_DATA_REC); } if (recAlone && dimAlone) { addButton("Transpose", Resources.ICON_TRANSPOSE); } addMultiNodes(Collections.singleton(node)); addButton("Open Details", Resources.ICON_FOCUS); } public void triggerDelete() { Set<String> toTest = ImmutableSet.of("Remove Node", "Remove Nodes", "Remove Block", "Remove Blocks"); for (GLButton b : Iterables.filter(this, GLButton.class)) { if (toTest.contains(b.getTooltip())) { b.setSelected(true); break; } } } @Override public void onSelectionChanged(GLButton button, boolean selected) { NodeGroup node = selection.iterator().next(); if (!node.isValid()) return; EDimension dim = EDimension.get(button.getTooltip().contains("Dim")); switch (button.getTooltip()) { case "Sort Dim": case "Sort Rec": undo.push(new SortByNodesCmd(node.getNode(), dim, false)); break; case "Sort Dims": case "Sort Recs": undo.push(SortByNodesCmd.multi(NodeSelections.getFullNodes(selection), dim, false)); break; case "Stratify Dim": case "Stratify Rec": undo.push(new SortByNodesCmd(node.getNode(), dim, true)); break; case "Stratify Dims": case "Stratify Recs": undo.push(SortByNodesCmd.multi(NodeSelections.getFullNodes(selection), dim, true)); break; case "Limit Dim": case "Limit Rec": undo.push(new LimitToNodeCmd(node.getNode(), dim)); break; case "Explode Dim": case "Explode Rec": undo.push(ExplodeSlicesCmd.multi(NodeSelections.getFullBlocks(selection), dim)); break; case "Remove Node": undo.push(new RemoveNodeCmd(node.getNode())); break; case "Remove Nodes": undo.push(RemoveNodeCmd.multi(NodeSelections.getFullNodes(selection))); break; case "Remove Slice": undo.push(new RemoveSliceCmd(node.getNode(), selection)); break; case "Remove Group": undo.push(new RemoveNodeGroupCmd(node)); break; case "Merge Groups": undo.push(new MergeGroupsCmd(node.getNode(), selection)); break; case "Remove Block": undo.push(new RemoveBlockCmd(node.getNode().getBlock())); break; case "Remove Blocks": undo.push(RemoveBlockCmd.multi(NodeSelections.getFullBlocks(selection))); break; case "Select All In Node": node.getNode().selectAll(); break; case "Select All In Block": node.getNode().getBlock().selectAll(); break; case "Select Hor": node.select(EDirection.WEST); node.select(EDirection.EAST); break; case "Select Ver": node.select(EDirection.NORTH); node.select(EDirection.SOUTH); break; case "Transpose": undo.push(new TransposeBlocksCmd(Collections.singleton(node.getNode().getBlock()))); break; case "Transpose Blocks": undo.push(new TransposeBlocksCmd(NodeSelections.getFullBlocks(selection))); break; case "Transpose View": undo.push(new TransposeNodeViewCmd(node.getNode())); break; case "Open Details": node.getNode().showInFocus(); } } private class ChangeVisTypeTo implements ISelectionCallback { private final Collection<Node> nodes; /** * @param singleton */ public ChangeVisTypeTo(Collection<Node> nodes) { this.nodes = nodes; } @Override public void onSelectionChanged(GLButton button, boolean selected) { final String id = button.getLayoutDataAs(GLElementSupplier.class, null).getId(); undo.push(new ChangeVisTypeToCmd(nodes, id)); } } }
package org.exist.xquery.functions.validation; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.exist.Namespaces; import org.exist.dom.QName; import org.exist.memtree.DocumentBuilderReceiver; import org.exist.memtree.MemTreeBuilder; import org.exist.memtree.NodeImpl; import org.exist.memtree.DocumentImpl; import org.exist.storage.BrokerPool; import org.exist.storage.io.ExistIOException; import org.exist.util.Configuration; import org.exist.util.XMLReaderObjectFactory; import org.exist.validation.GrammarPool; import org.exist.validation.ValidationContentHandler; import org.exist.validation.ValidationReport; import org.exist.validation.resolver.SearchResourceResolver; import org.exist.validation.resolver.eXistXMLCatalogResolver; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.FunctionParameterSequenceType; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * xQuery function for validation of XML instance documents * using grammars like XSDs and DTDs. * * @author Dannes Wessels (dizzzz@exist-db.org) */ public class Jaxp extends BasicFunction { private static final String simpleFunctionTxt = "Validate document by parsing $instance. Optionally " + "grammar caching can be enabled. Supported grammars types " + "are '.xsd' and '.dtd'."; private static final String extendedFunctionTxt = "Validate document by parsing $instance. Optionally " + "grammar caching can be enabled and " + "an XML catalog can be specified. Supported grammars types " + "are '.xsd' and '.dtd'."; private static final String documentTxt = "The document referenced as xs:anyURI, a node (element or result of fn:doc()) " + "or as a Java file object."; private static final String catalogTxt = "The catalogs referenced as xs:anyURI's."; private static final String cacheTxt = "Set the flag to true() to enable grammar caching."; private final BrokerPool brokerPool; // Setup function signature public final static FunctionSignature signatures[] = { new FunctionSignature( new QName("jaxp", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt, new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, documentTxt), new FunctionParameterSequenceType("cache-grammars", Type.BOOLEAN, Cardinality.EXACTLY_ONE, cacheTxt) }, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, Shared.simplereportText)), new FunctionSignature( new QName("jaxp", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt, new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, documentTxt), new FunctionParameterSequenceType("cache-grammars", Type.BOOLEAN, Cardinality.EXACTLY_ONE, cacheTxt), new FunctionParameterSequenceType("catalogs", Type.ITEM, Cardinality.ZERO_OR_MORE, catalogTxt),}, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, Shared.simplereportText)), new FunctionSignature( new QName("jaxp-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), simpleFunctionTxt + " An XML report is returned.", new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, documentTxt), new FunctionParameterSequenceType("enable-grammar-cache", Type.BOOLEAN, Cardinality.EXACTLY_ONE, cacheTxt),}, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, Shared.xmlreportText)), new FunctionSignature( new QName("jaxp-report", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), extendedFunctionTxt + " An XML report is returned.", new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, documentTxt), new FunctionParameterSequenceType("enable-grammar-cache", Type.BOOLEAN, Cardinality.EXACTLY_ONE, cacheTxt), new FunctionParameterSequenceType("catalogs", Type.ITEM, Cardinality.ZERO_OR_MORE, catalogTxt),}, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, Shared.xmlreportText)), new FunctionSignature( new QName("jaxp-parse", ValidationModule.NAMESPACE_URI, ValidationModule.PREFIX), "Parse document in validating more, all defaults are filled in according to the " + "grammar (xsd).", new SequenceType[]{ new FunctionParameterSequenceType("instance", Type.ITEM, Cardinality.EXACTLY_ONE, documentTxt), new FunctionParameterSequenceType("enable-grammar-cache", Type.BOOLEAN, Cardinality.EXACTLY_ONE, cacheTxt), new FunctionParameterSequenceType("catalogs", Type.ITEM, Cardinality.ZERO_OR_MORE, catalogTxt),}, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, "Parsed document")) }; public Jaxp(XQueryContext context, FunctionSignature signature) { super(context, signature); brokerPool = context.getBroker().getBrokerPool(); } /** * @throws org.exist.xquery.XPathException * @see BasicFunction#eval(Sequence[], Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { XMLEntityResolver entityResolver = null; GrammarPool grammarPool = null; ValidationReport report = new ValidationReport(); ContentHandler contenthandler = null; MemTreeBuilder instanceBuilder = null; if (isCalledAs("jaxp-parse")) { instanceBuilder = context.getDocumentBuilder(); contenthandler = new DocumentBuilderReceiver(instanceBuilder, true); // (namespace?) } else { contenthandler = new ValidationContentHandler(); } try { report.start(); // Get initialized parser XMLReader xmlReader = getXMLReader(); // Setup validation reporting xmlReader.setContentHandler(contenthandler); xmlReader.setErrorHandler(report); // Get inputstream for instance document InputSource instance = Shared.getInputSource(args[0].itemAt(0), context); // Handle catalog if (args.length == 2) { LOG.debug("No Catalog specified"); } else if (args[2].isEmpty()) { // Use system catalog LOG.debug("Using system catalog."); Configuration config = brokerPool.getConfiguration(); entityResolver = (eXistXMLCatalogResolver) config.getProperty(XMLReaderObjectFactory.CATALOG_RESOLVER); } else { // Get URL for catalog String catalogUrls[] = Shared.getUrls(args[2]); String singleUrl = catalogUrls[0]; if (singleUrl.endsWith("/")) { // Search grammar in collection specified by URL. Just one collection is used. LOG.debug("Search for grammar in " + singleUrl); entityResolver = new SearchResourceResolver(catalogUrls[0], brokerPool); xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_ENTITYRESOLVER, entityResolver); } else if (singleUrl.endsWith(".xml")) { LOG.debug("Using catalogs " + getStrings(catalogUrls)); entityResolver = new eXistXMLCatalogResolver(); ((eXistXMLCatalogResolver) entityResolver).setCatalogList(catalogUrls); xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_ENTITYRESOLVER, entityResolver); } else { LOG.error("Catalog URLs should end on / or .xml"); } } boolean useCache = ((BooleanValue) args[1].itemAt(0)).getValue(); // Use grammarpool if (useCache) { LOG.debug("Grammar caching enabled."); Configuration config = brokerPool.getConfiguration(); grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMER_POOL); xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool); } // Jaxp document LOG.debug("Start parsing document"); xmlReader.parse(instance); LOG.debug("Stopped parsing document"); // Distill namespace from document if (contenthandler instanceof ValidationContentHandler) { report.setNamespaceUri( ((ValidationContentHandler) contenthandler).getNamespaceUri()); } } catch (MalformedURLException ex) { LOG.error(ex.getMessage()); report.setException(ex); } catch (ExistIOException ex) { LOG.error(ex.getCause()); report.setException(ex); } catch (Throwable ex) { LOG.error(ex); report.setException(ex); } finally { report.stop(); } // Create response if (isCalledAs("parse")) { Sequence result = new ValueSequence(); result.add(new BooleanValue(report.isValid())); return result; } else /* isCalledAs("parse-report") */ { if(report.getThrowable()!=null){ throw new XPathException(report.getThrowable().getMessage(), report.getThrowable()); } if (contenthandler instanceof DocumentBuilderReceiver) { //DocumentBuilderReceiver dbr = (DocumentBuilderReceiver) contenthandler; return ((DocumentImpl) instanceBuilder.getDocument()).getNode(0); } else { MemTreeBuilder builder = context.getDocumentBuilder(); NodeImpl result = Shared.writeReport(report, builder); return result; } } } // private XMLReader getXMLReader() throws ParserConfigurationException, SAXException { // setup sax factory ; be sure just one instance! SAXParserFactory saxFactory = SAXParserFactory.newInstance(); // Enable validation stuff saxFactory.setValidating(true); saxFactory.setNamespaceAware(true); // Create xml reader SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setFeature(Namespaces.SAX_VALIDATION, true); xmlReader.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC, false); xmlReader.setFeature(XMLReaderObjectFactory.APACHE_FEATURES_VALIDATION_SCHEMA, true); xmlReader.setFeature(XMLReaderObjectFactory.APACHE_PROPERTIES_LOAD_EXT_DTD, true); xmlReader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true); return xmlReader; } // No-go ...processor is in validating mode private File preparseDTD(StreamSource instance, String systemId) throws IOException, TransformerConfigurationException, TransformerException { // prepare output tmp storage File tmp = File.createTempFile("DTDvalidation", "tmp"); tmp.deleteOnExit(); StreamResult result = new StreamResult(tmp); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemId); transformer.transform(instance, result); return tmp; } private static String getStrings(String[] data) { StringBuilder sb = new StringBuilder(); for (String field : data) { sb.append(field); sb.append(" "); } return sb.toString(); } /* if (args[1].hasOne()) { // Get URL for grammar grammarUrl = Shared.getUrl(args[1].itemAt(0)); // Special case for DTD, the document needs to be rewritten. if (grammarUrl.endsWith(".dtd")) { StreamSource newInstance = Shared.getStreamSource(instance); tmpFile = preparseDTD(newInstance, grammarUrl); instance = new InputSource(new FileInputStream(tmpFile)); } else if (grammarUrl.endsWith(".xsd")) { xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_NONAMESPACESCHEMALOCATION, grammarUrl); } else { throw new XPathException("Grammar type not supported."); } } */ }
package org.cyclops.integrateddynamics.api.part; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; import org.cyclops.cyclopscore.datastructure.DimPos; import org.cyclops.integrateddynamics.core.helper.PartHelpers; import javax.annotation.Nullable; /** * Object holder to refer to a block side and position. * @author rubensworks */ public class PartPos implements Comparable<PartPos> { private final DimPos pos; private final EnumFacing side; public static PartPos of(World world, BlockPos pos, @Nullable EnumFacing side) { return of(DimPos.of(world, pos), side); } public static PartPos of(DimPos pos, @Nullable EnumFacing side) { return new PartPos(pos, side); } private PartPos(DimPos pos, @Nullable EnumFacing side) { this.pos = pos; this.side = side; } public DimPos getPos() { return pos; } @Nullable public EnumFacing getSide() { return side; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof PartPos)) return false; PartPos partPos = (PartPos) o; if (!pos.equals(partPos.pos)) return false; return side == partPos.side; } @Override public int hashCode() { return 31 * pos.hashCode() + (side != null ? side.hashCode() : 0); } @Override public String toString() { return "PartPos{" + "pos=" + pos + ", side=" + side + '}'; } /** * Get part data from the given position. * @param pos The part position. * @return A pair of part type and part state or null if not found. */ public static Pair<IPartType, IPartState> getPartData(PartPos pos) { IPartContainer partContainer = PartHelpers.getPartContainer(pos.getPos(), pos.getSide()); if (partContainer != null) { IPartType partType = partContainer.getPart(pos.getSide()); IPartState partState = partContainer.getPartState(pos.getSide()); if (partType != null && partState != null) { return Pair.of(partType, partState); } } return null; } @Override public int compareTo(PartPos o) { int pos = this.getPos().compareTo(o.getPos()); if (pos == 0) { EnumFacing thisSide = this.getSide(); EnumFacing thatSide = o.getSide(); return thisSide == null ? (thatSide == null ? 0 : -1) : (thatSide == null ? 1 : thisSide.compareTo(thatSide)); } return pos; } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @author <a href="mailto:oliver@wehrens.de">Oliver Wehrens</a> * @version $Id$ */ package org.gridlab.gridsphere.portlet; import java.io.Serializable; import java.util.Comparator; import java.util.Locale; import java.util.ResourceBundle; /** * The <code>PortletRole</code> describes the supported portlet roles used * by the portal. In general, <code>Group</code>s contain <code>User</codes * with a single <code>PortleRole</code> * <p/> * Over time, we plan on allowing users to have more than one role * * @see org.gridlab.gridsphere.portlet.PortletGroup */ public class PortletRole implements Serializable, Comparator, Cloneable { private String oid = null; private int priority; private String roleName = null; private static final int GUEST_ROLE = 1; private static final int USER_ROLE = 2; private static final int ADMIN_ROLE = 3; private static final int SUPER_ROLE = 4; private static final String GUEST_ROLE_STRING = "GUEST"; private static final String USER_ROLE_STRING = "USER"; private static final String ADMIN_ROLE_STRING = "ADMIN"; private static final String SUPER_ROLE_STRING = "SUPER"; public static final PortletRole GUEST = new PortletRole(GUEST_ROLE_STRING, GUEST_ROLE); public static final PortletRole USER = new PortletRole(USER_ROLE_STRING, USER_ROLE); public static final PortletRole ADMIN = new PortletRole(ADMIN_ROLE_STRING, ADMIN_ROLE); public static final PortletRole SUPER = new PortletRole(SUPER_ROLE_STRING, SUPER_ROLE); public PortletRole() { } /** * Constructs an instance of PortletRole */ public PortletRole(String roleName, int priority) { this.roleName = roleName; this.priority = priority; } public static PortletRole toPortletRole(String portletRole) throws IllegalArgumentException { if (portletRole.equalsIgnoreCase("GUEST")) { return GUEST; } else if (portletRole.equalsIgnoreCase("USER")) { return USER; } else if (portletRole.equalsIgnoreCase("ADMIN")) { return ADMIN; } else if (portletRole.equalsIgnoreCase("SUPER")) { return SUPER; } else { throw new IllegalArgumentException("Unable to create PortletRole corresponding to: " + portletRole); } } /** * Returns a locale-specific <code>String</code> representation of * the portlet role * * @return the locale-specific role expressed as a <code>String</code> */ public String getText(Locale locale) { ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); String key = toString(); String value = bundle.getString(key); return value; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } /** * Returns a unique id for this role * * @return a unique id for this role */ public int getID() { return priority; } public void setID(int id) { this.priority = id; } /** * Returns the role name * * @return the role name */ public String getName() { return roleName; } public void setName(String roleName) { this.roleName = roleName; } /** * Returns <code>true</code> if this role is <code>GUEST</code>, <code>false otherwise</code> * * @return <code>true</code> if this role is <code>GUEST</code>, <code>false otherwise</code> */ public boolean isGuest() { return (roleName.equals(GUEST_ROLE_STRING)) ? true : false; } /** * Returns <code>true</code> if this role is <code>USER</code>, <code>false otherwise</code> * * @return <code>true</code> if this role is <code>USER</code>, <code>false otherwise</code> */ public boolean isUser() { return (roleName.equals(USER_ROLE_STRING)) ? true : false; } /** * Returns <code>true</code> if this role is <code>ADMIN</code>, <code>false otherwise</code> * * @return <code>true</code> if this role is <code>ADMIN</code>, <code>false otherwise</code> */ public boolean isAdmin() { return (roleName.equals(ADMIN_ROLE_STRING)) ? true : false; } /** * Returns <code>true</code> if this role is <code>SUPER</code>, <code>false otherwise</code> * * @return <code>true</code> if this role is <code>SUPER</code>, <code>false otherwise</code> */ public boolean isSuper() { return (roleName.equals(SUPER_ROLE_STRING)) ? true : false; } public String toString() { return roleName; } public Object clone() throws CloneNotSupportedException { PortletRole r = (PortletRole) super.clone(); r.roleName = this.roleName; r.priority = this.priority; return r; } public int compare(Object left, Object right) { int leftID = ((PortletRole) left).getID(); int rightID = ((PortletRole) right).getID(); int result; if (leftID < rightID) { result = -1; } else if (leftID > rightID) { result = 1; } else { result = 0; } return result; } public boolean equals(Object object) { if (object != null && (object.getClass().equals(this.getClass()))) { PortletRole portletRole = (PortletRole) object; return (priority == portletRole.getID()); } return false; } public int hashCode() { return priority; } private Object readResolve() { PortletRole r = PortletRole.GUEST; switch (priority) { case GUEST_ROLE: r = PortletRole.GUEST; break; case USER_ROLE: r = PortletRole.USER; break; case ADMIN_ROLE: r = PortletRole.ADMIN; break; case SUPER_ROLE: r = PortletRole.SUPER; break; } return r; } }
package org.embulk.output.mailchimp; import com.fasterxml.jackson.core.Base64Variants; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.MissingNode; import com.google.common.base.Throwables; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.util.StringContentProvider; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.embulk.config.ConfigException; import org.embulk.spi.DataException; import org.embulk.spi.Exec; import org.embulk.util.retryhelper.jetty92.Jetty92ClientCreator; import org.embulk.util.retryhelper.jetty92.Jetty92RetryHelper; import org.embulk.util.retryhelper.jetty92.Jetty92SingleRequester; import org.embulk.util.retryhelper.jetty92.StringJetty92ResponseEntityReader; import org.slf4j.Logger; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class MailChimpHttpClient { private static final Logger LOG = Exec.getLogger(MailChimpHttpClient.class); private final ObjectMapper jsonMapper = new ObjectMapper() .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); /** * Instantiates a new Mailchimp http client. * * @param task the task */ public MailChimpHttpClient(MailChimpOutputPluginDelegate.PluginTask task) { } public JsonNode sendRequest(final String endpoint, final HttpMethod method, final MailChimpOutputPluginDelegate.PluginTask task) { return sendRequest(endpoint, method, "", task); } public JsonNode sendRequest(final String endpoint, final HttpMethod method, final String content, final MailChimpOutputPluginDelegate.PluginTask task) { try (final Jetty92RetryHelper retryHelper = createRetryHelper(task)) { final String authorizationHeader = getAuthorizationHeader(task); String responseBody = retryHelper.requestWithRetry( new StringJetty92ResponseEntityReader(task.getTimeoutMillis()), new Jetty92SingleRequester() { @Override public void requestOnce(HttpClient client, Response.Listener responseListener) { Request request = client .newRequest(endpoint) .timeout(task.getTimeoutMillis(), TimeUnit.MILLISECONDS) .accept("application/json") .method(method); if (method == HttpMethod.POST || method == HttpMethod.PUT) { request.content(new StringContentProvider(content), "application/json;utf-8"); } if (!authorizationHeader.isEmpty()) { request.header("Authorization", authorizationHeader); } request.send(responseListener); } @Override public boolean isResponseStatusToRetry(Response response) { int status = response.getStatus(); return status == 429 || status / 100 != 4; } @Override protected boolean isExceptionToRetry(Exception exception) { LOG.error("Exception to retry.", exception); // This check is to make sure the exception is retryable, e.g: server not found, internal server error... if (exception instanceof ConfigException || exception instanceof ExecutionException) { return toRetry((Exception) exception.getCause()); } return exception instanceof TimeoutException || super.isExceptionToRetry(exception); } }); return responseBody != null && !responseBody.isEmpty() ? parseJson(responseBody) : MissingNode.getInstance(); } catch (Exception ex) { LOG.error("Exception occurred while sending request.", ex); throw Throwables.propagate(ex); } } private JsonNode parseJson(final String json) throws DataException { try { return this.jsonMapper.readTree(json); } catch (IOException ex) { // Try to parse invalid json before throwing exception return parseInvalidJsonString(json); } } // Sometimes, the MailChimp API returns invalid JSON when we pushed a large of data. ObjectMapper can not read string json. // So we have to use this method to parse string and build a json string as ReportResponse private JsonNode parseInvalidJsonString(final String json) { int totalCreatedIndex = json.indexOf("\"total_created\""); int totalUpdatedIndex = json.indexOf("\"total_updated\""); int errorCountIndex = json.indexOf("\"error_count\""); int errorsIndex = json.indexOf("\"errors\""); StringBuilder validJson = new StringBuilder(); validJson.append("{").append(json.substring(errorsIndex, totalCreatedIndex - 1)).append(","); validJson.append(json.substring(totalCreatedIndex, totalCreatedIndex + "\"total_created\"".length() + 2)).append(","); validJson.append(json.substring(totalUpdatedIndex, totalUpdatedIndex + "\"total_updated\"".length() + 2)).append(","); validJson.append(json.substring(errorCountIndex, errorCountIndex + "\"error_count\"".length() + 2)).append("}"); try { return this.jsonMapper.readTree(validJson.toString()); } catch (IOException ex) { throw new DataException(ex); } } public void avoidFlushAPI(String reason) { try { LOG.info("{} in 5s...", reason); Thread.sleep(5000); } catch (InterruptedException e) { LOG.warn("Failed to sleep: {}", e.getMessage()); } } /** * MailChimp API v3 supports non expires access_token. Then no need refresh_token * * @param task * @return */ private String getAuthorizationHeader(final MailChimpOutputPluginDelegate.PluginTask task) { switch (task.getAuthMethod()) { case OAUTH: return "OAuth " + task.getAccessToken().orNull(); case API_KEY: return "Basic " + Base64Variants.MIME_NO_LINEFEEDS .encode(("apikey" + ":" + task.getApikey().orNull()).getBytes()); default: throw new ConfigException("Not supported method"); } } private Jetty92RetryHelper createRetryHelper(MailChimpOutputPluginDelegate.PluginTask task) { return new Jetty92RetryHelper( task.getMaximumRetries(), task.getInitialRetryIntervalMillis(), task.getMaximumRetryIntervalMillis(), new Jetty92ClientCreator() { @Override public HttpClient createAndStart() { HttpClient client = new HttpClient(new SslContextFactory()); try { client.start(); return client; } catch (Exception e) { throw Throwables.propagate(e); } } }); } }
package org.madlonkay.supertmxmerge.gui; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.util.List; import javax.swing.JFrame; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import org.madlonkay.supertmxmerge.DiffController; import org.madlonkay.supertmxmerge.DiffController.DiffInfo; import org.madlonkay.supertmxmerge.util.GuiUtil; import org.madlonkay.supertmxmerge.util.LocString; /** * * @author Aaron Madlon-Kay <aaron@madlon-kay.com> */ public class DiffWindow extends javax.swing.JPanel { public static JFrame newAsFrame(DiffController controller) { JFrame frame = new MenuFrame(LocString.get("STM_DIFF_WINDOW_TITLE")); frame.setContentPane(new DiffWindow(frame, controller)); frame.pack(); return frame; } private final Window window; private final ProgressWindow progress; /** * Creates new form DiffWindow * @param window * @param controller */ public DiffWindow(Window window, DiffController controller) { progress = new ProgressWindow(); this.window = window; window.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent evt) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GuiUtil.closeWindow(progress); } }); } }); this.controller = controller; initComponents(); if (window instanceof MenuFrame) { buttonPanel.setVisible(false); ((MenuFrame) window).addFileMenuItem(saveAsMenuItem); } // Keep tooltips open. Via: ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); initContent(); } private void initContent() { List<DiffInfo> infos = controller.getDiffInfos(); progress.setMaximum(infos.size()); int n = 1; for (DiffInfo info : infos) { progress.setValue(n); progress.setMessage(LocString.getFormat("STM_DIFF_PROGRESS", n, infos.size())); diffsPanel.add(new DiffCell(n, info, jScrollPane1)); n++; } // Beansbinding is broken now for some reason, so set this manually. file1Label.setText(controller.getTmx1().getName()); file2Label.setText(controller.getTmx2().getName()); file1TextUnits.setText((String) unitCountConverter.convertForward(controller.getTmx1().getSize())); file2TextUnits.setText((String) unitCountConverter.convertForward(controller.getTmx2().getSize())); file1Label.setToolTipText((String) mapToTextConverter.convertForward(controller.getTmx1().getMetadata())); file2Label.setToolTipText((String) mapToTextConverter.convertForward(controller.getTmx2().getMetadata())); saveAsButton.setEnabled(controller.canSaveDiff()); } private DiffController getController() { return controller; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); controller = getController(); unitCountConverter = new LocStringConverter("STM_NUMBER_OF_UNITS", "STM_NUMBER_OF_UNITS_SINGULAR"); changeCountConverter = new LocStringConverter("STM_NUMBER_OF_CHANGES", "STM_NUMBER_OF_CHANGES_SINGULAR"); mapToTextConverter = new org.madlonkay.supertmxmerge.gui.MapToTextConverter(); saveAsMenuItem = new javax.swing.JMenuItem(); jPanel3 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); file1Label = new javax.swing.JLabel(); file2Label = new javax.swing.JLabel(); file1TextUnits = new javax.swing.JLabel(); file2TextUnits = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); changeCountLabel = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); diffsPanel = new org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel(); buttonPanel = new javax.swing.JPanel(); saveAsButton = new javax.swing.JButton(); saveAsMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAsMenuItem.setMnemonic('a'); saveAsMenuItem.setText(LocString.get("STM_FILE_MENU_SAVEAS")); // NOI18N saveAsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsActionPerformed(evt); } }); setLayout(new java.awt.BorderLayout()); jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.PAGE_AXIS)); jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4)); jPanel2.setLayout(new java.awt.GridLayout(2, 2, 10, 0)); file1Label.setFont(file1Label.getFont().deriveFont(file1Label.getFont().getStyle() | java.awt.Font.BOLD, file1Label.getFont().getSize()+2)); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.name}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1Name"); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.metadata}"), file1Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "file1Metadata"); binding.setSourceNullValue(LocString.get("STM_TMX_DETAILS_UNAVAILABLE")); // NOI18N binding.setConverter(mapToTextConverter); bindingGroup.addBinding(binding); jPanel2.add(file1Label); file2Label.setFont(file2Label.getFont().deriveFont(file2Label.getFont().getStyle() | java.awt.Font.BOLD, file2Label.getFont().getSize()+2)); file2Label.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.name}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2Name"); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.metadata}"), file2Label, org.jdesktop.beansbinding.BeanProperty.create("toolTipText"), "tmx2Metadata"); binding.setSourceNullValue(LocString.get("STM_TMX_DETAILS_UNAVAILABLE")); // NOI18N binding.setConverter(mapToTextConverter); bindingGroup.addBinding(binding); jPanel2.add(file2Label); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx1.size}"), file1TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file1UnitCount"); binding.setConverter(unitCountConverter); bindingGroup.addBinding(binding); jPanel2.add(file1TextUnits); file2TextUnits.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${tmx2.size}"), file2TextUnits, org.jdesktop.beansbinding.BeanProperty.create("text"), "file2UnitCount"); binding.setConverter(unitCountConverter); bindingGroup.addBinding(binding); jPanel2.add(file2TextUnits); jPanel3.add(jPanel2); jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, controller, org.jdesktop.beansbinding.ELProperty.create("${changeCount}"), changeCountLabel, org.jdesktop.beansbinding.BeanProperty.create("text"), "changeCount"); binding.setConverter(changeCountConverter); bindingGroup.addBinding(binding); jPanel4.add(changeCountLabel); jPanel3.add(jPanel4); add(jPanel3, java.awt.BorderLayout.NORTH); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); diffsPanel.setLayout(new javax.swing.BoxLayout(diffsPanel, javax.swing.BoxLayout.PAGE_AXIS)); jScrollPane1.setViewportView(diffsPanel); add(jScrollPane1, java.awt.BorderLayout.CENTER); buttonPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4)); buttonPanel.setLayout(new java.awt.BorderLayout()); saveAsButton.setText(LocString.get("STM_SAVE_AS_BUTTON")); // NOI18N binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_ONCE, controller, org.jdesktop.beansbinding.ELProperty.create("${canSaveDiff}"), saveAsButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"), "canSaveDiff"); bindingGroup.addBinding(binding); saveAsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsActionPerformed(evt); } }); buttonPanel.add(saveAsButton, java.awt.BorderLayout.EAST); add(buttonPanel, java.awt.BorderLayout.SOUTH); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents private void saveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsActionPerformed getController().saveAs(); }//GEN-LAST:event_saveAsActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private org.madlonkay.supertmxmerge.gui.LocStringConverter changeCountConverter; private javax.swing.JLabel changeCountLabel; private org.madlonkay.supertmxmerge.DiffController controller; private org.madlonkay.supertmxmerge.gui.ReasonablySizedPanel diffsPanel; private javax.swing.JLabel file1Label; private javax.swing.JLabel file1TextUnits; private javax.swing.JLabel file2Label; private javax.swing.JLabel file2TextUnits; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private org.madlonkay.supertmxmerge.gui.MapToTextConverter mapToTextConverter; private javax.swing.JButton saveAsButton; private javax.swing.JMenuItem saveAsMenuItem; private org.madlonkay.supertmxmerge.gui.LocStringConverter unitCountConverter; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
package org.fiteagle.north.sfa.allocate; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.fiteagle.api.core.IGeni; import org.fiteagle.api.core.IMessageBus; import org.fiteagle.api.core.MessageBusOntologyModel; import org.fiteagle.api.core.MessageUtil; import org.fiteagle.north.sfa.am.ISFA_AM; import org.fiteagle.north.sfa.am.dm.SFA_AM_MDBSender; import org.fiteagle.north.sfa.util.URN; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDF; public class ProcessAllocate { private final static Logger LOGGER = Logger.getLogger(ProcessAllocate.class.getName()); public static void parseAllocateParameter(final List<?> parameter, final Map<String, Object> allocateParameters) { ProcessAllocate.LOGGER.log(Level.INFO, "parsing allocate parameter"); System.out.println(parameter); System.out.println(parameter.size()); for (final Object param : parameter) { if (param instanceof String) { String allocateParameter = (String) param; if (allocateParameter.startsWith(ISFA_AM.URN)) { allocateParameters.put(ISFA_AM.URN, allocateParameter); ProcessAllocate.LOGGER.log(Level.INFO, allocateParameters.get(ISFA_AM.URN).toString()); } else if (allocateParameter.contains(ISFA_AM.REQUEST)) { allocateParameters.put(ISFA_AM.REQUEST, allocateParameter); ProcessAllocate.LOGGER.log(Level.INFO, allocateParameters.get(ISFA_AM.REQUEST).toString()); final List<String> requiredResources = new LinkedList<>(); parseRSpec(allocateParameter, ISFA_AM.componentManagerId, requiredResources); allocateParameters.put(ISFA_AM.RequiredResources, requiredResources); } } if (param instanceof Map<?, ?>) { @SuppressWarnings("unchecked") final Map<String, ?> param2 = (Map<String, ?>) param; if (!param2.isEmpty()) { for (Map.Entry<String, ?> parameters : param2.entrySet()) { if (parameters.getKey().toString().equals(IGeni.GENI_END_TIME)) { allocateParameters.put(ISFA_AM.EndTime, parameters.getValue().toString()); ProcessAllocate.LOGGER.log(Level.INFO, allocateParameters.get(ISFA_AM.EndTime).toString()); } } } } } /* * for (final Object param : parameter) { if (param instanceof String) { // considered to be slice_urn String param2 * = (String) param; this.delegate.setSliceURN(param2); } else if (param instanceof Map<?, ?>) { // considered to be * options parameters. this.parseOptionsParameters(param); } else if(param instanceof List<?>){ // considered to be * credentials parameters. this.parseCredentialsParameters(param); } } */ } @SuppressWarnings("unchecked") public static void reserveInstances(final Map<String, Object> allocateParameter, Map<String, String> sliverMap) { Model requestModel = ModelFactory.createDefaultModel(); Resource slice = requestModel.createResource(allocateParameter.get(ISFA_AM.URN).toString()); slice.addProperty(RDF.type, MessageBusOntologyModel.classGroup); if(allocateParameter.containsKey(ISFA_AM.EndTime)){ slice.addProperty(MessageBusOntologyModel.endTime, allocateParameter.get(ISFA_AM.EndTime).toString()); } int counter = 1; for (final Object requiredReserouces : (List<String>) allocateParameter.get(ISFA_AM.RequiredResources)){ Resource sliver = requestModel.createResource(setSliverURN(allocateParameter.get(ISFA_AM.URN).toString(), counter)); sliver.addProperty(RDF.type, MessageBusOntologyModel.classReservation); sliver.addProperty(MessageBusOntologyModel.partOfGroup, slice.getURI()); sliver.addProperty(MessageBusOntologyModel.reserveInstanceFrom, requiredReserouces.toString()); sliver.addProperty(MessageBusOntologyModel.hasState,IGeni.GENI_ALLOCATED); counter = counter + 1; } String serializedModel = MessageUtil.serializeModel(requestModel, IMessageBus.SERIALIZATION_TURTLE); LOGGER.log(Level.INFO, "send reservation request ..."); Model resultModel = SFA_AM_MDBSender.getInstance().sendRDFRequest(serializedModel, IMessageBus.TYPE_CREATE, IMessageBus.TARGET_RESERVATION); LOGGER.log(Level.INFO, "reservation reply received."); StmtIterator iter = resultModel.listStatements(); while (iter.hasNext()) { Statement st = iter.next(); Resource r = st.getSubject(); sliverMap.put(r.getURI().toString(), st.getObject().toString()); LOGGER.log(Level.INFO, "created sliver " + r.getURI()); } } private static void parseRSpec(String request, String requiredAttribute, List<String> requiredResources) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(request)); Document doc = db.parse(is); NodeList nodes = doc.getElementsByTagName(ISFA_AM.node); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); requiredResources.add(element.getAttribute(requiredAttribute)); System.out.println("parsed element component manager id " + element.getAttribute(requiredAttribute)); } } catch (ParserConfigurationException | SAXException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void addAllocateValue(final HashMap<String, Object> result, final Map<String,String> slivers, final Map<String, Object> allocateParameters) { final Map<String, Object> value = new HashMap<>(); value.put(IGeni.GENI_RSPEC, "should be the geni.rspec manifest"); // to be continued final List<Map<String, Object>> geniSlivers = new LinkedList<>(); /** * defines a loop depending on the slivers number. * In the loop, Map is created for each sliver containing * sliver urn, experires and status. * The created maps should be added to geni_slivers list. */ for (Map.Entry<String, String> sliver : slivers.entrySet()) { LOGGER.log(Level.INFO, "sliver in the list " + sliver.getKey()); final Map<String, Object> sliverMap = new HashMap<>(); sliverMap.put(IGeni.GENI_SLIVER_URN, sliver.getKey()); LOGGER.log(Level.INFO, "sliver in the map is " + sliverMap.get(IGeni.GENI_SLIVER_URN)); if(allocateParameters.containsKey(ISFA_AM.EndTime)){ sliverMap.put(IGeni.GENI_EXPIRES, allocateParameters.get(ISFA_AM.EndTime)); LOGGER.log(Level.INFO, "end time is " + sliverMap.get(IGeni.GENI_EXPIRES)); } else { sliverMap.put(IGeni.GENI_EXPIRES, ""); } sliverMap.put(IGeni.GENI_ALLOCATION_STATUS, sliver.getValue()); LOGGER.log(Level.INFO, "geni allocation status is " + sliverMap.get(IGeni.GENI_ALLOCATION_STATUS)); geniSlivers.add(sliverMap); } value.put(IGeni.GENI_SLIVERS, geniSlivers); result.put(ISFA_AM.VALUE, value); } private static String setSliverURN(String SliceURN, int i){ String sliverURN = ""; URN urn = new URN(SliceURN); urn.setType(ISFA_AM.Sliver); urn.setSubject(Integer.toString(i)); sliverURN = urn.toString(); return sliverURN; } }
package org.owasp.esapi.reference; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.util.Arrays; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.ESAPI; import org.owasp.esapi.ValidationErrorList; import org.owasp.esapi.errors.EncodingException; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationAvailabilityException; import org.owasp.esapi.errors.ValidationException; import org.owasp.validator.html.AntiSamy; import org.owasp.validator.html.CleanResults; import org.owasp.validator.html.Policy; import org.owasp.validator.html.PolicyException; import org.owasp.validator.html.ScanException; public class DefaultValidator implements org.owasp.esapi.Validator { /** OWASP AntiSamy markup verification policy */ private Policy antiSamyPolicy = null; /** constants */ private static final int MAX_CREDIT_CARD_LENGTH = 19; private static final int MAX_PARAMETER_NAME_LENGTH = 100; private static final int MAX_PARAMETER_VALUE_LENGTH = 65535; public DefaultValidator() { } public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException { try { getValidInput( context, input, type, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { try { context = ESAPI.encoder().canonicalize( context ); String canonical = ESAPI.encoder().canonicalize( input ); if ( type == null || type.length() == 0 ) { throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input ); } if (isEmpty(canonical)) { if (allowNull) return null; throw new ValidationException( context + ": Input required.", "Input required: context=" + context + ", type=" + type + "), input=" + input, context ); } if (canonical.length() > maxLength) { throw new ValidationException( context + ": Invalid input. The maximum length of " + maxLength + " characters was exceeded.", "Input exceeds maximum allowed length of " + maxLength + " by " + (canonical.length()-maxLength) + " characters: context=" + context + ", type=" + type + "), input=" + input, context ); } Pattern p = ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getValidationPattern( type ); if ( p == null ) { try { p = Pattern.compile( type ); } catch( PatternSyntaxException e ) { throw new RuntimeException( "Validation misconfiguration, specified type to validate against was null: context=" + context + ", type=" + type + "), input=" + input ); } } if ( !p.matcher(canonical).matches() ) { throw new ValidationException( context + ": Invalid input. Please conform to: " + p.pattern() + " with a maximum length of " + maxLength, "Invalid input: context=" + context + ", type=" + type + "( " + p.pattern() + "), input=" + input, context ); } return canonical; } catch (EncodingException e) { throw new ValidationException( context + ": Invalid input. An encoding error occurred.", "Error canonicalizing user input", e, context); } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInput(context, input, type, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid date according to the specified date format. */ public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException { try { getValidDate( context, input, format, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} * * Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException, * and input that is clearly an attack will generate a descriptive IntrusionException. * * */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input date required", "Input date required: context=" + context + ", input=" + input, context ); } Date date = format.parse(input); return date; } catch (Exception e) { throw new ValidationException( context + ": Invalid date must follow " + format + " format", "Invalid date: context=" + context + ", format=" + format + ", input=" + input, e, context); } } /** * {@inheritDoc} * * Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException, * and input that is clearly an attack will generate a descriptive IntrusionException. * * */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDate(context, input, format, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return null; } /** * {@inheritDoc} * * Returns true if input is "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas * on how to do HTML validation in a whitelist way, as this is an extremely difficult problem. * * */ public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { if ( antiSamyPolicy == null ) { if (ESAPI.securityConfiguration().getResourceDirectory() == null) { //load via classpath ClassLoader loader = getClass().getClassLoader(); InputStream in = null; try { in = loader.getResourceAsStream("antisamy-esapi.xml"); if (in != null) { antiSamyPolicy = Policy.getInstance(in); } } catch (Exception e) { antiSamyPolicy = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (antiSamyPolicy == null) { throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource"); } } else { //load via fileio antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml"); } } AntiSamy as = new AntiSamy(); CleanResults test = as.scan(input, antiSamyPolicy); return(test.getErrorMessages().size() == 0); } catch (Exception e) { return false; } } /** * {@inheritDoc} * * Returns canonicalized and validated "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas * on how to do HTML validation in a whitelist way, as this is an extremely difficult problem. * * */ public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input HTML required", "Input HTML required: context=" + context + ", input=" + input, context ); } if (input.length() > maxLength) { throw new ValidationException( context + ": Invalid HTML. You enterted " + input.length() + " characters. Input can not exceed " + maxLength + " characters.", context + " input exceedes maxLength by " + (input.length()-maxLength) + " characters", context); } try { if ( antiSamyPolicy == null ) { if (ESAPI.securityConfiguration().getResourceDirectory() == null) { //load via classpath ClassLoader loader = getClass().getClassLoader(); InputStream in = null; try { in = loader.getResourceAsStream("antisamy-esapi.xml"); if (in != null) { antiSamyPolicy = Policy.getInstance(in); } } catch (Exception e) { antiSamyPolicy = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (antiSamyPolicy == null) { throw new IllegalArgumentException ("Can't load antisamy-esapi.xml as a classloader resource"); } } else { //load via fileio antiSamyPolicy = Policy.getInstance( ESAPI.securityConfiguration().getResourceDirectory() + "antisamy-esapi.xml"); } } AntiSamy as = new AntiSamy(); CleanResults test = as.scan(input, antiSamyPolicy); List errors = test.getErrorMessages(); if ( errors.size() > 0 ) { // just create new exception to get it logged and intrusion detected new ValidationException( "Invalid HTML input: context=" + context, "Invalid HTML input: context=" + context + ", errors=" + errors, context ); } return(test.getCleanHTML().trim()); } catch (ScanException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input: context=" + context + " error=" + e.getMessage(), e, context ); } catch (PolicyException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input does not follow rules in antisamy-esapi.xml: context=" + context + " error=" + e.getMessage(), e, context ); } } /** * ValidationErrorList variant of getValidSafeHTML */ public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidSafeHTML(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * {@inheritDoc} * * Returns true if input is a valid credit card. Maxlength is mandated by valid credit card type. * * */ public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException { try { getValidCreditCard( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated credit card number as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input credit card required", "Input credit card required: context=" + context + ", input=" + input, context ); } String canonical = getValidInput( context, input, "CreditCard", MAX_CREDIT_CARD_LENGTH, allowNull); // perform Luhn algorithm checking StringBuffer digitsOnly = new StringBuffer(); char c; for (int i = 0; i < canonical.length(); i++) { c = canonical.charAt(i); if (Character.isDigit(c)) { digitsOnly.append(c); } } int sum = 0; int digit = 0; int addend = 0; boolean timesTwo = false; for (int i = digitsOnly.length() - 1; i >= 0; i digit = Integer.parseInt(digitsOnly.substring(i, i + 1)); if (timesTwo) { addend = digit * 2; if (addend > 9) { addend -= 9; } } else { addend = digit; } sum += addend; timesTwo = !timesTwo; } int modulus = sum % 10; if (modulus != 0) throw new ValidationException( context + ": Invalid credit card input", "Invalid credit card input: context=" + context, context ); return canonical; } /** * ValidationErrorList variant of getValidCreditCard */ public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidCreditCard(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if the directory path (not including a filename) is valid. * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidDirectoryPath(String context, String input, boolean allowNull) throws IntrusionException { try { getValidDirectoryPath( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated directory path as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidDirectoryPath(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context ); } // do basic validation String canonical = getValidInput( context, input, "DirectoryName", 255, false); // get the canonical path without the drive letter if present String cpath = new File(canonical).getCanonicalPath().replaceAll( "\\\\", "/"); String temp = cpath.toLowerCase(); if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') { cpath = cpath.substring(2); } // prepare the input without the drive letter if present String escaped = canonical.replaceAll( "\\\\", "/"); temp = escaped.toLowerCase(); if (temp.length() >= 2 && temp.charAt(0) >= 'a' && temp.charAt(0) <= 'z' && temp.charAt(1) == ':') { escaped = escaped.substring(2); } // the path is valid if the input matches the canonical path if (!escaped.equals(cpath.toLowerCase())) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } return canonical; } catch (IOException e) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not exist: context=" + context + ", input=" + input, e, context ); } } /** * ValidationErrorList variant of getValidDirectoryPath */ public String getValidDirectoryPath(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDirectoryPath(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid file name. */ public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException { try { getValidFileName( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a canonicalized and validated file name as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidFileName(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { String canonical = ""; // detect path manipulation try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context ); } // do basic validation canonical = ESAPI.encoder().canonicalize(input); getValidInput( context, input, "FileName", 255, true ); File f = new File(canonical); String c = f.getCanonicalPath(); String cpath = c.substring(c.lastIndexOf(File.separator) + 1); // the path is valid if the input matches the canonical path if (!input.equals(cpath.toLowerCase())) { throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } } catch (IOException e) { throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context ); } catch (EncodingException ee) { throw new IntrusionException( context + ": Invalid file name", "Invalid file name: context=" + context + ", canonical=" + canonical, ee ); } // verify extensions List extensions = ESAPI.securityConfiguration().getAllowedFileExtensions(); Iterator i = extensions.iterator(); while (i.hasNext()) { String ext = (String) i.next(); if (input.toLowerCase().endsWith(ext.toLowerCase())) { return canonical; } } throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+")", "Invalid file name does not have valid extension ( "+ESAPI.securityConfiguration().getAllowedFileExtensions()+"): context=" + context+", input=" + input, context ); } /** * Returns a canonicalized and validated file name as a String. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidFileName(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileName(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * {@inheritDoc} * * Returns true if input is a valid number. * * */ public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException { try { getValidNumber(context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException { Double minDoubleValue = new Double(minValue); Double maxDoubleValue = new Double(maxValue); return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull); } public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidNumber(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Double(0); } /** * {@inheritDoc} * * Returns true if input is a valid number. * * */ public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException { return isValidDouble( context, input, minValue, maxValue, allowNull ); } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException { if (minValue > maxValue) { //should this be a RunTime? throw new ValidationException( context + ": Invalid double input: context", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context ); } if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required: context", "Input required: context=" + context + ", input=" + input, context ); } try { Double d = new Double(Double.parseDouble(input)); if (d.isInfinite()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context ); if (d.isNaN()) throw new ValidationException( "Invalid double input: context=" + context, "Invalid double input is infinite: context=" + context + ", input=" + input, context ); if (d.doubleValue() < minValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); if (d.doubleValue() > maxValue) throw new ValidationException( "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context, "Invalid double input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); return d; } catch (NumberFormatException e) { throw new ValidationException( context + ": Invalid double input", "Invalid double input format: context=" + context + ", input=" + input, e, context); } } public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDouble(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Double(0); } /** * {@inheritDoc} * * Returns true if input is a valid number. * * */ public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException { try { getValidInteger( context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns a validated number as a double. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException { if (minValue > maxValue) { //should this be a RunTime? throw new ValidationException( context + ": Invalid Integer", "Validation parameter error for double: maxValue ( " + maxValue + ") must be greater than minValue ( " + minValue + ") for " + context, context ); } if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } try { int i = Integer.parseInt(input); if (i < minValue || i > maxValue ) throw new ValidationException( context + ": Invalid Integer. Value must be between " + minValue + " and " + maxValue, "Invalid int input must be between " + minValue + " and " + maxValue + ": context=" + context + ", input=" + input, context ); return new Integer(i); } catch (NumberFormatException e) { throw new ValidationException( context + ": Invalid integer input", "Invalid int input: context=" + context + ", input=" + input, e, context ); } } public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInteger(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return new Integer(0); } /** * Returns true if input is valid file content. */ public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException { try { getValidFileContent( context, input, maxBytes, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns validated file content as a byte array. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize(); if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context ); if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context ); return input; } public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileContent(context, input, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } //not sure what to return on error return input; } /** * Returns true if a file upload has a valid name, path, and content. * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> * */ public boolean isValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException { return( isValidFileName( context, filename, allowNull ) && isValidDirectoryPath( context, directorypath, allowNull ) && isValidFileContent( context, content, maxBytes, allowNull ) ); } /** * Validates the filepath, filename, and content of a file. Invalid input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public void assertValidFileUpload(String context, String directorypath, String filename, byte[] content, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { getValidFileName( context, filename, allowNull ); getValidDirectoryPath( context, directorypath, allowNull ); getValidFileContent( context, content, maxBytes, allowNull ); } /** * ValidationErrorList variant of assertValidFileUpload */ public void assertValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { assertValidFileUpload(context, filepath, filename, content, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest saved in EASPI Authenticator */ public boolean isValidHTTPRequest() throws IntrusionException { try { assertIsValidHTTPRequest(); return true; } catch( Exception e ) { return false; } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public boolean isValidHTTPRequest(HttpServletRequest request) throws IntrusionException { try { assertIsValidHTTPRequest(request); return true; } catch( Exception e ) { return false; } } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest saved in EASPI Authenticator * */ public void assertIsValidHTTPRequest() throws ValidationException, IntrusionException { HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest(); assertIsValidHTTPRequest(request); } /** * Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed * characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ private void assertIsValidHTTPRequest(HttpServletRequest request) throws ValidationException, IntrusionException { if (request == null) { throw new ValidationException( "Input required: HTTP request is null", "Input required: HTTP request is null" ); } if ( !request.getMethod().equals( "GET") && !request.getMethod().equals("POST") ) { throw new IntrusionException( "Bad HTTP method received", "Bad HTTP method received: " + request.getMethod() ); } Iterator i1 = request.getParameterMap().entrySet().iterator(); while (i1.hasNext()) { Map.Entry entry = (Map.Entry) i1.next(); String name = (String) entry.getKey(); getValidInput( "HTTP request parameter: " + name, name, "HTTPParameterName", MAX_PARAMETER_NAME_LENGTH, false ); String[] values = (String[]) entry.getValue(); Iterator i3 = Arrays.asList(values).iterator(); while (i3.hasNext()) { String value = (String) i3.next(); getValidInput( "HTTP request parameter: " + name, value, "HTTPParameterValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } if (request.getCookies() != null) { Iterator i2 = Arrays.asList(request.getCookies()).iterator(); while (i2.hasNext()) { Cookie cookie = (Cookie) i2.next(); String name = cookie.getName(); getValidInput( "HTTP request cookie: " + name, name, "HTTPCookieName", MAX_PARAMETER_NAME_LENGTH, true ); String value = cookie.getValue(); getValidInput( "HTTP request cookie: " + name, value, "HTTPCookieValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name != null && !name.equalsIgnoreCase( "Cookie")) { getValidInput( "HTTP request header: " + name, name, "HTTPHeaderName", MAX_PARAMETER_NAME_LENGTH, true ); Enumeration e2 = request.getHeaders(name); while (e2.hasMoreElements()) { String value = (String) e2.nextElement(); getValidInput( "HTTP request header: " + name, value, "HTTPHeaderValue", MAX_PARAMETER_VALUE_LENGTH, true ); } } } } /** * {@inheritDoc} * * Returns true if input is a valid list item. * * */ public boolean isValidListItem(String context, String input, List list) { try { getValidListItem( context, input, list); return true; } catch( Exception e ) { return false; } } /** * Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidListItem(String context, String input, List list) throws ValidationException, IntrusionException { if (list.contains(input)) return input; throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context ); } /** * ValidationErrorList variant of getValidListItem */ public String getValidListItem(String context, String input, List list, ValidationErrorList errors) throws IntrusionException { try { return getValidListItem(context, input, list); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * {@inheritDoc} * * Returns true if the parameters in the current request contain all required parameters and only optional ones in addition. * * */ public boolean isValidHTTPRequestParameterSet(String context, Set requiredNames, Set optionalNames) { try { assertIsValidHTTPRequestParameterSet( context, requiredNames, optionalNames); return true; } catch( Exception e ) { return false; } } /** * Validates that the parameters in the current request contain all required parameters and only optional ones in * addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional) throws ValidationException, IntrusionException { HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest(); Set actualNames = request.getParameterMap().keySet(); // verify ALL required parameters are present Set missing = new HashSet(required); missing.removeAll(actualNames); if (missing.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context ); } // verify ONLY optional + required parameters are present Set extra = new HashSet(actualNames); extra.removeAll(required); extra.removeAll(optional); if (extra.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context ); } } /** * ValidationErrorList variant of assertIsValidHTTPRequestParameterSet */ public void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional, ValidationErrorList errors) throws IntrusionException { try { assertIsValidHTTPRequestParameterSet(context, required, optional); } catch (ValidationException e) { errors.addError(context, e); } } public boolean isValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public byte[] getValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context ); } if (input.length > maxLength) { throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + input, context); } for (int i = 0; i < input.length; i++) { if (input[i] < 33 || input[i] > 126) { throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + input, context); } } return input; } /** * ValidationErrorList variant of getValidPrintable */ public byte[] getValidPrintable(String context, byte[] input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * {@inheritDoc} * * Returns true if input is valid printable ASCII characters (32-126). * * */ public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { String canonical = ""; try { canonical = ESAPI.encoder().canonicalize(input); return new String( getValidPrintable( context, canonical.getBytes(), maxLength, allowNull) ); } catch (EncodingException e) { throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context); } } /** * ValidationErrorList variant of getValidPrintable */ public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * Returns true if input is a valid redirect location. */ public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException { return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull); } /** * Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull); } /** * ValidationErrorList variant of getValidRedirectLocation */ public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidRedirectLocation(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return input; } /** * {@inheritDoc} * * This implementation reads until a newline or the specified number of * characters. */ public String safeReadLine(InputStream in, int max) throws ValidationException { if (max <= 0) throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream"); StringBuffer sb = new StringBuffer(); int count = 0; int c; try { while (true) { c = in.read(); if ( c == -1 ) { if (sb.length() == 0) return null; break; } if (c == '\n' || c == '\r') break; count++; if (count > max) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")"); } sb.append((char) c); } return sb.toString(); } catch (IOException e) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e); } } /** * Helper function to check if a String is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(String input) { return (input==null || input.trim().length() == 0); } /** * Helper function to check if a byte array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(byte[] input) { return (input==null || input.length == 0); } }
package org.fxmisc.wellbehaved.input; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; import javafx.beans.property.ObjectProperty; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; /** * Methods of this class could be added directly to the {@link EventHandler} * interface. The interface could further be extended with default methods * <pre> * {@code * EventHandler<? super T> orElse(EventHandler<? super T> other); * EventHandler<? super T> without(EventHandler<?> other); * } * </pre> * The latter may replace the {@link #exclude(EventHandler, EventHandler)} * static method. * @param <T> */ public final class EventHandlerHelper<T extends Event> { public static abstract class Builder<T extends Event> { private static <T extends Event> Builder<T> empty() { return new Builder<T>() { @Override <U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity) { return new ArrayList<>(additionalCapacity); } }; } // private constructor to prevent subclassing by the user private Builder() {} public <U extends T> On<T, U> on(EventPattern<? super T, ? extends U> eventMatcher) { return new On<>(this, eventMatcher); } public <U extends T> On<T, U> on(EventType<? extends U> eventType) { return on(EventPattern.eventTypePattern(eventType)); } public <U extends T> Builder<U> addHandler(EventHandler<? super U> handler) { return new CompositeBuilder<>(this, handler); } public final EventHandler<T> create() { List<EventHandler<? super T>> handlers = getHandlers(); return new CompositeEventHandler<>(handlers); } List<EventHandler<? super T>> getHandlers() { return getHandlers(0); } abstract <U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity); } private static class CompositeBuilder<T extends Event> extends Builder<T> { private final Builder<? super T> previousBuilder; private final EventHandler<? super T> handler; private CompositeBuilder( Builder<? super T> previousBuilder, EventHandler<? super T> handler) { this.previousBuilder = previousBuilder; this.handler = handler; } @Override <U extends T> List<EventHandler<? super U>> getHandlers(int additionalCapacity) { List<EventHandler<? super U>> handlers = previousBuilder.getHandlers(additionalCapacity + 1); handlers.add(handler); return handlers; } } public static class On<T extends Event, U extends T> { private final Builder<? super T> previousBuilder; private final EventPattern<? super T, ? extends U> eventMatcher; private On( Builder<? super T> previous, EventPattern<? super T, ? extends U> eventMatcher) { this.previousBuilder = previous; this.eventMatcher = eventMatcher; } public On<T, U> where(Predicate<? super U> condition) { return new On<>(previousBuilder, eventMatcher.and(condition)); } public Builder<T> act(Consumer<? super U> action) { return previousBuilder.addHandler(t -> { eventMatcher.match(t).ifPresent(u -> { action.accept(u); t.consume(); }); }); } } public static <T extends Event, U extends T> On<T, U> on( EventPattern<? super T, ? extends U> eventMatcher) { return Builder.<T>empty().on(eventMatcher); } public static <T extends Event> On<Event, T> on( EventType<? extends T> eventType) { return Builder.empty().on(eventType); } public static <T extends Event> Builder<T> startWith(EventHandler<? super T> handler) { return Builder.empty().addHandler(handler); } static <T extends Event> EventHandler<T> empty() { return EmptyEventHandler.instance(); } @SafeVarargs public static <T extends Event> EventHandler<? super T> chain(EventHandler<? super T>... handlers) { ArrayList<EventHandler<? super T>> nonEmptyHandlers = new ArrayList<>(handlers.length); for(EventHandler<? super T> handler: handlers) { if(handler != empty()) { nonEmptyHandlers.add(handler); } } if(nonEmptyHandlers.isEmpty()) { return empty(); } else if(nonEmptyHandlers.size() == 1) { return nonEmptyHandlers.get(0); } else { nonEmptyHandlers.trimToSize(); return new CompositeEventHandler<>(nonEmptyHandlers); } } public static <T extends Event> EventHandler<? super T> exclude(EventHandler<T> handler, EventHandler<?> subHandler) { if(handler instanceof CompositeEventHandler) { return ((CompositeEventHandler<T>) handler).without(subHandler); } else if(handler.equals(subHandler)) { return empty(); } else { return handler; } } public static <T extends Event> void install( ObjectProperty<EventHandler<? super T>> property, EventHandler<? super T> handler) { EventHandler<? super T> oldHandler = property.get(); property.set(EventHandlerHelper.chain(handler, oldHandler)); } public static <T extends Event> void remove( ObjectProperty<EventHandler<? super T>> property, EventHandler<? super T> handler) { EventHandler<? super T> oldHandler = property.get(); property.set(EventHandlerHelper.exclude(oldHandler, handler)); } // prevent instantiation private EventHandlerHelper() {} } final class EmptyEventHandler<T extends Event> implements EventHandler<T> { private static EmptyEventHandler<?> INSTANCE = new EmptyEventHandler<>(); @SuppressWarnings("unchecked") static <T extends Event> EmptyEventHandler<T> instance() { return (EmptyEventHandler<T>) INSTANCE; } private EmptyEventHandler() {} @Override public void handle(T event) { // do nothing } } class CompositeEventHandler<T extends Event> implements EventHandler<T> { private final List<EventHandler<? super T>> handlers; CompositeEventHandler(List<EventHandler<? super T>> handlers) { this.handlers = handlers; } @Override public void handle(T event) { for(EventHandler<? super T> handler: handlers) { handler.handle(event); if(event.isConsumed()) { break; } } } public EventHandler<? super T> without(EventHandler<?> other) { if(this.equals(other)) { return EmptyEventHandler.instance(); } else { boolean changed = false; List<EventHandler<? super T>> newHandlers = new ArrayList<>(handlers.size()); for(EventHandler<? super T> handler: handlers) { EventHandler<? super T> h = EventHandlerHelper.exclude(handler, other); if(h != handler) { changed = true; } if(h != EmptyEventHandler.instance()) { newHandlers.add(h); } } if(!changed) { return this; } else if(newHandlers.isEmpty()) { return EmptyEventHandler.instance(); } else if(newHandlers.size() == 1) { return newHandlers.get(0); } else { return new CompositeEventHandler<>(newHandlers); } } } }
package info.guardianproject.otr.app.im.app; import info.guardianproject.iocipher.File; import info.guardianproject.iocipher.FileInputStream; import info.guardianproject.iocipher.FileOutputStream; import info.guardianproject.iocipher.VirtualFileSystem; import java.io.FileNotFoundException; import java.io.IOException; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.util.Log; public class IocVfs { public static final String TAG = IocVfs.class.getName(); private static String dbFile; private static VirtualFileSystem vfs; private static final String BLOB_NAME = "media.db"; private static String password; //maybe called multiple times to remount public static void init(Context context) throws IllegalArgumentException { if (dbFile == null && context.getExternalFilesDir(null) != null) dbFile = new File(context.getExternalFilesDir(null),BLOB_NAME).getAbsolutePath(); else dbFile = new File(context.getFilesDir(),BLOB_NAME).getAbsolutePath(); if (vfs == null) vfs = new VirtualFileSystem(dbFile); if (password != null) mount(); } public static void mount() throws IllegalArgumentException { // Log.e(TAG, "mount:" + dbFile); vfs.mount(password); } public static void unmount() { // Log.e(TAG, "unmount:" + dbFile); vfs.unmount(); } public static void list(String parent) { File file = new File(parent); String[] list = file.list(); // Log.e(TAG, file.getAbsolutePath()); for (int i = 0 ; i < list.length ; i++) { String fullname = parent + list[i]; File child = new File(fullname); if (child.isDirectory()) { list(fullname+"/"); } else { File full = new File(fullname); // Log.e(TAG, fullname + " " + full.length()); } } } public static void deleteSession( String sessionId ) throws IOException { String dirName = "/" + sessionId; File file = new File(dirName); // if the session doesnt have any ul/dl files - bail if (!file.exists()) { return; } // delete recursive delete( dirName ); } private static void delete(String parentName) throws IOException { File parent = new File(parentName); // if a file or an empty directory - delete it if (!parent.isDirectory() || parent.list().length == 0 ) { // Log.e(TAG, "delete:" + parent ); if (!parent.delete()) { throw new IOException("Error deleting " + parent); } return; } // directory - recurse String[] list = parent.list(); for (int i = 0 ; i < list.length ; i++) { String childName = parentName + "/" + list[i]; delete( childName ); } delete( parentName ); } private static final String VFS_SCHEME = "vfs"; public static Uri vfsUri(String filename) { return Uri.parse(VFS_SCHEME + ":" + filename); } public static boolean isVfsScheme(String scheme) { return VFS_SCHEME.equals(scheme); } public static Bitmap getThumbnailVfs(ContentResolver cr, Uri uri) { File image = new File(uri.getPath()); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inInputShareable = true; options.inPurgeable = true; // BitmapFactory.decodeFile(image.getPath(), options); try { FileInputStream fis = new FileInputStream(new File(image.getPath())); BitmapFactory.decodeStream(fis, null, options); } catch (Exception e) { Log.e(ImApp.LOG_TAG,"unable to read vfs thumbnail",e); return null; } if ((options.outWidth == -1) || (options.outHeight == -1)) return null; int originalSize = (options.outHeight > options.outWidth) ? options.outHeight : options.outWidth; BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = originalSize / MessageView.THUMBNAIL_SIZE; // Bitmap scaledBitmap = BitmapFactory.decodeFile(image.getPath(), opts); try { FileInputStream fis = new FileInputStream(new File(image.getPath())); Bitmap scaledBitmap = BitmapFactory.decodeStream(fis, null, opts); return scaledBitmap; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } /** * @param mCacheWord */ public static void init(Context context, String password) throws IllegalArgumentException { // Log.w(TAG, "init with password of length " + password.length()); if (password.length() > 32) password = password.substring(0, 32); IocVfs.password = password; init(context); } /** * Copy device content into vfs. * All imported content is stored under /SESSION_NAME/ * The original full path is retained to facilitate browsing * The session content can be deleted when the session is over * @param sourcePath * @return vfs uri * @throws IOException */ public static Uri importContent(String sessionId, String sourcePath) throws IOException { list("/"); File sourceFile = new File(sourcePath); String targetPath = "/" + sessionId + "/upload/" + sourceFile.getName(); targetPath = createUniqueFilename(targetPath); copyToVfs( sourcePath, targetPath ); list("/"); return vfsUri(targetPath); } public static void exportAll(String sessionId ) throws IOException { } public static void exportContent(String mimeType, Uri mediaUri) throws IOException { String targetPath = exportPath(mimeType, mediaUri); String sourcePath = mediaUri.getPath(); copyToExternal( sourcePath, targetPath); } public static String exportPath(String mimeType, Uri mediaUri) { String targetFilename; if (mimeType.startsWith("image")) { targetFilename = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) +"/" + mediaUri.getLastPathSegment(); } else if (mimeType.startsWith("audio")) { targetFilename = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) +"/" + mediaUri.getLastPathSegment(); } else { targetFilename = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +"/" + mediaUri.getLastPathSegment(); } String targetUniqueFilename = createUniqueFilenameExternal(targetFilename); return targetUniqueFilename; } public static void copyToVfs(String sourcePath, String targetPath) throws IOException { // create the target directories tree mkdirs( targetPath ); // copy java.io.FileInputStream fis = new java.io.FileInputStream(new java.io.File(sourcePath)); FileOutputStream fos = new FileOutputStream(new File(targetPath), false); byte[] b = new byte[8*1024]; int length; while ((length = fis.read(b)) != -1) { fos.write(b, 0, length); } fos.close(); fis.close(); } public static void copyToExternal(String sourcePath, String targetPath) throws IOException { // copy FileInputStream fis = new FileInputStream(new File(sourcePath)); java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(targetPath), false); byte[] b = new byte[8*1024]; int length; while ((length = fis.read(b)) != -1) { fos.write(b, 0, length); } fos.close(); fis.close(); } private static void mkdirs(String targetPath) throws IOException { File targetFile = new File(targetPath); if (!targetFile.exists()) { File dirFile = targetFile.getParentFile(); if (!dirFile.exists()) { boolean created = dirFile.mkdirs(); if (!created) { throw new IOException("Error creating " + targetPath); } } } } public static boolean exists(String path) { return new File(path).exists(); } public static boolean sessionExists(String sessionId) { return exists( "/" + sessionId ); } private static String createUniqueFilename( String filename ) { if (!exists(filename)) { return filename; } int count = 1; String uniqueName; File file; do { uniqueName = formatUnique(filename, count++); file = new File(uniqueName); } while(file.exists()); return uniqueName; } private static String formatUnique(String filename, int counter) { int lastDot = filename.lastIndexOf("."); String name = filename.substring(0,lastDot); String ext = filename.substring(lastDot); return name + "(" + counter + ")" + ext; } public static String getDownloadFilename(String sessionId, String filenameFromUrl) { String filename = "/" + sessionId + "/download/" + filenameFromUrl; String uniqueFilename = createUniqueFilename(filename); return uniqueFilename; } private static String createUniqueFilenameExternal( String filename ) { if (!(new java.io.File(filename)).exists()) { return filename; } int count = 1; String uniqueName; java.io.File file; do { uniqueName = formatUnique(filename, count++); file = new java.io.File(uniqueName); } while(file.exists()); return uniqueName; } }
package org.pentaho.di.job.entries.ftp; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.io.File; import java.net.InetAddress; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs.FileObject; import org.apache.log4j.Logger; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobEntryType; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.w3c.dom.Node; import com.enterprisedt.net.ftp.FTPClient; import com.enterprisedt.net.ftp.FTPConnectMode; import com.enterprisedt.net.ftp.FTPException; import com.enterprisedt.net.ftp.FTPTransferType; /** * This defines an FTP job entry. * * @author Matt * @since 05-11-2003 * */ public class JobEntryFTP extends JobEntryBase implements Cloneable, JobEntryInterface { private static Logger log4j = Logger.getLogger(JobEntryFTP.class); private String serverName; private String userName; private String password; private String ftpDirectory; private String targetDirectory; private String wildcard; private boolean binaryMode; private int timeout; private boolean remove; private boolean onlyGettingNewFiles; /* Don't overwrite files */ private boolean activeConnection; private String controlEncoding; /* how to convert list of filenames e.g. */ private String proxyHost; private String proxyPort; /* string to allow variable substitution */ private String proxyUsername; private String proxyPassword; /** * Implicit encoding used before PDI v2.4.1 */ static private String LEGACY_CONTROL_ENCODING = "US-ASCII"; //$NON-NLS-1$ /** * Default encoding when making a new ftp job entry instance. */ static private String DEFAULT_CONTROL_ENCODING = "ISO-8859-1"; //$NON-NLS-1$ public JobEntryFTP(String n) { super(n, ""); //$NON-NLS-1$ serverName = null; setID(-1L); setJobEntryType(JobEntryType.FTP); setControlEncoding(DEFAULT_CONTROL_ENCODING); binaryMode=true; } public JobEntryFTP() { this(""); //$NON-NLS-1$ } public JobEntryFTP(JobEntryBase jeb) { super(jeb); } public Object clone() { JobEntryFTP je = (JobEntryFTP) super.clone(); return je; } public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("servername", serverName)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("username", userName)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword()))); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetDirectory)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("binary", binaryMode)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("remove", remove)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("active", activeConnection)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("control_encoding", controlEncoding)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_host", proxyHost)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_port", proxyPort)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_username", proxyUsername)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("proxy_password", proxyPassword)); //$NON-NLS-1$ //$NON-NLS-2$ return retval.toString(); } public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases, slaveServers); serverName = XMLHandler.getTagValue(entrynode, "servername"); //$NON-NLS-1$ userName = XMLHandler.getTagValue(entrynode, "username"); //$NON-NLS-1$ password = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(entrynode, "password")); //$NON-NLS-1$ ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory"); //$NON-NLS-1$ targetDirectory = XMLHandler.getTagValue(entrynode, "targetdirectory"); //$NON-NLS-1$ wildcard = XMLHandler.getTagValue(entrynode, "wildcard"); //$NON-NLS-1$ binaryMode = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "binary")); //$NON-NLS-1$ //$NON-NLS-2$ timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 10000); //$NON-NLS-1$ remove = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "remove")); //$NON-NLS-1$ //$NON-NLS-2$ onlyGettingNewFiles = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "only_new")); //$NON-NLS-1$ //$NON-NLS-2$ activeConnection = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "active")); //$NON-NLS-1$ //$NON-NLS-2$ controlEncoding = XMLHandler.getTagValue(entrynode, "control_encoding"); //$NON-NLS-1$ if (controlEncoding == null) { // if we couldn't retrieve an encoding, assume it's an old instance and // put in the the encoding used before v 2.4.0 controlEncoding = LEGACY_CONTROL_ENCODING; } proxyHost = XMLHandler.getTagValue(entrynode, "proxy_host"); //$NON-NLS-1$ proxyPort = XMLHandler.getTagValue(entrynode, "proxy_port"); //$NON-NLS-1$ proxyUsername = XMLHandler.getTagValue(entrynode, "proxy_username"); //$NON-NLS-1$ proxyPassword = XMLHandler.getTagValue(entrynode, "proxy_password"); //$NON-NLS-1$ } catch (KettleXMLException xe) { throw new KettleXMLException(Messages.getString("JobEntryFTP.UnableToLoadFromXml"), xe); //$NON-NLS-1$ } } public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException { try { super.loadRep(rep, id_jobentry, databases, slaveServers); serverName = rep.getJobEntryAttributeString(id_jobentry, "servername"); //$NON-NLS-1$ userName = rep.getJobEntryAttributeString(id_jobentry, "username"); //$NON-NLS-1$ password = Encr.decryptPasswordOptionallyEncrypted( rep.getJobEntryAttributeString(id_jobentry, "password") ); //$NON-NLS-1$ ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory"); //$NON-NLS-1$ targetDirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory"); //$NON-NLS-1$ wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard"); //$NON-NLS-1$ binaryMode = rep.getJobEntryAttributeBoolean(id_jobentry, "binary"); //$NON-NLS-1$ timeout = (int) rep.getJobEntryAttributeInteger(id_jobentry, "timeout"); //$NON-NLS-1$ remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove"); //$NON-NLS-1$ onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new"); //$NON-NLS-1$ activeConnection = rep.getJobEntryAttributeBoolean(id_jobentry, "active"); //$NON-NLS-1$ controlEncoding = rep.getJobEntryAttributeString(id_jobentry, "control_encoding"); //$NON-NLS-1$ if (controlEncoding == null) { // if we couldn't retrieve an encoding, assume it's an old instance and // put in the the encoding used before v 2.4.0 controlEncoding = LEGACY_CONTROL_ENCODING; } proxyHost = rep.getJobEntryAttributeString(id_jobentry, "proxy_host"); //$NON-NLS-1$ proxyPort = rep.getJobEntryAttributeString(id_jobentry, "proxy_port"); //$NON-NLS-1$ proxyUsername = rep.getJobEntryAttributeString(id_jobentry, "proxy_username"); //$NON-NLS-1$ proxyPassword = rep.getJobEntryAttributeString(id_jobentry, "proxy_password"); //$NON-NLS-1$ } catch (KettleException dbe) { throw new KettleException( Messages.getString("JobEntryFTP.UnableToLoadFromRepo", String.valueOf(id_jobentry)), dbe); //$NON-NLS-1$ } } public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "username", userName); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "password", Encr.encryptPasswordIfNotUsingVariables(password)); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "targetdirectory", targetDirectory); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "binary", binaryMode); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "remove", remove); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "active", activeConnection); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "control_encoding", controlEncoding); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_host", proxyHost); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_port", proxyPort); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_username", proxyUsername); //$NON-NLS-1$ rep.saveJobEntryAttribute(id_job, getID(), "proxy_password", proxyPassword); //$NON-NLS-1$ } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("JobEntryFTP.UnableToSaveToRepo", String.valueOf(id_job)), dbe); //$NON-NLS-1$ } } /** * @return Returns the binaryMode. */ public boolean isBinaryMode() { return binaryMode; } /** * @param binaryMode The binaryMode to set. */ public void setBinaryMode(boolean binaryMode) { this.binaryMode = binaryMode; } /** * @return Returns the directory. */ public String getFtpDirectory() { return ftpDirectory; } /** * @param directory The directory to set. */ public void setFtpDirectory(String directory) { this.ftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName The serverName to set. */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard The wildcard to set. */ public void setWildcard(String wildcard) { this.wildcard = wildcard; } /** * @return Returns the targetDirectory. */ public String getTargetDirectory() { return targetDirectory; } /** * @param targetDirectory The targetDirectory to set. */ public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } /** * @param timeout The timeout to set. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the timeout. */ public int getTimeout() { return timeout; } /** * @param remove The remove to set. */ public void setRemove(boolean remove) { this.remove = remove; } /** * @return Returns the remove. */ public boolean getRemove() { return remove; } /** * @return Returns the onlyGettingNewFiles. */ public boolean isOnlyGettingNewFiles() { return onlyGettingNewFiles; } /** * @param onlyGettingNewFiles The onlyGettingNewFiles to set. */ public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles) { this.onlyGettingNewFiles = onlyGettingNewFiles; } /** * Get the control encoding to be used for ftp'ing * * @return the used encoding */ public String getControlEncoding() { return controlEncoding; } /** * Set the encoding to be used for ftp'ing. This determines how * names are translated in dir e.g. It does impact the contents * of the files being ftp'ed. * * @param encoding The encoding to be used. */ public void setControlEncoding(String encoding) { this.controlEncoding = encoding; } /** * @return Returns the hostname of the ftp-proxy. */ public String getProxyHost() { return proxyHost; } /** * @param proxyHost The hostname of the proxy. */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } /** * @return Returns the password which is used to authenticate at the proxy. */ public String getProxyPassword() { return proxyPassword; } /** * @param proxyPassword The password which is used to authenticate at the proxy. */ public void setProxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } /** * @return Returns the port of the ftp-proxy. */ public String getProxyPort() { return proxyPort; } /** * @param proxyPort The port of the ftp-proxy. */ public void setProxyPort(String proxyPort) { this.proxyPort = proxyPort; } /** * @return Returns the username which is used to authenticate at the proxy. */ public String getProxyUsername() { return proxyUsername; } /** * @param proxyUsername The username which is used to authenticate at the proxy. */ public void setProxyUsername(String proxyUsername) { this.proxyUsername = proxyUsername; } public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); log4j.info(Messages.getString("JobEntryFTP.Started", serverName)); //$NON-NLS-1$ Result result = previousResult; result.setResult(false); long filesRetrieved = 0; log.logDetailed(toString(), Messages.getString("JobEntryFTP.Start")); //$NON-NLS-1$ FTPClient ftpclient = null; try { // Create ftp client to host:port ... ftpclient = new FTPClient(); String realServername = environmentSubstitute(serverName); ftpclient.setRemoteAddr(InetAddress.getByName(realServername)); if (!Const.isEmpty(proxyHost)) { String realProxy_host = environmentSubstitute(proxyHost); ftpclient.setRemoteAddr(InetAddress.getByName(realProxy_host)); if ( log.isDetailed() ) log.logDetailed(toString(), "Opened FTP connection to proxy server ["+realProxy_host+"]"); // FIXME: Proper default port for proxy int port = Const.toInt(environmentSubstitute(proxyPort), 0); if (port != 0) { ftpclient.setRemotePort(port); } } else { ftpclient.setRemoteAddr(InetAddress.getByName(realServername)); if ( log.isDetailed() ) log.logDetailed(toString(), "Opened FTP connection to server ["+realServername+"]"); } if ( log.isDetailed() ) log.logDetailed(toString(), Messages.getString("JobEntryFTP.OpenedConnection", realServername)); //$NON-NLS-1$ // set activeConnection connectmode ... if (activeConnection) { ftpclient.setConnectMode(FTPConnectMode.ACTIVE); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetActive")); //$NON-NLS-1$ } else { ftpclient.setConnectMode(FTPConnectMode.PASV); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetPassive")); //$NON-NLS-1$ } // Set the timeout ftpclient.setTimeout(timeout * 1000); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetTimeout", String.valueOf(timeout))); //$NON-NLS-1$ ftpclient.setControlEncoding(controlEncoding); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetEncoding", controlEncoding)); //$NON-NLS-1$ // login to ftp host ... ftpclient.connect(); String realUsername = environmentSubstitute(userName) + (!Const.isEmpty(proxyUsername) ? "@" + environmentSubstitute(proxyUsername) : "") + (!Const.isEmpty(proxyHost) ? "@" + realServername : ""); String realPassword = environmentSubstitute(password) + (!Const.isEmpty(proxyPassword) ? "@" + environmentSubstitute(proxyPassword) : "" ); ftpclient.login(realUsername, realPassword); // Remove password from logging, you don't know where it ends up. log.logDetailed(toString(), Messages.getString("JobEntryFTP.LoggedIn", realUsername)); //$NON-NLS-1$ // move to spool dir ... if (!Const.isEmpty(ftpDirectory)) { String realFtpDirectory = environmentSubstitute(ftpDirectory); ftpclient.chdir(realFtpDirectory); log.logDetailed(toString(), Messages.getString("JobEntryFTP.ChangedDir", realFtpDirectory)); //$NON-NLS-1$ } // Get all the files in the current directory... String[] filelist = ftpclient.dir(); log.logDetailed(toString(), Messages.getString("JobEntryFTP.FoundNFiles", String.valueOf(filelist.length))); //$NON-NLS-1$ // set transfertype ... if (binaryMode) { ftpclient.setType(FTPTransferType.BINARY); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetBinary")); //$NON-NLS-1$ } else { ftpclient.setType(FTPTransferType.ASCII); log.logDetailed(toString(), Messages.getString("JobEntryFTP.SetAscii")); //$NON-NLS-1$ } // Some FTP servers return a message saying no files found as a string in the filenlist // e.g. Solaris 8 // CHECK THIS !!! if (filelist.length == 1) { String translatedWildcard = environmentSubstitute(wildcard); if (filelist[0].startsWith(translatedWildcard)) { throw new FTPException(filelist[0]); } } Pattern pattern = null; if (!Const.isEmpty(wildcard)) { String realWildcard = environmentSubstitute(wildcard); pattern = Pattern.compile(realWildcard); } // Get the files in the list... for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) { boolean getIt = true; // First see if the file matches the regular expression! if (pattern != null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { log.logDetailed(toString(), Messages.getString("JobEntryFTP.GettingFile", filelist[i], environmentSubstitute(targetDirectory))); //$NON-NLS-1$ String targetFilename = getTargetFilename(filelist[i]); FileObject targetFile = KettleVFS.getFileObject(targetFilename); if ((onlyGettingNewFiles == false) || (onlyGettingNewFiles == true) && needsDownload(filelist[i])) { ftpclient.get(KettleVFS.getOutputStream(targetFilename, false), filelist[i]); filesRetrieved++; // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString()); resultFile.setComment(Messages.getString("JobEntryFTP.Downloaded", serverName)); //$NON-NLS-1$ result.getResultFiles().put(resultFile.getFile().toString(), resultFile); log.logDetailed(toString(), Messages.getString("JobEntryFTP.GotFile", filelist[i])); //$NON-NLS-1$ } // Delete the file if this is needed! if (remove) { ftpclient.delete(filelist[i]); log.logDetailed(toString(), Messages.getString("JobEntryFTP.DeletedFile", filelist[i])); //$NON-NLS-1$ } } } result.setResult(true); result.setNrFilesRetrieved(filesRetrieved); } catch (Exception e) { result.setNrErrors(1); log.logError(toString(), Messages.getString("JobEntryFTP.ErrorGetting", e.getMessage())); //$NON-NLS-1$ log.logError(toString(), Const.getStackTracker(e)); } finally { if (ftpclient != null && ftpclient.connected()) { try { ftpclient.quit(); } catch (Exception e) { log.logError(toString(), Messages.getString("JobEntryFTP.ErrorQuitting", e.getMessage())); //$NON-NLS-1$ } } } return result; } /** * @param string the filename from the FTP server * * @return the calculated target filename */ protected String getTargetFilename(String string) { return environmentSubstitute(targetDirectory) + Const.FILE_SEPARATOR + string; } public boolean evaluates() { return true; } /** * See if the filename on the FTP server needs downloading. * The default is to check the presence of the file in the target directory. * If you need other functionality, extend this class and build it into a plugin. * * @param filename The filename to check * @return true if the file needs downloading */ protected boolean needsDownload(String filename) { File file = new File(getTargetFilename(filename)); return !file.exists(); } /** * @return the activeConnection */ public boolean isActiveConnection() { return activeConnection; } /** * @param activeConnection the activeConnection to set */ public void setActiveConnection(boolean passive) { this.activeConnection = passive; } public void check(List<CheckResultInterface> remarks, JobMeta jobMeta) { andValidator().validate(this, "serverName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator() .validate(this, "targetDirectory", remarks, putValidators(notBlankValidator(), fileExistsValidator())); //$NON-NLS-1$ andValidator().validate(this, "userName", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$ andValidator().validate(this, "password", remarks, putValidators(notNullValidator())); //$NON-NLS-1$ } public List<ResourceReference> getResourceDependencies(JobMeta jobMeta) { List<ResourceReference> references = super.getResourceDependencies(jobMeta); if (!Const.isEmpty(serverName)) { String realServername = jobMeta.environmentSubstitute(serverName); ResourceReference reference = new ResourceReference(this); reference.getEntries().add(new ResourceEntry(realServername, ResourceType.SERVER)); references.add(reference); } return references; } }
package org.jtrfp.trcl.beh; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.InterpolatingAltitudeMap; import org.jtrfp.trcl.TerrainChunk; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.Powerup; import org.jtrfp.trcl.obj.WorldObject; public class LeavesPowerupOnDeathBehavior extends Behavior implements DeathListener { private static final int OVER_TERRAIN_PAD=20000; private final Powerup pup; public LeavesPowerupOnDeathBehavior(Powerup p){ this.pup=p; } @Override public void notifyDeath() {//Y-fudge to ensure powerup is not too close to ground. final WorldObject p=getParent(); final Vector3D thisPos=p.getPosition(); double height; final InterpolatingAltitudeMap map=p.getTr().getAltitudeMap(); if(map!=null)height= map.heightAt((thisPos.getX()/TR.mapSquareSize), (thisPos.getZ()/TR.mapSquareSize))*(p.getTr().getWorld().sizeY/2); else{height=Double.NEGATIVE_INFINITY;} final Vector3D yFudge=thisPos.getY()<height+OVER_TERRAIN_PAD?new Vector3D(0,OVER_TERRAIN_PAD,0):Vector3D.ZERO; getParent().getTr().getResourceManager().getPluralizedPowerupFactory(). spawn(getParent().getPosition().add(yFudge), pup); }//end notifyDeath() }//end LeavesPowerupOnDeathBehavior
package org.mafagafogigante.dungeon.commands; import org.mafagafogigante.dungeon.game.DungeonString; import org.mafagafogigante.dungeon.io.Writer; import org.mafagafogigante.dungeon.logging.DungeonLogger; import org.mafagafogigante.dungeon.util.Utils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A set of Commands. */ public final class CommandSet { private static final int COMMAND_NAME_COLUMN_WIDTH = 20; private final List<Command> commands = new ArrayList<>(); private final List<CommandDescription> commandDescriptions = new ArrayList<>(); private CommandSet() { } /** * Constructs an empty CommandSet containing only the "commands" Command. */ public static CommandSet emptyCommandSet() { final CommandSet commandSet = new CommandSet(); commandSet.addCommand(new Command("commands", "Lists all commands in this command set.") { @Override public void execute(@NotNull String[] arguments) { String filter = arguments.length == 0 ? null : arguments[0]; List<CommandDescription> descriptions = commandSet.getCommandDescriptions(); DungeonString dungeonString = new DungeonString(); int count = 0; for (CommandDescription description : descriptions) { if (filter == null || Utils.startsWithIgnoreCase(description.getName(), filter)) { count++; dungeonString.append(Utils.padString(description.getName(), COMMAND_NAME_COLUMN_WIDTH)); dungeonString.append(description.getInfo()); dungeonString.append("\n"); } } if (count == 0 && filter != null) { Writer.write("No command starts with '" + filter + "'."); } else { if (count > 1) { dungeonString.append("\nListed "); dungeonString.append(String.valueOf(count)); dungeonString.append(" commands."); if (filter == null) { dungeonString.append("\nYou can filter the output of this command by typing the beginning of a command."); } } Writer.write(dungeonString); } } }); return commandSet; } /** * Retrieves a Command corresponding to the specified token or null if no command matches the token. */ public Command getCommand(String token) { for (Command command : commands) { if (command.getDescription().getName().equalsIgnoreCase(token)) { return command; } } return null; } /** * Adds a Command to this CommandSet. * * @param command a Command object, not null */ void addCommand(Command command) { if (command == null) { DungeonLogger.warning("Passed null to CommandSet.addCommand()."); } else if (commands.contains(command)) { DungeonLogger.warning("Attempted to add the same Command to a CommandSet twice."); } else { commands.add(command); commandDescriptions.add(command.getDescription()); } } /** * Returns an unmodifiable view of the List of CommandDescriptions. * * @return an unmodifiable List of CommandDescriptions */ private List<CommandDescription> getCommandDescriptions() { return Collections.unmodifiableList(commandDescriptions); } @Override public String toString() { return String.format("CommandSet of size %d.", commands.size()); } /** * Retrieves a list of the names of the commands closest to the provided token according to their Levenshtein * distance. */ public List<String> getClosestCommands(String token) { List<String> closestCommands = new ArrayList<>(); int best = Integer.MAX_VALUE; for (Command command : commands) { String commandName = command.getDescription().getName(); int distance = StringUtils.getLevenshteinDistance(token, commandName); if (distance < best) { closestCommands.clear(); best = distance; } if (distance == best) { closestCommands.add(commandName); } } return closestCommands; } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc862.sirius.subsystems; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; import org.usfirst.frc862.sirius.RobotMap; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.command.Subsystem; public class Pivot extends Subsystem { private static final double ANGLE_EPSILON = 1.0; class PowerTableValue { public double up_power; public double down_power; public double hold_power; public PowerTableValue(double u, double d, double h) { up_power = u; down_power = d; hold_power = h; } } // TODO switch to something that uses a primitive double key so we don't have to create an object for each get // Key = angle, value = associated powers private NavigableMap<Double, PowerTableValue> powerTable; public Pivot() { powerTable = new TreeMap<>(); // TODO externalize to a file and expose to // smart dashboard -- verify list is always sorted powerTable.put(0.0, new PowerTableValue(-0.3, 0.1, -0.2)); powerTable.put(10.0, new PowerTableValue(-0.4, 0.1, -0.25)); powerTable.put(40.0, new PowerTableValue(-0.5, 0.1, -0.3)); } public PowerTableValue getPowerValues(double angle) { // find floor/ceiling values Entry<Double, PowerTableValue> floor = powerTable.floorEntry(angle); Entry<Double, PowerTableValue> ceil = powerTable.ceilingEntry(angle); if(ceil == null) { ceil = powerTable.lastEntry(); } if(floor == null) { floor = powerTable.firstEntry(); } // Pull angle and values from the ceil and floor double floorAngle = floor.getKey(); PowerTableValue floorValues = floor.getValue(); double ceilAngle = ceil.getKey(); PowerTableValue ceilValues = ceil.getValue(); // find position between double distance = ceilAngle - floorAngle; double percent = (angle - floorAngle) / distance; // interpolate to position return new PowerTableValue( interpolate(percent, floorValues.up_power, ceilValues.up_power), interpolate(percent, floorValues.down_power, ceilValues.down_power), interpolate(percent, floorValues.hold_power, ceilValues.hold_power) ); } public double interpolate(double dist, double low, double high) { return (high - low) * dist + low; } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private final Encoder angleEncoder = RobotMap.pivotAngleEncoder; private final SpeedController angleMotor = RobotMap.pivotAngleMotor; private final DigitalInput hallEffect = RobotMap.pivotHallEffect; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } public void moveToAngle(double angle) { PowerTableValue val = getPowerValues(angle); if (atAngle(angle)) { angleMotor.set(val.hold_power); } else if (angleEncoder.getDistance() > angle) { angleMotor.set(val.down_power); } else { angleMotor.set(val.up_power); } } public void hold() { PowerTableValue val = getPowerValues(angleEncoder.getDistance()); angleMotor.set(val.hold_power); } public boolean atAngle(double intakeAngle) { return Math.abs(angleEncoder.getDistance() - intakeAngle) < ANGLE_EPSILON; } public double getAngle() { return angleEncoder.getDistance(); } public void setPower(double v) { angleMotor.set(v); } }
package org.support.project.knowledge.logic; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.support.project.aop.Aspect; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; import org.support.project.common.util.StringUtils; import org.support.project.di.Container; import org.support.project.di.DI; import org.support.project.di.Instance; import org.support.project.knowledge.dao.EventsDao; import org.support.project.knowledge.dao.KnowledgeItemValuesDao; import org.support.project.knowledge.dao.ParticipantsDao; import org.support.project.knowledge.entity.EventsEntity; import org.support.project.knowledge.entity.KnowledgeItemValuesEntity; import org.support.project.knowledge.entity.KnowledgesEntity; import org.support.project.knowledge.entity.ParticipantsEntity; import org.support.project.knowledge.vo.Participation; import org.support.project.knowledge.vo.Participations; import org.support.project.web.bean.LoginedUser; @DI(instance = Instance.Singleton) public class EventsLogic { private static final int PAGE_LIMIT = 20; private static final Log LOG = LogFactory.getLog(EventsLogic.class); public static final int ITEM_NO_DATE = 0; public static final int ITEM_NO_START = 1; public static final int ITEM_NO_END = 2; public static final int ITEM_NO_TIMEZONE = 3; public static final int ITEM_NO_THE_NUMBER_TO_BE_ACCEPTED = 4; public static final int STSTUS_PARTICIPATION = 1; public static final int STSTUS_WAIT_CANSEL = 0; public static EventsLogic get() { return Container.getComp(EventsLogic.class); } private void logging(Calendar calendar) { if (LOG.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); builder.append(calendar.getTimeInMillis()).append(" "); builder.append(calendar.get(Calendar.YEAR)).append("/") .append(calendar.get(Calendar.MONTH) + 1).append("/") .append(calendar.get(Calendar.DATE)).append(" "); builder.append(calendar.get(Calendar.HOUR)).append(":") .append(calendar.get(Calendar.MINUTE)).append(":") .append(calendar.get(Calendar.SECOND)).append(".") .append(calendar.get(Calendar.MILLISECOND)).append(" "); builder.append(calendar.getTimeZone().getDisplayName()); LOG.debug(builder.toString()); } } public List<EventsEntity> eventList(String date, String timezone, LoginedUser loginedUser) throws ParseException { DateFormat monthformat = new SimpleDateFormat("yyyyMM"); Date d = monthformat.parse(date); TimeZone tz = TimeZone.getTimeZone(timezone); Calendar start = Calendar.getInstance(tz); Calendar end = Calendar.getInstance(tz); TimeZone gmt = TimeZone.getTimeZone("GMT"); Calendar in = Calendar.getInstance(gmt); in.setTime(d); start.set(in.get(Calendar.YEAR), in.get(Calendar.MONTH), 1, 0, 0, 0); start.set(Calendar.MILLISECOND, 0); end.set(in.get(Calendar.YEAR), in.get(Calendar.MONTH), in.getActualMaximum(Calendar.DATE), 23, 59, 59); end.set(Calendar.MILLISECOND, 999); logging(in); logging(start); logging(end); return EventsDao.get().selectAccessAbleEvents(start, end, loginedUser); } public List<KnowledgesEntity> eventKnowledgeList(String date, String timezone, LoginedUser loginedUser) throws ParseException { DateFormat format = new SimpleDateFormat("yyyyMMdd"); Date d = format.parse(date); TimeZone tz = TimeZone.getTimeZone(timezone); Calendar start = Calendar.getInstance(tz); start.setTime(d); start.set(Calendar.HOUR, 0); start.set(Calendar.MINUTE, 0); start.set(Calendar.SECOND, 0); start.set(Calendar.MILLISECOND, 0); return EventsDao.get().selectAccessAbleEvents(start, loginedUser, PAGE_LIMIT, 0); } public Participations isParticipation(Long knowledgeId, Integer userId) { Participations participations = new Participations(); ParticipantsEntity participant = ParticipantsDao.get().selectOnKey(knowledgeId, userId); if (participant != null) { participations.setStatus(participant.getStatus()); } KnowledgeItemValuesEntity limit = KnowledgeItemValuesDao.get().selectOnKey( ITEM_NO_THE_NUMBER_TO_BE_ACCEPTED, knowledgeId, TemplateLogic.TYPE_ID_EVENT); if (StringUtils.isInteger(limit.getItemValue())) { participations.setLimit(new Integer(limit.getItemValue())); } List<Participation> participants = ParticipantsDao.get().selectParticipations(knowledgeId); for (Participation participation : participants) { participation.setPassword("-"); } participations.setCount(participants.size()); participations.setParticipations(participants); return participations; } /** * * @param knowledgeId * @param loginUserId * @return */ @Aspect(advice = org.support.project.ormapping.transaction.Transaction.class) public Boolean participation(Long knowledgeId, Integer userId) { ParticipantsEntity participant = ParticipantsDao.get().selectOnKey(knowledgeId, userId); if (participant != null) { if (participant.getStatus().intValue() == STSTUS_PARTICIPATION) { return true; } else { return false; } } KnowledgeItemValuesEntity limit = KnowledgeItemValuesDao.get().selectOnKey( ITEM_NO_THE_NUMBER_TO_BE_ACCEPTED, knowledgeId, TemplateLogic.TYPE_ID_EVENT); int limitCnt = 0; if (StringUtils.isInteger(limit.getItemValue())) { limitCnt = new Integer(limit.getItemValue()); } List<Participation> participants = ParticipantsDao.get().selectParticipations(knowledgeId); participant = new ParticipantsEntity(knowledgeId, userId); if (participants.size() < limitCnt) { participant.setStatus(STSTUS_PARTICIPATION); } else { participant.setStatus(STSTUS_WAIT_CANSEL); } ParticipantsDao.get().insert(participant); return participant.getStatus().intValue() == STSTUS_PARTICIPATION; } /** * * @param knowledgeId * @param userId */ @Aspect(advice = org.support.project.ormapping.transaction.Transaction.class) public void removeParticipation(Long knowledgeId, Integer userId) { ParticipantsEntity participant = ParticipantsDao.get().selectOnKey(knowledgeId, userId); if (participant == null) { return; } ParticipantsDao.get().physicalDelete(participant); if (participant.getStatus().intValue() == STSTUS_PARTICIPATION) { List<Participation> participants = ParticipantsDao.get().selectParticipations(knowledgeId); for (int i = 0; i < participants.size(); i++) { Participation p = participants.get(i); if (p.getStatus().intValue() == STSTUS_WAIT_CANSEL) { ParticipantsEntity entity = new ParticipantsEntity(knowledgeId, p.getUserId()); entity.setStatus(STSTUS_PARTICIPATION); ParticipantsDao.get().update(entity); break; } } } } }
package org.threadly.concurrent; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import org.threadly.concurrent.lock.NativeLockFactory; import org.threadly.concurrent.lock.StripedLock; import org.threadly.concurrent.lock.VirtualLock; /** * TaskDistributor is designed to take a multi-threaded pool * and add tasks with a given key such that those tasks will * be run single threaded for any given key. The thread which * runs those tasks may be different each time, but no two tasks * with the same key will ever be run in parallel. * * Because of that, it is recommended that the executor provided * has as many possible threads as possible keys that could be * provided to be run in parallel. If this class is starved for * threads some keys may continue to process new tasks, while * other keys could be starved. * * @author jent - Mike Jensen */ public class TaskExecutorDistributor { protected static final int DEFAULT_THREAD_KEEPALIVE_TIME = 1000 * 10; protected static final int DEFAULT_LOCK_PARALISM = 10; protected static final float CONCURRENT_HASH_MAP_LOAD_FACTOR = (float)0.75; // 0.75 is ConcurrentHashMap default protected static final int CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE = 100; protected static final int CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL = 100; protected final Executor executor; protected final StripedLock sLock; private final ConcurrentHashMap<Object, TaskQueueWorker> taskWorkers; /** * Constructor which creates executor based off provided values. * * @param expectedParallism Expected number of keys that will be used in parallel * @param maxThreadCount Max thread count (limits the qty of keys which are handled in parallel) */ public TaskExecutorDistributor(int expectedParallism, int maxThreadCount) { this(new PriorityScheduledExecutor(expectedParallism, maxThreadCount, DEFAULT_THREAD_KEEPALIVE_TIME, TaskPriority.High, PriorityScheduledExecutor.DEFAULT_LOW_PRIORITY_MAX_WAIT), new StripedLock(expectedParallism, new NativeLockFactory())); } /** * Constructor to use a provided executor implementation for running tasks. * * @param executor A multi-threaded executor to distribute tasks to. * Ideally has as many possible threads as keys that * will be used in parallel. */ public TaskExecutorDistributor(Executor executor) { this(DEFAULT_LOCK_PARALISM, executor); } /** * Constructor to use a provided executor implementation for running tasks. * * @param expectedParallism level of expected qty of threads adding tasks in parallel * @param executor A multi-threaded executor to distribute tasks to. * Ideally has as many possible threads as keys that * will be used in parallel. */ public TaskExecutorDistributor(int expectedParallism, Executor executor) { this(executor, new StripedLock(expectedParallism, new NativeLockFactory())); } /** * used for testing, so that agentLock can be held and prevent execution. */ protected TaskExecutorDistributor(Executor executor, StripedLock sLock) { if (executor == null) { throw new IllegalArgumentException("executor can not be null"); } this.executor = executor; this.sLock = sLock; int mapInitialSize = Math.min(sLock.getExpectedConcurrencyLevel(), CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE); int mapConcurrencyLevel = Math.min(sLock.getExpectedConcurrencyLevel(), CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL); this.taskWorkers = new ConcurrentHashMap<Object, TaskQueueWorker>(mapInitialSize, CONCURRENT_HASH_MAP_LOAD_FACTOR, mapConcurrencyLevel); } /** * Getter for the executor being used behind the scenes. * * @return executor tasks are being distributed to */ public Executor getExecutor() { return executor; } /** * Provide a task to be run with a given thread key. * * @param threadKey object key where hashCode will be used to determine execution thread * @param task Task to be executed. */ public void addTask(Object threadKey, Runnable task) { if (threadKey == null) { throw new IllegalArgumentException("Must provide thread key"); } else if (task == null) { throw new IllegalArgumentException("Must provide task"); } VirtualLock agentLock = sLock.getLock(threadKey); synchronized (agentLock) { TaskQueueWorker worker = taskWorkers.get(threadKey); if (worker == null) { worker = new TaskQueueWorker(threadKey, agentLock, task); taskWorkers.put(threadKey, worker); executor.execute(worker); } else { worker.add(task); } } } /** * Worker which will consume through a given queue of tasks. * Each key is represented by one worker at any given time. * * @author jent - Mike Jensen */ private class TaskQueueWorker extends VirtualRunnable { private final Object mapKey; private final VirtualLock agentLock; private LinkedList<Runnable> queue; private TaskQueueWorker(Object mapKey, VirtualLock agentLock, Runnable firstTask) { this.mapKey = mapKey; this.agentLock = agentLock; this.queue = new LinkedList<Runnable>(); queue.add(firstTask); } public void add(Runnable task) { synchronized (agentLock) { queue.addLast(task); } } private List<Runnable> next() { synchronized (agentLock) { List<Runnable> result = queue; queue = new LinkedList<Runnable>(); return result; } } @Override public void run() { while (true) { List<Runnable> nextList; synchronized (agentLock) { nextList = next(); if (nextList == null) { taskWorkers.remove(mapKey); break; // stop consuming tasks } } Iterator<Runnable> it = nextList.iterator(); while (it.hasNext()) { try { Runnable next = it.next(); if (factory != null && next instanceof VirtualRunnable) { ((VirtualRunnable)next).run(factory); } else { next.run(); } } catch (Throwable t) { UncaughtExceptionHandler ueh = Thread.getDefaultUncaughtExceptionHandler(); ueh.uncaughtException(Thread.currentThread(), t); } } } } } }
package org.threadly.concurrent; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import org.threadly.concurrent.lock.NativeLockFactory; import org.threadly.concurrent.lock.StripedLock; import org.threadly.concurrent.lock.VirtualLock; /** * TaskDistributor is designed to take a multi-threaded pool * and add tasks with a given key such that those tasks will * be run single threaded for any given key. The thread which * runs those tasks may be different each time, but no two tasks * with the same key will ever be run in parallel. * * Because of that, it is recommended that the executor provided * has as many possible threads as possible keys that could be * provided to be run in parallel. If this class is starved for * threads some keys may continue to process new tasks, while * other keys could be starved. * * @author jent - Mike Jensen */ public class TaskExecutorDistributor { protected static final int DEFAULT_THREAD_KEEPALIVE_TIME = 1000 * 10; protected static final int DEFAULT_LOCK_PARALISM = 10; protected static final float CONCURRENT_HASH_MAP_LOAD_FACTOR = (float)0.75; // 0.75 is ConcurrentHashMap default protected static final int CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE = 100; protected static final int CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL = 100; protected final Executor executor; protected final StripedLock sLock; private final ConcurrentHashMap<Object, TaskQueueWorker> taskWorkers; /** * Constructor which creates executor based off provided values. * * @param expectedParallism Expected number of keys that will be used in parallel * @param maxThreadCount Max thread count (limits the qty of keys which are handled in parallel) */ public TaskExecutorDistributor(int expectedParallism, int maxThreadCount) { this(new PriorityScheduledExecutor(expectedParallism, maxThreadCount, DEFAULT_THREAD_KEEPALIVE_TIME, TaskPriority.High, PriorityScheduledExecutor.DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS), new StripedLock(expectedParallism, new NativeLockFactory())); } /** * Constructor to use a provided executor implementation for running tasks. * * @param executor A multi-threaded executor to distribute tasks to. * Ideally has as many possible threads as keys that * will be used in parallel. */ public TaskExecutorDistributor(Executor executor) { this(DEFAULT_LOCK_PARALISM, executor); } /** * Constructor to use a provided executor implementation for running tasks. * * @param expectedParallism level of expected qty of threads adding tasks in parallel * @param executor A multi-threaded executor to distribute tasks to. * Ideally has as many possible threads as keys that * will be used in parallel. */ public TaskExecutorDistributor(int expectedParallism, Executor executor) { this(executor, new StripedLock(expectedParallism, new NativeLockFactory())); } /** * Constructor to be used in unit tests. This allows you to provide a StripedLock * that provides a {@link org.threadly.test.concurrent.lock.TestableLockFactory} so * that this class can be used with the * {@link org.threadly.test.concurrent.TestablePriorityScheduler}. * * @param executor executor to be used for task worker execution * @param sLock lock to be used for controlling access to workers */ public TaskExecutorDistributor(Executor executor, StripedLock sLock) { if (executor == null) { throw new IllegalArgumentException("executor can not be null"); } else if (sLock == null) { throw new IllegalArgumentException("striped lock must be provided"); } this.executor = executor; this.sLock = sLock; int mapInitialSize = Math.min(sLock.getExpectedConcurrencyLevel(), CONCURRENT_HASH_MAP_MAX_INITIAL_SIZE); int mapConcurrencyLevel = Math.min(sLock.getExpectedConcurrencyLevel(), CONCURRENT_HASH_MAP_MAX_CONCURRENCY_LEVEL); this.taskWorkers = new ConcurrentHashMap<Object, TaskQueueWorker>(mapInitialSize, CONCURRENT_HASH_MAP_LOAD_FACTOR, mapConcurrencyLevel); } /** * Getter for the executor being used behind the scenes. * * @return executor tasks are being distributed to */ public Executor getExecutor() { return executor; } /** * Returns an executor interface where all tasks submitted * on this executor will run on the provided key. * * @param threadKey object key where hashCode will be used to determine execution thread * @return executor which will only execute based on the provided key */ public Executor getExecutorForKey(Object threadKey) { if (threadKey == null) { throw new IllegalArgumentException("Must provide thread key"); } return new KeyBasedExecutor(threadKey); } /** * Provide a task to be run with a given thread key. * * @param threadKey object key where hashCode will be used to determine execution thread * @param task Task to be executed. */ public void addTask(Object threadKey, Runnable task) { if (threadKey == null) { throw new IllegalArgumentException("Must provide thread key"); } else if (task == null) { throw new IllegalArgumentException("Must provide task"); } VirtualLock agentLock = sLock.getLock(threadKey); synchronized (agentLock) { TaskQueueWorker worker = taskWorkers.get(threadKey); if (worker == null) { worker = new TaskQueueWorker(threadKey, agentLock, task); taskWorkers.put(threadKey, worker); executor.execute(worker); } else { worker.add(task); } } } /** * Worker which will consume through a given queue of tasks. * Each key is represented by one worker at any given time. * * @author jent - Mike Jensen */ private class TaskQueueWorker extends VirtualRunnable { private final Object mapKey; private final VirtualLock agentLock; private LinkedList<Runnable> queue; private TaskQueueWorker(Object mapKey, VirtualLock agentLock, Runnable firstTask) { this.mapKey = mapKey; this.agentLock = agentLock; this.queue = new LinkedList<Runnable>(); queue.add(firstTask); } public void add(Runnable task) { queue.addLast(task); } @Override public void run() { while (true) { List<Runnable> nextList; synchronized (agentLock) { nextList = queue; if (nextList.isEmpty()) { // stop consuming tasks taskWorkers.remove(mapKey); break; } else { // prepare queue for future tasks queue = new LinkedList<Runnable>(); } } Iterator<Runnable> it = nextList.iterator(); while (it.hasNext()) { try { Runnable next = it.next(); if (factory != null && next instanceof VirtualRunnable) { ((VirtualRunnable)next).run(factory); } else { next.run(); } } catch (Throwable t) { UncaughtExceptionHandler ueh = Thread.getDefaultUncaughtExceptionHandler(); if (ueh != null) { ueh.uncaughtException(Thread.currentThread(), t); } else { t.printStackTrace(); } } } } } } /** * Simple executor implementation that runs on a given key. * * @author jent - Mike Jensen */ private class KeyBasedExecutor implements Executor { private final Object threadKey; private KeyBasedExecutor(Object threadKey) { this.threadKey = threadKey; } @Override public void execute(Runnable command) { addTask(threadKey, command); } } }
package org.threadly.litesockets; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import org.threadly.concurrent.NoThreadScheduler; import org.threadly.concurrent.SubmitterExecutor; import org.threadly.litesockets.utils.IOUtils; import org.threadly.util.ArgumentVerifier; import org.threadly.util.Clock; /** * <p>The NoThreadSocketExecuter is a simpler implementation of a {@link SocketExecuter} * that does not create any threads. Since there are no threads operations happen on whatever thread * calls .select(), and only 1 thread at a time should ever call it at a time. Other then * that it should be completely thread safe.</p> * * <p>This is generally the implementation used by clients. It can be used for servers * but only when not servicing many connections at once. How many connections is hardware * and OS defendant. For an average multi-core x86 linux server I a connections not to much more * then 1000 connections would be its limit, though alot depends on how active those connections are.</p> * * <p>It should also be noted that all client read/close callbacks happen on the thread that calls select().</p> * * @author lwahlmeier */ public class NoThreadSocketExecuter extends SocketExecuterCommonBase { private final NoThreadScheduler localNoThreadScheduler; private Selector commonSelector; private volatile boolean wakeUp = false; /** * Constructs a NoThreadSocketExecuter. {@link #start()} must still be called before using it. */ public NoThreadSocketExecuter() { super(new NoThreadScheduler()); localNoThreadScheduler = (NoThreadScheduler)schedulerPool; } /** * This is used to wakeup the {@link Selector} assuming it was called with a timeout on it. * Most all methods in this class that need to do a wakeup do it automatically, but * there are situations where you might want to wake up the thread we are blocked on * manually. */ public void wakeup() { if(commonSelector != null && commonSelector.isOpen()) { wakeUp = true; commonSelector.wakeup(); } } @Override public void setClientOperations(final Client client) { ArgumentVerifier.assertNotNull(client, "Client"); if(!clients.containsKey(client.getChannel())) { return; } if(client.isClosed()) { clients.remove(client.getChannel()); schedulerPool.submit(new RemoveFromSelector(commonSelector, client)).addListener(new Runnable() { @Override public void run() { IOUtils.closeQuietly(client.getChannel()); }}); } else if(client.getChannel().isConnectionPending()) { schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_CONNECT)); } else if(client.canWrite() && client.canRead()) { schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE|SelectionKey.OP_READ)); } else if (client.canRead()){ schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_READ)); } else if (client.canWrite()){ schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, SelectionKey.OP_WRITE)); } else { schedulerPool.execute(new AddToSelector(schedulerPool, client, commonSelector, 0)); } commonSelector.wakeup(); } @Override public void setUDPServerOperations(final UDPServer udpServer, final boolean enable) { if(checkServer(udpServer)) { if(enable) { if(udpServer.needsWrite()) { schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ|SelectionKey.OP_WRITE)); } else { schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, SelectionKey.OP_READ)); } } else { schedulerPool.execute(new AddToSelector(schedulerPool, udpServer, commonSelector, 0)); } commonSelector.wakeup(); } } @Override protected void startupService() { commonSelector = openSelector(); this.acceptSelector = commonSelector; this.readSelector = commonSelector; this.writeSelector = commonSelector; } @Override protected void shutdownService() { commonSelector.wakeup(); for(final Client client: clients.values()) { IOUtils.closeQuietly(client); } for(final Server server: servers.values()) { IOUtils.closeQuietly(server); } if(commonSelector != null && commonSelector.isOpen()) { closeSelector(schedulerPool, commonSelector); } while(localNoThreadScheduler.hasTaskReadyToRun()) { try { localNoThreadScheduler.tick(null); } catch(Exception e) { } } clients.clear(); servers.clear(); } /** * This will run all ExecuterTasks, check for pending network operations, * then run those operations. There can be a lot of I/O operations so this * could take some time to run. In general it should not be called from things like * GUI threads. * */ public void select() { select(0); } /** * This is the same as the {@link #select()} but it allows you to set a delay. * This delay is the time to wait for socket operations to happen. It will * block the calling thread for up to this amount of time, but it could be less * if any network operation happens (including another thread adding a client/server). * * * @param delay Max time in milliseconds to block for. */ public void select(final int delay) { ArgumentVerifier.assertNotNegative(delay, "delay"); checkRunning(); long startTime = delay == 0 ? -1 : Clock.accurateForwardProgressingMillis(); do { if (wakeUp) { break; } try { commonSelector.selectNow(); //We have to do this before we tick for windows localNoThreadScheduler.tick(null); commonSelector.select(Math.min(delay, 50)); if(isRunning()) { for(final SelectionKey key: commonSelector.selectedKeys()) { try { if(key.isAcceptable()) { doServerAccept(servers.get(key.channel())); } else { final Client tmpClient = clients.get(key.channel()); if(key.isConnectable() && tmpClient != null) { doClientConnect(tmpClient, commonSelector); key.cancel(); //Stupid windows bug here. setClientOperations(tmpClient); } else { if (key.isReadable()) { if(tmpClient != null){ doClientRead(tmpClient, commonSelector); } else { final Server server = servers.get(key.channel()); if(server != null && server.getServerType() == WireProtocol.UDP) { server.acceptChannel((DatagramChannel)server.getSelectableChannel()); } } } if(key.isWritable()) { if(tmpClient != null){ doClientWrite(tmpClient, commonSelector); } else { final Server server = servers.get(key.channel()); if(server != null) { if(server instanceof UDPServer) { UDPServer us = (UDPServer) server; stats.addWrite(us.doWrite()); setUDPServerOperations(us, true); } } } } } } } catch(CancelledKeyException e) { //Key could be cancelled at any point, we dont really care about it. } } //Also for windows bug, canceled keys are not removed till we select again. //So we just have to at the end of the loop. commonSelector.selectNow(); localNoThreadScheduler.tick(null); } } catch (IOException e) { //There is really nothing to do here but try again, usually this is because of shutdown. } catch(ClosedSelectorException e) { //We do nothing here because the next loop should not happen now. } catch (NullPointerException e) { //There is a bug in some JVMs around this where the select() can throw an NPE from native code. } } while ((delay == 0 ? Clock.lastKnownForwardProgressingMillis() : Clock.accurateForwardProgressingMillis()) - startTime <= delay && isRunning()); wakeUp = false; } @Override public SubmitterExecutor getExecutorFor(final Object obj) { return localNoThreadScheduler; } }
package ru.r2cloud.jradio.blocks; import java.io.IOException; import java.util.UUID; import ru.r2cloud.jradio.AbstractTaggedStream; import ru.r2cloud.jradio.ByteInput; import ru.r2cloud.jradio.Tag; public class CorrelateAccessCodeTag extends AbstractTaggedStream implements ByteInput { private ByteInput input; private long dataRegister = 0; private long mask = 0; private int threshold; private int length = 0; private long accessCode; private String d_key; private String blockId; private long abs_out_sample_cnt = 0; private boolean soft; public CorrelateAccessCodeTag(ByteInput input, int threshold, String key, String access_code) { this(input, threshold, key, access_code, false); } public CorrelateAccessCodeTag(ByteInput input, int threshold, String key, String access_code, boolean soft) { this.input = input; this.threshold = threshold; this.d_key = key; this.blockId = UUID.randomUUID().toString(); this.soft = soft; setAccessCode(access_code); } private void setAccessCode(String accessCodeBinary) { length = accessCodeBinary.length(); // # of bytes in string if (length > 64) { throw new IllegalArgumentException("access code with length: " + length + " is unsupported"); } // set len bottom bits to 1. mask = (~0L >>> (64 - length)); accessCode = 0; for (int i = 0; i < length; i++) { accessCode = (accessCode << 1) | (Byte.valueOf(String.valueOf(accessCodeBinary.charAt(i))) & 1); } } @Override public byte readByte() throws IOException { byte result = input.readByte(); byte toCheck; if (soft) { // make hard for correlation, but leave stream soft if ((result & 0xFF) > 127) { toCheck = 1; } else { toCheck = 0; } } else { toCheck = result; } long wrong_bits = 0; long nwrong = threshold + 1; wrong_bits = (dataRegister ^ accessCode) & mask; nwrong = calc(wrong_bits); // shift in new data dataRegister = (dataRegister << 1) | (toCheck & 0x1); if (nwrong <= threshold) { Tag tag = new Tag(); tag.setStreamId(0); tag.setSample(abs_out_sample_cnt); tag.setKey(d_key); tag.setValue(String.valueOf(nwrong)); tag.setBlockId(blockId); addTag(tag); } abs_out_sample_cnt++; return result; } private static long calc(long value) { int retVal = (int) (value & 0x00000000FFFFFFFFl); retVal = (retVal & 0x55555555) + (retVal >> 1 & 0x55555555); retVal = (retVal & 0x33333333) + (retVal >> 2 & 0x33333333); retVal = (retVal + (retVal >> 4)) & 0x0F0F0F0F; retVal = (retVal + (retVal >> 8)); retVal = (retVal + (retVal >> 16)) & 0x0000003F; long retVal64 = retVal; // retVal = valueVector[1]; retVal = (int) ((value & 0xFFFFFFFF00000000l) >> 31); retVal = (retVal & 0x55555555) + (retVal >> 1 & 0x55555555); retVal = (retVal & 0x33333333) + (retVal >> 2 & 0x33333333); retVal = (retVal + (retVal >> 4)) & 0x0F0F0F0F; retVal = (retVal + (retVal >> 8)); retVal = (retVal + (retVal >> 16)) & 0x0000003F; retVal64 += retVal; return retVal64; } @Override public void close() throws IOException { input.close(); } }
/** @@author A0142130A **/ package seedu.taskell.logic.commands; import seedu.taskell.commons.core.EventsCenter; import seedu.taskell.commons.events.ui.DisplayListChangedEvent; import seedu.taskell.model.History; import seedu.taskell.model.HistoryManager; /** Lists a list of previous commands available for Undo operation * */ public class ViewHistoryCommand extends Command { public static final String COMMAND_WORD_1 = "history"; public static final String COMMAND_WORD_2 = "hist"; public static final String MESSAGE_SUCCESS = "Listed all commands available for undo."; public static final String MESSAGE_UNSUCCESSFUL = "Error displaying history"; private static ViewHistoryCommand self; public ViewHistoryCommand() {} public static ViewHistoryCommand getInstance() { if (self == null) { self = new ViewHistoryCommand(); } return self; } @Override public CommandResult execute() { try { indicateDisplayListChanged(); } catch (Exception e) { return new CommandResult(MESSAGE_UNSUCCESSFUL); } return new CommandResult(MESSAGE_SUCCESS); } public void indicateDisplayListChanged() { EventsCenter.getInstance().post( new DisplayListChangedEvent(history.getListCommandText())); } }
package techreborn.blocks.storage.item; import net.minecraft.block.BlockState; import net.minecraft.block.Material; import net.minecraft.block.entity.BlockEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.MiningToolItem; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import reborncore.api.blockentity.IMachineGuiHandler; import reborncore.common.blocks.BlockMachineBase; import reborncore.common.util.RebornInventory; import reborncore.common.util.WorldUtils; import techreborn.blockentity.GuiType; import techreborn.blockentity.storage.item.StorageUnitBaseBlockEntity; import techreborn.init.TRContent; import techreborn.items.tool.WrenchItem; public class StorageUnitBlock extends BlockMachineBase { public final TRContent.StorageUnit unitType; public StorageUnitBlock(TRContent.StorageUnit unitType) { super((Settings.of(unitType.name.equals("buffer") || unitType.name.equals("crude") ? Material.WOOD : Material.METAL).strength(2.0F, 2.0F))); this.unitType = unitType; } @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new StorageUnitBaseBlockEntity(pos, state, unitType); } @Override public ActionResult onUse(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockHitResult hitResult) { if (unitType == TRContent.StorageUnit.CREATIVE || worldIn.isClient) { return super.onUse(state, worldIn, pos, playerIn, hand, hitResult); } final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) worldIn.getBlockEntity(pos); if (storageEntity == null) { return super.onUse(state, worldIn, pos, playerIn, hand, hitResult); } if (storageEntity.isFull()) { return super.onUse(state, worldIn, pos, playerIn, hand, hitResult); } ItemStack stackInHand = playerIn.getStackInHand(Hand.MAIN_HAND); if (!storageEntity.canAcceptStack(stackInHand)) { return super.onUse(state, worldIn, pos, playerIn, hand, hitResult); } Item itemInHand = stackInHand.getItem(); if (itemInHand instanceof WrenchItem){ return super.onUse(state, worldIn, pos, playerIn, hand, hitResult); } // Add item which is the same type (in users inventory) into storage for (int i = 0; i < playerIn.getInventory().size() && !storageEntity.isFull(); i++) { ItemStack curStack = playerIn.getInventory().getStack(i); if (curStack.getItem() == itemInHand) { playerIn.getInventory().setStack(i, storageEntity.processInput(curStack)); } } return ActionResult.SUCCESS; } @Override public void onBlockBreakStart(BlockState state, World world, BlockPos pos, PlayerEntity player) { super.onBlockBreakStart(state, world, pos, player); if (world.isClient) return; final StorageUnitBaseBlockEntity storageEntity = (StorageUnitBaseBlockEntity) world.getBlockEntity(pos); if (storageEntity == null) { return; } if (storageEntity.isEmpty()) { return; } ItemStack stackInHand = player.getStackInHand(Hand.MAIN_HAND); // Let's assume that player is trying to break this block, rather than get an item from storage if (stackInHand.getItem() instanceof MiningToolItem) { return; } RebornInventory<StorageUnitBaseBlockEntity> inventory = storageEntity.getInventory(); ItemStack out = inventory.getStack(StorageUnitBaseBlockEntity.OUTPUT_SLOT); // Full stack if sneaking if (player.isSneaking()) { WorldUtils.dropItem(out, world, player.getBlockPos()); out.setCount(0); } else { ItemStack dropStack = out.copy(); dropStack.setCount(1); WorldUtils.dropItem(dropStack, world, player.getBlockPos()); out.decrement(1); } inventory.setHashChanged(); } @Override public IMachineGuiHandler getGui() { return GuiType.STORAGE_UNIT; } }
package uk.ac.ox.oucs.erewhon.oxpq; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Calendar; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.Map.Entry; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.oucs.gaboto.GabotoConfiguration; import org.oucs.gaboto.GabotoFactory; import org.oucs.gaboto.transformation.EntityPoolTransformer; import org.oucs.gaboto.transformation.GeoJSONPoolTransfomer; import org.oucs.gaboto.transformation.JSONPoolTransformer; import org.oucs.gaboto.transformation.KMLPoolTransformer; import org.oucs.gaboto.transformation.RDFPoolTransformerFactory; import org.oucs.gaboto.model.Gaboto; import org.oucs.gaboto.model.GabotoSnapshot; import org.oucs.gaboto.model.ResourceDoesNotExistException; import org.oucs.gaboto.model.query.GabotoQuery; import org.oucs.gaboto.model.query.UnsupportedQueryFormatException; import org.oucs.gaboto.node.GabotoEntity; import org.oucs.gaboto.node.pool.EntityPool; import org.oucs.gaboto.node.pool.EntityPoolConfiguration; import org.oucs.gaboto.time.TimeInstant; import org.oucs.gaboto.vocabulary.OxPointsVocab; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; public class OxPointsQueryServlet extends HttpServlet { private static final long serialVersionUID = 4155078999145248554L; private static Logger logger = Logger.getLogger(OxPointsQueryServlet.class.getName()); private static Gaboto gaboto; private static GabotoSnapshot snapshot; private static GabotoConfiguration config; private static Calendar startTime; public void init() { logger.debug("init"); config = GabotoConfiguration.fromConfigFile(); GabotoFactory.init(config); gaboto = GabotoFactory.getEmptyInMemoryGaboto(); gaboto.read(getResourceOrDie("graphs.rdf"), getResourceOrDie("cdg.rdf")); gaboto.recreateTimeDimensionIndex(); startTime = Calendar.getInstance(); snapshot = gaboto.getSnapshot(TimeInstant.from(startTime)); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { outputPool(request, response); } catch (ResourceNotFoundException e) { try { response.sendError(404, e.getMessage()); } catch (IOException e1) { error(request, response, new AnticipatedException("Problem reporting error: " + e.getMessage(),e1)); } } catch (AnticipatedException e) { error(request, response, e); } } void error(HttpServletRequest request, HttpServletResponse response, AnticipatedException exception) { response.setContentType("text/html"); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { throw new RuntimeException(e); } out.println("<html><head><title>OxPoints Anticipated Error</title></head>"); out.println("<body>"); out.println("<h2>OxPoints Anticipated Error</h2>"); out.println("<h3>" + exception.getMessage() + "</h3>"); out.println("<p>An anticipated error has occured in the application"); out.println("that runs this website, please contact <a href='mailto:"); out.println(getSysAdminEmail() + "'>" + getSysAdminName() + "</a>"); out.println(", with the information given below.</p>"); out.println("<h3> Invoked with " + request.getRequestURL().toString() + "</h3>"); if (request.getQueryString() != null) out.println("<h3> query " + request.getQueryString() + "</h3>"); out.println("<h4><font color='red'><pre>"); exception.printStackTrace(out); out.println("</pre></font></h4>"); out.println("</body></html>"); } private String getSysAdminEmail() { return "Tim.Pizey@oucs.ox.ac.uk"; } private String getSysAdminName() { return "Tim Pizey"; } void outputPool(HttpServletRequest request, HttpServletResponse response) throws ResourceNotFoundException { Query query = Query.fromRequest(request); switch (query.getReturnType()) { case META_TIMESTAMP: try { response.getWriter().write(new Long(startTime.getTimeInMillis()).toString()); } catch (IOException e) { throw new RuntimeException(e); } return; case META_TYPES: output(snapshot.getGaboto().getConfig().getGabotoOntologyLookup().getRegisteredEntityClassesAsClassNames(), query, response); return; case ALL: output(EntityPool.createFrom(snapshot), query, response); return; case INDIVIDUAL: EntityPool pool = new EntityPool(gaboto, snapshot); establishParticipantUri(query); pool.addEntity(snapshot.loadEntity(query.getUri())); output(pool, query, response); return; case TYPE_COLLECTION: output(loadPoolWithEntitiesOfType(query.getType()), query, response); return; case PROPERTY_ANY: // value null output(loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue()), query, response); return; case PROPERTY_SUBJECT: EntityPool subjectPool = null; if (requiresResource(query.getRequestedProperty())) { establishParticipantUri(query); if (query.getUri() == null) throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() + " and value " + query.getParticipantCode()); GabotoEntity object = snapshot.loadEntity(query.getUri()); EntityPool creationPool = EntityPool.createFrom(snapshot); System.err.println("CreationPool size " + creationPool.size()); object.setCreatedFromPool(creationPool); subjectPool = loadPoolWithActiveParticipants(object, query.getRequestedProperty()); } else { subjectPool = loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue()); } output(subjectPool, query, response); return; case PROPERTY_OBJECT: establishParticipantUri(query); if (query.getUri() == null) throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() + " and value " + query.getParticipantCode()); GabotoEntity subject = snapshot.loadEntity(query.getUri()); EntityPool objectPool = loadPoolWithPassiveParticipants(subject, query.getRequestedProperty()); output(objectPool, query, response); return; case NOT_FILTERED_TYPE_COLLECTION: EntityPool p = loadPoolWithEntitiesOfType(query.getType()); EntityPool p2 = loadPoolWithEntitiesOfType(query.getType()); for (GabotoEntity e : p.getEntities()) if (e.getPropertyValue(query.getNotProperty(), false, false) != null) p2.removeEntity(e); output(p2, query, response); return; default: throw new RuntimeException("Fell through case with value " + query.getReturnType()); } } private EntityPool loadPoolWithEntitiesOfProperty(Property prop, String value) { System.err.println("loadPoolWithEntitiesOfProperty" + prop + ":" + value); if (prop == null) throw new NullPointerException(); EntityPool pool = null; if (value == null) { pool = snapshot.loadEntitiesWithProperty(prop); } else { String values[] = value.split("[|]"); for (String v : values) { if (requiresResource(prop)) { Resource r = getResource(v); System.err.println("About to load " + prop + " with value " + r); pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, r)); } else { pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, v)); } } } return pool; } @SuppressWarnings("unchecked") private EntityPool loadPoolWithActiveParticipants(GabotoEntity passiveParticipant, Property prop) { if (prop == null) throw new NullPointerException(); EntityPool pool = new EntityPool(gaboto, snapshot); System.err.println("loadPoolWithActiveParticipants" + passiveParticipant.getUri() + " prop " + prop + " which "); Set<Entry<String, Object>> passiveProperties = passiveParticipant.getAllPassiveProperties().entrySet(); for (Entry<String, Object> entry : passiveProperties) { if (entry.getKey().equals(prop.getURI())) { if (entry.getValue() != null) { if (entry.getValue() instanceof HashSet) { HashSet<Object> them = (HashSet<Object>)entry.getValue(); for (Object e : them) { if (e instanceof GabotoEntity) { System.err.println("Adding set member :" + e); pool.add((GabotoEntity)e); } } } else if (entry.getValue() instanceof GabotoEntity) { System.err.println("Adding individual :" + entry.getKey()); pool.add((GabotoEntity)entry.getValue()); } else { System.err.println("Ignoring:" + entry.getKey()); } } else { System.err.println("Ignoring:" + entry.getKey()); } } else { System.err.println("Ignoring:" + entry.getKey()); } } return pool; } private void establishParticipantUri(Query query) throws ResourceNotFoundException { if (query.needsCodeLookup()) { System.err.println("need"); Property coding = Query.getPropertyFromAbreviation(query.getParticipantCoding()); System.err.println("establishUri" + query.getParticipantCode()); EntityPool objectPool = snapshot.loadEntitiesWithProperty(coding, query.getParticipantCode()); boolean found = false; for (GabotoEntity objectKey: objectPool) { if (found) throw new RuntimeException("Found two:" + objectKey); query.setParticipantUri(objectKey.getUri()); found = true; } } if (query.getParticipantUri() == null) throw new ResourceNotFoundException("No resource found with coding " + query.getParticipantCoding() + " and value " + query.getParticipantCode()); } @SuppressWarnings("unchecked") private EntityPool loadPoolWithPassiveParticipants(GabotoEntity activeParticipant, Property prop) { if (prop == null) throw new NullPointerException(); EntityPool pool = new EntityPool(gaboto, snapshot); System.err.println("loadPoolWithPassiveParticipants" + activeParticipant.getUri() + " prop " + prop + " which "); Set<Entry<String, Object>> directProperties = activeParticipant.getAllDirectProperties().entrySet(); for (Entry<String, Object> entry : directProperties) { if (entry.getKey().equals(prop.getURI())) { if (entry.getValue() != null) { if (entry.getValue() instanceof HashSet) { HashSet<Object> them = (HashSet<Object>)entry.getValue(); for (Object e : them) { if (e instanceof GabotoEntity) { pool.add((GabotoEntity)e); } } } else if (entry.getValue() instanceof GabotoEntity) { pool.add((GabotoEntity)entry.getValue()); } else { System.err.println("Ignoring:" + entry.getKey()); } } else { System.err.println("Ignoring:" + entry.getKey()); } } else { System.err.println("Ignoring:" + entry.getKey()); } } return pool; } private EntityPool becomeOrAdd(EntityPool pool, EntityPool poolToAdd) { System.err.println("BecomeOrAdd" + pool); if (poolToAdd == null) throw new NullPointerException(); if (pool == null) { return poolToAdd; } else { for (GabotoEntity e : poolToAdd.getEntities()) { pool.addEntity(e); } return pool; } } private Resource getResource(String v) { String vUri = v; if (!vUri.startsWith(config.getNSData())) vUri = config.getNSData() + v; try { return snapshot.getResource(vUri); } catch (ResourceDoesNotExistException e) { throw new RuntimeException(e); } } private boolean requiresResource(Property property) { if (property.getLocalName().endsWith("subsetOf")) { return true; } else if (property.getLocalName().endsWith("physicallyContainedWithin")) { return true; } else if (property.getLocalName().endsWith("hasPrimaryPlace")) { return true; } else if (property.getLocalName().endsWith("occupies")) { return true; } else if (property.getLocalName().endsWith("associatedWith")) { return true; } return false; } private EntityPool loadPoolWithEntitiesOfType(String type) { System.err.println("Type:" + type); String types[] = type.split("[|]"); EntityPoolConfiguration conf = new EntityPoolConfiguration(snapshot); for (String t : types) { if (!snapshot.getGaboto().getConfig().getGabotoOntologyLookup().isValidName(t)) throw new IllegalArgumentException("Found no URI matching type " + t); String typeURI = OxPointsVocab.NS + t; conf.addAcceptedType(typeURI); } return EntityPool.createFrom(conf); } private void output(Collection<String> them, Query query, HttpServletResponse response) { try { if (query.getFormat().equals("txt")) { boolean doneOne = false; for (String member : them) { if (doneOne) response.getWriter().write("|"); response.getWriter().write(member); doneOne = true; } response.getWriter().write("\n"); } else if (query.getFormat().equals("csv")) { boolean doneOne = false; for (String member : them) { if (doneOne) response.getWriter().write(","); response.getWriter().write(member); doneOne = true; } response.getWriter().write("\n"); } else if (query.getFormat().equals("js")) { boolean doneOne = false; response.getWriter().write("var oxpointsTypes = ["); for (String member : them) { if (doneOne) response.getWriter().write(","); response.getWriter().write("'"); response.getWriter().write(member); response.getWriter().write("'"); doneOne = true; } response.getWriter().write("];\n"); } else if (query.getFormat().equals("xml")) { response.getWriter().write("<c>"); for (String member : them) { response.getWriter().write("<i>"); response.getWriter().write(member); response.getWriter().write("</i>"); } response.getWriter().write("</c>"); response.getWriter().write("\n"); } else throw new AnticipatedException("Unexpected format " + query.getFormat()); } catch (IOException e) { throw new RuntimeException(e); } } private void output(EntityPool pool, Query query, HttpServletResponse response) { System.err.println("Pool has " + pool.getSize() + " elements"); String output = ""; if (query.getFormat().equals("kml")) { output = createKml(pool, query); response.setContentType("application/vnd.google-earth.kml+xml"); } else if (query.getFormat().equals("json") || query.getFormat().equals("js")) { JSONPoolTransformer transformer = new JSONPoolTransformer(); transformer.setNesting(query.getJsonDepth()); output = transformer.transform(pool); if (query.getFormat().equals("js")) { output = query.getJsCallback() + "(" + output + ");"; } response.setContentType("text/javascript"); } else if (query.getFormat().equals("gjson")) { GeoJSONPoolTransfomer transformer = new GeoJSONPoolTransfomer(); if (query.getArc() != null) { transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI()); } if (query.getOrderBy() != null) { transformer.setOrderBy(query.getOrderByProperty().getURI()); } transformer.setDisplayParentName(query.getDisplayParentName()); output += transformer.transform(pool); if (query.getJsCallback() != null) output = query.getJsCallback() + "(" + output + ");"; response.setContentType("text/javascript"); } else if (query.getFormat().equals("xml")) { EntityPoolTransformer transformer; try { transformer = RDFPoolTransformerFactory.getRDFPoolTransformer(GabotoQuery.FORMAT_RDF_XML_ABBREV); output = transformer.transform(pool); } catch (UnsupportedQueryFormatException e) { throw new IllegalArgumentException(e); } response.setContentType("text/xml"); } else if (query.getFormat().equals("txt")) { try { for (GabotoEntity entity: pool.getEntities()) { response.getWriter().write(entity.toString() + "\n"); for (Entry<String, Object> entry : entity.getAllDirectProperties().entrySet()) { if (entry.getValue() != null) response.getWriter().write(" " + entry.getKey() + " : " + entry.getValue() + "\n"); } } } catch (IOException e) { throw new RuntimeException(e); } response.setContentType("text/plain"); } else { output = runGPSBabel(createKml(pool, query), "kml", query.getFormat()); if (output.equals("")) throw new RuntimeException("No output created by GPSBabel"); } // System.err.println("output:" + output + ":"); try { response.getWriter().write(output); } catch (IOException e) { throw new RuntimeException(e); } } private String createKml(EntityPool pool, Query query) { String output; KMLPoolTransformer transformer = new KMLPoolTransformer(); if (query.getArc() != null) { transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI()); } if (query.getOrderBy() != null) { transformer.setOrderBy(query.getOrderByProperty().getURI()); } transformer.setDisplayParentName(query.getDisplayParentName()); output = transformer.transform(pool); return output; } /** * @param input * A String, normally kml * @param formatIn * format name, other than kml * @param formatOut * what you want out * @return the reformatted String */ public static String runGPSBabel(String input, String formatIn, String formatOut) { // '/usr/bin/gpsbabel -i kml -o ' . $format . ' -f ' . $In . ' -F ' . $Out; if (formatIn == null) formatIn = "kml"; if (formatOut == null) throw new IllegalArgumentException("Missing output format for GPSBabel"); OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; String output = ""; String command = "/usr/bin/gpsbabel -i " + formatIn + " -o " + formatOut + " -f - -F -"; System.err.println("GPSBabel command:" + command); Process process; try { process = Runtime.getRuntime().exec(command, null, null); } catch (IOException e) { throw new RuntimeException(e); } try { stdin = process.getOutputStream(); stdout = process.getInputStream(); stderr = process.getErrorStream(); try { stdin.write(input.getBytes()); stdin.flush(); stdin.close(); } catch (IOException e) { // clean up if any output in stderr BufferedReader errBufferedReader = new BufferedReader(new InputStreamReader(stderr)); String stderrString = ""; String stderrLine = null; try { while ((stderrLine = errBufferedReader.readLine()) != null) { System.err.println("[Stderr Ex] " + stderrLine); stderrString += stderrLine; } errBufferedReader.close(); } catch (IOException e2) { throw new RuntimeException("Command " + command + " stderr reader failed:" + e2); } throw new RuntimeException("Command " + command + " gave error:\n" + stderrString); } BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout)); String line; try { while ((line = brCleanUp.readLine()) != null) { System.out.println("[Stdout] " + line); output += line; } brCleanUp.close(); } catch (IOException e) { throw new RuntimeException(e); } // clean up if any output in stderr brCleanUp = new BufferedReader(new InputStreamReader(stderr)); String stderrString = ""; try { while ((line = brCleanUp.readLine()) != null) { System.err.println("[Stderr] " + line); stderrString += line; } brCleanUp.close(); } catch (IOException e) { throw new RuntimeException(e); } if (!stderrString.equals("")) throw new RuntimeException("Command " + command + " gave error:\n" + stderrString); } finally { process.destroy(); } return output; } private InputStream getResourceOrDie(String fileName) { String resourceName = fileName; InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); if (is == null) throw new NullPointerException("File " + resourceName + " cannot be loaded"); return is; } }
package xdi2.connector.allfiled.mapping; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import xdi2.core.ContextNode; import xdi2.core.Graph; import xdi2.core.exceptions.Xdi2RuntimeException; import xdi2.core.features.dictionary.Dictionary; import xdi2.core.features.equivalence.Equivalence; import xdi2.core.features.multiplicity.Multiplicity; import xdi2.core.impl.memory.MemoryGraphFactory; import xdi2.core.io.XDIReaderRegistry; import xdi2.core.xri3.XDI3Segment; public class AllfiledMapping { public static final XDI3Segment XRI_S_ALLFILED_CONTEXT = XDI3Segment.create("+(https://allfiled.com/)"); private static final Logger log = LoggerFactory.getLogger(AllfiledMapping.class); private static AllfiledMapping instance; private Graph mappingGraph; public AllfiledMapping() { this.mappingGraph = MemoryGraphFactory.getInstance().openGraph(); try { XDIReaderRegistry.getAuto().read(this.mappingGraph, AllfiledMapping.class.getResourceAsStream("mapping.xdi")); } catch (Exception ex) { throw new Xdi2RuntimeException(ex.getMessage(), ex); } } public static AllfiledMapping getInstance() { if (instance == null) instance = new AllfiledMapping(); return instance; } /** * Converts a Allfiled data XRI to a native Allfiled category identifier. * Example: +(personal)+(person)$!(+(forename)) --> personal */ public String allfiledDataXriToAllfiledCategoryIdentifier(XDI3Segment allfiledDataXri) { if (allfiledDataXri == null) throw new NullPointerException(); // convert String allfiledCategoryIdentifier = Dictionary.instanceXriToNativeIdentifier(Multiplicity.baseArcXri(allfiledDataXri.getSubSegment(0))); // done if (log.isDebugEnabled()) log.debug("Converted " + allfiledDataXri + " to " + allfiledCategoryIdentifier); return allfiledCategoryIdentifier; } /** * Converts a Allfiled data XRI to a native Allfiled file identifier. * Example: +(personal)+(person)$!(+(forename)) --> person */ public String allfiledDataXriToAllfiledFileIdentifier(XDI3Segment allfiledDataXri) { if (allfiledDataXri == null) throw new NullPointerException(); // convert String allfiledFileIdentifier = Dictionary.instanceXriToNativeIdentifier(Multiplicity.baseArcXri(allfiledDataXri.getSubSegment(1))); // done if (log.isDebugEnabled()) log.debug("Converted " + allfiledDataXri + " to " + allfiledFileIdentifier); return allfiledFileIdentifier; } /** * Converts a Allfiled data XRI to a native Allfiled field identifier. * Example: +(personal)+(person)$!(+(forename)) --> forename */ public String allfiledDataXriToAllfiledFieldIdentifier(XDI3Segment allfiledDataXri) { if (allfiledDataXri == null) throw new NullPointerException(); // convert String allfiledFieldIdentifier = Dictionary.instanceXriToNativeIdentifier(Multiplicity.baseArcXri(allfiledDataXri.getSubSegment(2))); // done if (log.isDebugEnabled()) log.debug("Converted " + allfiledDataXri + " to " + allfiledFieldIdentifier); return allfiledFieldIdentifier; } /** * Maps and converts a Allfiled data XRI to an XDI data XRI. * Example: +(personal)+(person)$!(+(forename)) --> +first$!(+name) */ public XDI3Segment allfiledDataXriToXdiDataXri(XDI3Segment allfiledDataXri) { if (allfiledDataXri == null) throw new NullPointerException(); // convert StringBuffer buffer1 = new StringBuffer(); for (int i=0; i<allfiledDataXri.getNumSubSegments(); i++) { buffer1.append(Dictionary.instanceXriToDictionaryXri(Multiplicity.baseArcXri(allfiledDataXri.getSubSegment(i)))); } // map XDI3Segment allfiledDataDictionaryXri = XDI3Segment.create("" + XRI_S_ALLFILED_CONTEXT + buffer1.toString()); ContextNode allfiledDataDictionaryContextNode = this.mappingGraph.findContextNode(allfiledDataDictionaryXri, false); if (allfiledDataDictionaryContextNode == null) return null; ContextNode xdiDataDictionaryContextNode = Equivalence.getReferenceContextNode(allfiledDataDictionaryContextNode); XDI3Segment xdiDataDictionaryXri = xdiDataDictionaryContextNode.getXri(); // convert StringBuilder buffer2 = new StringBuilder(); for (int i=0; i<xdiDataDictionaryXri.getNumSubSegments(); i++) { if (i + 1 < xdiDataDictionaryXri.getNumSubSegments()) { buffer2.append(Multiplicity.entitySingletonArcXri(Dictionary.dictionaryXriToInstanceXri(xdiDataDictionaryXri.getSubSegment(i)))); } else { buffer2.append(Multiplicity.attributeSingletonArcXri(Dictionary.dictionaryXriToInstanceXri(xdiDataDictionaryXri.getSubSegment(i)))); } } XDI3Segment xdiDataXri = XDI3Segment.create(buffer2.toString()); // done if (log.isDebugEnabled()) log.debug("Mapped and converted " + allfiledDataXri + " to " + xdiDataXri); return xdiDataXri; } /** * Maps and converts an XDI data XRI to a Allfiled data XRI. * Example: +first$!(+name) --> +(personal)+(person)$!(+(forename)) */ public XDI3Segment xdiDataXriToAllfiledDataXri(XDI3Segment xdiDataXri) { if (xdiDataXri == null) throw new NullPointerException(); // convert StringBuffer buffer1 = new StringBuffer(); for (int i=0; i<xdiDataXri.getNumSubSegments(); i++) { buffer1.append(Dictionary.instanceXriToDictionaryXri(Multiplicity.baseArcXri(xdiDataXri.getSubSegment(i)))); } // map XDI3Segment xdiDataDictionaryXri = XDI3Segment.create(buffer1.toString()); ContextNode xdiDataDictionaryContextNode = this.mappingGraph.findContextNode(xdiDataDictionaryXri, false); if (xdiDataDictionaryContextNode == null) return null; ContextNode allfiledDataDictionaryContextNode = Equivalence.getIncomingReferenceContextNodes(xdiDataDictionaryContextNode).next(); XDI3Segment allfiledDataDictionaryXri = allfiledDataDictionaryContextNode.getXri(); // convert StringBuilder buffer2 = new StringBuilder(); for (int i=1; i<allfiledDataDictionaryXri.getNumSubSegments(); i++) { if (i + 1 < allfiledDataDictionaryXri.getNumSubSegments()) { buffer2.append(Multiplicity.entitySingletonArcXri(Dictionary.dictionaryXriToInstanceXri(allfiledDataDictionaryXri.getSubSegment(i)))); } else { buffer2.append(Multiplicity.attributeSingletonArcXri(Dictionary.dictionaryXriToInstanceXri(allfiledDataDictionaryXri.getSubSegment(i)))); } } XDI3Segment allfiledDataXri = XDI3Segment.create(buffer2.toString()); // done if (log.isDebugEnabled()) log.debug("Mapped and converted " + xdiDataXri + " to " + allfiledDataXri); return allfiledDataXri; } /* * Getters and setters */ public Graph getMappingGraph() { return this.mappingGraph; } public void setMappingGraph(Graph mappingGraph) { this.mappingGraph = mappingGraph; } }
package zmaster587.advancedRocketry.util; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import zmaster587.advancedRocketry.AdvancedRocketry; import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks; import zmaster587.advancedRocketry.api.AreaBlob; import zmaster587.advancedRocketry.api.Configuration; import zmaster587.advancedRocketry.api.util.IBlobHandler; import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler; import zmaster587.libVulpes.util.BlockPosition; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class AtmosphereBlob extends AreaBlob implements Runnable { static ThreadPoolExecutor pool = (Configuration.atmosphereHandleBitMask & 1) == 1 ? new ThreadPoolExecutor(3, 16, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2)) : null; boolean executing; BlockPosition blockPos; List<AreaBlob> nearbyBlobs; public AtmosphereBlob(IBlobHandler blobHandler) { super(blobHandler); executing = false; } @Override public void removeBlock(int x, int y, int z) { BlockPosition blockPos = new BlockPosition(x, y, z); graph.remove(blockPos); graph.contains(blockPos); for(ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { BlockPosition newBlock = blockPos.getPositionAtOffset(direction.offsetX, direction.offsetY, direction.offsetZ); if(graph.contains(newBlock) && !graph.doesPathExist(newBlock, blobHandler.getRootPosition())) runEffectOnWorldBlocks(blobHandler.getWorld(), graph.removeAllNodesConnectedTo(newBlock)); } } @Override public boolean isPositionAllowed(World world, BlockPosition pos, List<AreaBlob> otherBlobs) { for(AreaBlob blob : otherBlobs) { if(blob.contains(pos) && blob != this) return false; } return !SealableBlockHandler.INSTANCE.isBlockSealed(world, pos); } @Override public void addBlock(BlockPosition blockPos, List<AreaBlob> otherBlobs) { if(blobHandler.canFormBlob()) { if(!this.contains(blockPos)) { if(!executing) { this.nearbyBlobs = otherBlobs; this.blockPos = blockPos; executing = true; if((Configuration.atmosphereHandleBitMask & 1) == 1) pool.execute(this); else this.run(); } } } } @Override public void run() { Stack<BlockPosition> stack = new Stack<BlockPosition>(); stack.push(blockPos); final int maxSize = (Configuration.atmosphereHandleBitMask & 2) != 0 ? (int)(Math.pow(this.getBlobMaxRadius(), 3)*((4f/3f)*Math.PI)) : this.getBlobMaxRadius(); final HashSet<BlockPosition> addableBlocks = new HashSet<BlockPosition>(); //Breadth first search; non recursive while(!stack.isEmpty()) { BlockPosition stackElement = stack.pop(); addableBlocks.add(stackElement); for(ForgeDirection dir2 : ForgeDirection.VALID_DIRECTIONS) { BlockPosition searchNextPosition = stackElement.getPositionAtOffset(dir2.offsetX, dir2.offsetY, dir2.offsetZ); //Don't path areas we have already scanned if(!graph.contains(searchNextPosition) && !addableBlocks.contains(searchNextPosition)) { boolean sealed; try { sealed = !isPositionAllowed(blobHandler.getWorld(), searchNextPosition, nearbyBlobs);//SealableBlockHandler.INSTANCE.isBlockSealed(blobHandler.getWorld(), searchNextPosition); if(!sealed) { if(((Configuration.atmosphereHandleBitMask & 2) == 0 && searchNextPosition.getDistance(this.getRootPosition()) <= maxSize) || ((Configuration.atmosphereHandleBitMask & 2) != 0 && addableBlocks.size() <= maxSize)) { stack.push(searchNextPosition); addableBlocks.add(searchNextPosition); } else { //Failed to seal, void clearBlob(); executing = false; return; } } } catch (Exception e){ //Catches errors with additional information AdvancedRocketry.logger.info("Error: AtmosphereBlob has failed to form correctly due to an error. \nCurrentBlock: " + stackElement + "\tNextPos: " + searchNextPosition + "\tDir: " + dir2 + "\tStackSize: " + stack.size()); e.printStackTrace(); //Failed to seal, void clearBlob(); executing = false; return; } } } } //only one instance can editing this at a time because this will not run again b/c "worker" is not null synchronized(graph) { for(BlockPosition blockPos2 : addableBlocks) { super.addBlock(blockPos2, nearbyBlobs); } } executing = false; } /** * @param world * @param blocks Collection containing affected locations */ protected void runEffectOnWorldBlocks(World world, Collection<BlockPosition> blocks) { if(!AtmosphereHandler.getOxygenHandler(world.provider.dimensionId).getDefaultAtmosphereType().allowsCombustion()) { List<BlockPosition> list; synchronized (graph) { list = new LinkedList<BlockPosition>(blocks); } for(BlockPosition pos : list) { Block block = world.getBlock(pos.x, pos.y, pos.z); if(block== Blocks.torch) { world.setBlock(pos.x, pos.y, pos.z, AdvancedRocketryBlocks.blockUnlitTorch); } else if(Configuration.torchBlocks.contains(block)) { EntityItem item = new EntityItem(world, pos.x, pos.y, pos.z, new ItemStack(block)); world.setBlockToAir(pos.x, pos.y, pos.z); world.spawnEntityInWorld(item); } } } } @Override public void clearBlob() { World world = blobHandler.getWorld(); runEffectOnWorldBlocks(world, getLocations()); super.clearBlob(); } public int getPressure() { return 100; } }
package pitt.search.semanticvectors; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Enumeration; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorSearcher; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.VectorUtils; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher{ private VectorStore queryVecStore; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract float getScore(float[] testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils) { this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList(); float score, threshold = -1; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Initialize result list if just starting. if (results.size() == 0) { ObjectVector firstElement = vecEnum.nextElement(); score = getScore(firstElement.getVector()); results.add(new SearchResult(score, firstElement)); continue; } // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } return results; } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(this.queryVector)) { System.err.println("Query vector is zero ... no results."); System.exit(-1); } } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using sparse cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosineSparse extends VectorSearcher { float[] queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosineSparse(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); float[] fullQueryVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, queryTerms); if (VectorUtils.isZeroVector(fullQueryVector)) { System.err.println("Query vector is zero ... no results."); System.exit(-1); } short[] sparseQueryVector = VectorUtils.floatVectorToSparseVector(fullQueryVector, 20); this.queryVector = VectorUtils.sparseVectorToFloatVector(sparseQueryVector, ObjectVector.vecLength); } public float getScore(float[] testVector) { //testVector = VectorUtils.getNormalizedVector(testVector); short[] sparseTestVector = VectorUtils.floatVectorToSparseVector(testVector, 40); testVector = VectorUtils.sparseVectorToFloatVector(sparseTestVector, ObjectVector.vecLength); return VectorUtils.scalarProduct(this.queryVector, testVector); } } /** * Class for searching a vector store using tensor product * similarity. The class takes a seed tensor as a training * example. This tensor should be entangled (a superposition of * several individual products A * B) for non-trivial results. */ static public class VectorSearcherTensorSim extends VectorSearcher { private float[][] trainingTensor; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherTensorSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); this.trainingTensor = VectorUtils.createZeroTensor(ObjectVector.vecLength); // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[][] trainingPair = VectorUtils.getOuterProduct(trainingVec1, trainingVec2); this.trainingTensor = VectorUtils.getTensorSum(trainingTensor, trainingPair); } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroTensor(trainingTensor)) { System.err.println("Tensor training relation is zero ... no results."); System.exit(-1); } this.trainingTensor = VectorUtils.getNormalizedTensor(trainingTensor); // This is an explicit way of taking a slice of the last i // terms. There may be a quicker way of doing this. String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { System.err.println("Query vector is zero ... no results."); System.exit(-1); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogous to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[][] testTensor = VectorUtils.getOuterProduct(this.partnerVector, testVector); return VectorUtils.getInnerProduct(this.trainingTensor, testTensor); } } /** * Class for searching a vector store using convolution similarity. * Interface is similar to that for VectorSearcherTensorSim. */ static public class VectorSearcherConvolutionSim extends VectorSearcher { private float[] trainingConvolution; private float[] partnerVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. This should be a list of one or more * tilde-separated training pairs, e.g., <code>paris~france * berlin~germany</code> followed by a list of one or more search * terms, e.g., <code>london birmingham</code>. */ public VectorSearcherConvolutionSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); this.trainingConvolution = new float[2 * ObjectVector.vecLength - 1]; for (int i = 0; i < 2 * ObjectVector.vecLength - 1; ++i) { this.trainingConvolution[i] = 0; } // Collect tensor training relations. int i = 0; while (queryTerms[i].indexOf("~") > 0) { System.err.println("Training pair: " + queryTerms[i]); String[] trainingTerms = queryTerms[i].split("~"); if (trainingTerms.length != 2) { System.err.println("Tensor training terms must be pairs split by individual" + " '~' character. Error with: '" + queryTerms[i] + "'"); } float[] trainingVec1 = queryVecStore.getVector(trainingTerms[0]); float[] trainingVec2 = queryVecStore.getVector(trainingTerms[1]); if (trainingVec1 != null && trainingVec2 != null) { float[] trainingPair = VectorUtils.getConvolutionFromVectors(trainingVec1, trainingVec2); for (int j = 0; j < 2 * ObjectVector.vecLength - 1; ++j) { this.trainingConvolution[j] += trainingPair[j]; } } ++i; } // Check to see that we got a non-zero training tensor before moving on. if (VectorUtils.isZeroVector(trainingConvolution)) { System.err.println("Convolution training relation is zero ... no results."); System.exit(-1); } this.trainingConvolution = VectorUtils.getNormalizedVector(trainingConvolution); String[] partnerTerms = new String[queryTerms.length - i]; for (int j = 0; j < queryTerms.length - i; ++j) { partnerTerms[j] = queryTerms[i + j]; } this.partnerVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, partnerTerms); if (VectorUtils.isZeroVector(this.partnerVector)) { System.err.println("Query vector is zero ... no results."); System.exit(-1); } } /** * @param testVector Vector being tested. * Scores are hopefully high when the relationship between queryVector * and testVector is analogoues to the relationship between rel1 and rel2. */ public float getScore(float[] testVector) { float[] testConvolution = VectorUtils.getConvolutionFromVectors(this.partnerVector, testVector); testConvolution = VectorUtils.getNormalizedVector(testConvolution); return VectorUtils.scalarProduct(this.trainingConvolution, testConvolution); } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<float[]> disjunctSpace; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctSpace = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } VectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { return VectorUtils.getSumScalarProduct(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<float[]> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctVectors = new ArrayList(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); float[] tmpVector = CompoundVectorBuilder.getQueryVector(queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ public float getScore(float[] testVector) { float score = -1; float max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = VectorUtils.scalarProduct(this.disjunctVectors.get(i), testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ static public class VectorSearcherPerm extends VectorSearcher { float[] theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) { super(queryVecStore, searchVecStore, luceneUtils); theAvg = pitt.search.semanticvectors.CompoundVectorBuilder.getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); } public float getScore(float[] testVector) { return VectorUtils.scalarProduct(theAvg, testVector); } } }
package jlibs.xml.sax.async; import jlibs.xml.ClarkName; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import static javax.xml.XMLConstants.*; /** * @author Santhosh Kumar T */ class Attributes{ private AttributesImpl attrs = new AttributesImpl(); private Namespaces namespaces; DTD dtd; public Attributes(Namespaces namespaces){ this.namespaces = namespaces; } public void reset(){ attrs.clear(); } public String addAttribute(String elemName, QName attrQName, StringBuilder value) throws SAXException{ String attrName = attrQName.name; AttributeType type = dtd==null ? AttributeType.CDATA : dtd.attributeType(elemName, attrName); String attrValue = type.normalize(value.toString()); String attrLocalName = attrQName.localName; if(attrName.startsWith("xmlns")){ if(attrName.length()==5){ namespaces.add("", attrValue); return null; }else if(attrName.charAt(5)==':'){ if(attrLocalName.equals(XML_NS_PREFIX)){ if(!attrValue.equals(XML_NS_URI)) return "prefix "+ XML_NS_PREFIX+" must refer to "+ XML_NS_URI; }else if(attrLocalName.equals(XMLNS_ATTRIBUTE)) return "prefix "+ XMLNS_ATTRIBUTE+" must not be declared"; else{ if(attrValue.equals(XML_NS_URI)) return XML_NS_URI+" must be bound to "+ XML_NS_PREFIX; else if(attrValue.equals(XMLNS_ATTRIBUTE_NS_URI)) return XMLNS_ATTRIBUTE_NS_URI+" must be bound to "+ XMLNS_ATTRIBUTE; else{ if(attrValue.length()==0) return "No Prefix Undeclaring: "+attrLocalName; namespaces.add(attrLocalName, attrValue); return null; } } } } attrs.addAttribute(attrQName.prefix, attrLocalName, attrName, type.name(), attrValue); return null; } public String fixAttributes(String elemName) throws SAXException{ int attrCount = attrs.getLength(); if(attrCount>0){ for(int i=0; i<attrCount; i++){ String prefix = attrs.getURI(i); if(prefix.length()>0){ String uri = namespaces.getNamespaceURI(prefix); if(uri==null) return "Unbound prefix: "+prefix; attrs.setURI(i, uri); } } if(attrCount>1){ for(int i=1; i<attrCount; i++){ if(attrs.getIndex(attrs.getURI(i), attrs.getLocalName(i))<i) return "Attribute \""+ClarkName.valueOf(attrs.getURI(i), attrs.getLocalName(i))+"\" was already specified for element \""+elemName+"\""; } } } if(dtd!=null) dtd.addMissingAttributes(elemName, attrs); return null; } public AttributesImpl get(){ return attrs; } }
// $Id: TileManager.java 3392 2005-03-10 01:30:34Z ray $ // Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.media.tile; import java.lang.ref.SoftReference; import java.util.HashMap; import com.samskivert.io.PersistenceException; import com.threerings.media.Log; import com.threerings.media.image.ImageManager; /** * The tile manager provides a simplified interface for retrieving and * caching tiles. Tiles can be loaded in two different ways. An * application can load a tileset by hand, specifying the path to the * tileset image and all of the tileset metadata necessary for extracting * the image tiles, or it can provide a tileset repository which loads up * tilesets using whatever repository mechanism is implemented by the * supplied repository. In the latter case, tilesets are loaded by a * unique identifier. * * <p> Loading tilesets by hand is intended for things like toolbar icons * or games with a single set of tiles (think Stratego, for example). * Loading tilesets from a repository supports games with vast numbers of * tiles to which more tiles may be added on the fly (think the tiles for * an isometric-display graphical MUD). */ public class TileManager { /** * Creates a tile manager and provides it with a reference to the * image manager from which it will load tileset images. * * @param imgr the image manager via which the tile manager will * decode and cache images. */ public TileManager (ImageManager imgr) { _imgr = imgr; _defaultProvider = new IMImageProvider(_imgr, (String)null); } /** * Loads up a tileset from the specified image with the specified * metadata parameters. */ public UniformTileSet loadTileSet (String imgPath, int width, int height) { return loadCachedTileSet("", imgPath, width, height); } /** * Loads up a tileset from the specified image (located in the * specified resource set) with the specified metadata parameters. */ public UniformTileSet loadTileSet ( String rset, String imgPath, int width, int height) { return loadTileSet( getImageProvider(rset), rset, imgPath, width, height); } public UniformTileSet loadTileSet ( ImageProvider improv, String improvKey, String imgPath, int width, int height) { UniformTileSet uts = loadCachedTileSet( improvKey, imgPath, width, height); uts.setImageProvider(improv); return uts; } /** * Returns an image provider that will load images from the specified * resource set. */ public ImageProvider getImageProvider (String rset) { return new IMImageProvider(_imgr, rset); } /** * Used to load and cache tilesets loaded via {@link #loadTileSet}. */ protected UniformTileSet loadCachedTileSet ( String bundle, String imgPath, int width, int height) { String key = bundle + "::" + imgPath; SoftReference ref = (SoftReference) _handcache.get(key); UniformTileSet uts = (ref == null) ? null : (UniformTileSet) ref.get(); if (uts == null) { uts = new UniformTileSet(); uts.setImageProvider(_defaultProvider); uts.setImagePath(imgPath); uts.setWidth(width); uts.setHeight(height); _handcache.put(key, new SoftReference(uts)); } return uts; } /** * Clears any cached tilesets. */ public void clearCache () { _handcache = new HashMap(); } /** * Sets the tileset repository that will be used by the tile manager * when tiles are requested by tileset id. */ public void setTileSetRepository (TileSetRepository setrep) { _setrep = setrep; } /** * Returns the tileset repository currently in use. */ public TileSetRepository getTileSetRepository () { return _setrep; } /** * Returns the tileset with the specified id. Tilesets are fetched * from the tileset repository supplied via {@link * #setTileSetRepository}, and are subsequently cached. * * @param tileSetId the unique identifier for the desired tileset. * * @exception NoSuchTileSetException thrown if no tileset exists with * the specified id or if an underlying error occurs with the tileset * repository's persistence mechanism. */ public TileSet getTileSet (int tileSetId) throws NoSuchTileSetException { // make sure we have a repository configured if (_setrep == null) { throw new NoSuchTileSetException(tileSetId); } try { return _setrep.getTileSet(tileSetId); } catch (PersistenceException pe) { Log.warning("Failure loading tileset [id=" + tileSetId + ", error=" + pe + "]."); throw new NoSuchTileSetException(tileSetId); } } /** * Returns the tileset with the specified name. * * @throws NoSuchTileSetException if no tileset with the specified * name is available via our configured tile set repository. */ public TileSet getTileSet (String name) throws NoSuchTileSetException { // make sure we have a repository configured if (_setrep == null) { throw new NoSuchTileSetException(name); } try { return _setrep.getTileSet(name); } catch (PersistenceException pe) { Log.warning("Failure loading tileset [name=" + name + ", error=" + pe + "]."); throw new NoSuchTileSetException(name); } } /** * Returns the {@link Tile} object with the specified fully qualified * tile id. * * @see TileUtil#getFQTileId */ public Tile getTile (int fqTileId) throws NoSuchTileSetException { return getTile(TileUtil.getTileSetId(fqTileId), TileUtil.getTileIndex(fqTileId), null); } /** * Returns the {@link Tile} object with the specified fully qualified * tile id. The supplied colorizer will be used to recolor the tile. * * @see TileUtil#getFQTileId */ public Tile getTile (int fqTileId, TileSet.Colorizer rizer) throws NoSuchTileSetException { return getTile(TileUtil.getTileSetId(fqTileId), TileUtil.getTileIndex(fqTileId), rizer); } /** * Returns the {@link Tile} object from the specified tileset at the * specified index. * * @param tileSetId the tileset id. * @param tileIndex the index of the tile to be retrieved. * * @return the tile object. */ public Tile getTile (int tileSetId, int tileIndex, TileSet.Colorizer rizer) throws NoSuchTileSetException { TileSet set = getTileSet(tileSetId); return set.getTile(tileIndex, rizer); } /** The entity through which we decode and cache images. */ protected ImageManager _imgr; /** A cache of tilesets that have been loaded by hand. */ protected HashMap _handcache = new HashMap(); /** The tile set repository. */ protected TileSetRepository _setrep; /** Used to load tileset images from the default resource source. */ protected ImageProvider _defaultProvider; }
package org.openlca.jsonld; import java.util.Date; import java.util.List; import org.openlca.core.database.CategoryDao; import org.openlca.core.database.FlowPropertyDao; import org.openlca.core.database.IDatabase; import org.openlca.core.database.LocationDao; import org.openlca.core.model.Category; import org.openlca.core.model.FlowProperty; import org.openlca.core.model.Location; import org.openlca.core.model.Unit; import org.openlca.core.model.Version; import org.openlca.core.model.descriptors.BaseDescriptor; import org.openlca.core.model.descriptors.CategorizedDescriptor; import org.openlca.core.model.descriptors.CategoryDescriptor; import org.openlca.core.model.descriptors.FlowDescriptor; import org.openlca.core.model.descriptors.ImpactCategoryDescriptor; import org.openlca.core.model.descriptors.ProcessDescriptor; import org.openlca.util.Categories; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Utility functions for reading and writing Json data. */ public class Json { private Json() { } /** Return the given property as JSON object. */ public static JsonObject getObject(JsonObject obj, String property) { if (obj == null || property == null) return null; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonObject()) return null; else return elem.getAsJsonObject(); } /** Return the given property as JSON array. */ public static JsonArray getArray(JsonObject obj, String property) { if (obj == null || property == null) return null; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonArray()) return null; else return elem.getAsJsonArray(); } /** Return the string value of the given property. */ public static String getString(JsonObject obj, String property) { if (obj == null || property == null) return null; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonPrimitive()) return null; else return elem.getAsString(); } /** Return the double value of the given property. */ public static double getDouble(JsonObject obj, String property, double defaultVal) { if (obj == null || property == null) return defaultVal; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonPrimitive()) return defaultVal; else return elem.getAsDouble(); } /** Return the int value of the given property. */ public static int getInt(JsonObject obj, String property, int defaultVal) { if (obj == null || property == null) return defaultVal; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonPrimitive()) return defaultVal; else return elem.getAsInt(); } public static Double getOptionalDouble(JsonObject obj, String property) { if (obj == null || property == null) return null; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonPrimitive()) return null; else return elem.getAsDouble(); } public static boolean getBool(JsonObject obj, String property, boolean defaultVal) { if (obj == null || property == null) return defaultVal; JsonElement elem = obj.get(property); if (elem == null || !elem.isJsonPrimitive()) return defaultVal; else return elem.getAsBoolean(); } public static Date getDate(JsonObject obj, String property) { String xmlString = getString(obj, property); return Dates.fromString(xmlString); } public static <T extends Enum<T>> T getEnum(JsonObject obj, String property, Class<T> enumClass) { String value = getString(obj, property); return Enums.getValue(value, enumClass); } /** * Returns the value of the `@id` field of the entity reference with the * given name. For example, the given object could be an exchange and the * given reference name could be `flow`, then, this method would return the * reference ID of the flow. */ public static String getRefId(JsonObject obj, String refName) { JsonObject ref = getObject(obj, refName); if (ref == null) return null; return getString(ref, "@id"); } public static void put(JsonObject obj, String prop, String val) { if (obj == null || val == null) return; obj.addProperty(prop, val); } /** * Generates a `Ref` type as defined in olca-schema. For some types (e.g. * flows or processes) a more specific `Ref` type is used (e.g. `FlowRef` or * `ProcessRef`) that contains additional meta-data. */ public static JsonObject asRef(BaseDescriptor d, IDatabase db) { if (d == null) return null; JsonObject obj = new JsonObject(); if (d.getModelType() != null) { String type = d.getModelType().getModelClass().getSimpleName(); put(obj, "@type", type); } put(obj, "@id", d.getRefId()); put(obj, "name", d.getName()); put(obj, "description", d.getDescription()); put(obj, "version", Version.asString(d.getVersion())); if (d instanceof CategorizedDescriptor) { putCategoryPath(obj, (CategorizedDescriptor) d, db); } if (d instanceof CategoryDescriptor) { putCategoryMetaData(obj, (CategoryDescriptor) d, db); } if (d instanceof FlowDescriptor) { putFlowMetaData(obj, (FlowDescriptor) d, db); } if (d instanceof ProcessDescriptor) { putProcessMetaData(obj, (ProcessDescriptor) d, db); } if (d instanceof ImpactCategoryDescriptor) { ImpactCategoryDescriptor icd = (ImpactCategoryDescriptor) d; obj.addProperty("refUnit", icd.getReferenceUnit()); } return obj; } private static void putCategoryPath(JsonObject ref, CategorizedDescriptor d, IDatabase db) { if (ref == null || d == null || d.getCategory() == null) return; CategoryDao dao = new CategoryDao(db); Category cat = dao.getForId(d.getCategory()); if (cat == null) return; List<String> path = Categories.path(cat); JsonArray array = new JsonArray(); for (String p : path) { array.add(new JsonPrimitive(p)); } ref.add("categoryPath", array); } private static void putCategoryMetaData(JsonObject ref, CategoryDescriptor d, IDatabase db) { if (ref == null || d == null) return; if (d.getCategoryType() != null) { String type = d.getCategoryType().getModelClass().getSimpleName(); ref.addProperty("categoryType", type); } } private static void putFlowMetaData(JsonObject ref, FlowDescriptor d, IDatabase db) { if (ref == null || d == null) return; if (d.getFlowType() != null) { ref.addProperty("flowType", d.getFlowType().name()); } if (d.getLocation() != null) { Location loc = new LocationDao(db).getForId(d.getLocation()); if (loc != null) { ref.addProperty("location", loc.getCode()); } } FlowProperty prop = new FlowPropertyDao(db).getForId(d.getRefFlowPropertyId()); if (prop != null && prop.getUnitGroup() != null) { Unit unit = prop.getUnitGroup().getReferenceUnit(); if (unit != null) { ref.addProperty("refUnit", unit.getName()); } } } private static void putProcessMetaData(JsonObject ref, ProcessDescriptor d, IDatabase db) { if (ref == null || d == null) return; if (d.getProcessType() != null) { ref.addProperty("processType", d.getProcessType().name()); } if (d.getLocation() != null) { Location loc = new LocationDao(db).getForId(d.getLocation()); if (loc != null) { ref.addProperty("location", loc.getCode()); } } } }
package org.jaxen.expr; import org.jaxen.Context; class DefaultNumberExpr extends DefaultExpr implements NumberExpr { private static final long serialVersionUID = -6021898973386269611L; private Double number; DefaultNumberExpr( Double number ) { this.number = number; } public Number getNumber() { return this.number; } public String toString() { return "[(DefaultNumberExpr): " + getNumber() + "]"; } public String getText() { return getNumber().toString(); } public Object evaluate( Context context ) { return getNumber(); } public void accept( Visitor visitor ) { visitor.visit( this ); } }
package org.apache.commons.digester; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; public class RulesBase implements Rules { /** * The set of registered Rule instances, keyed by the matching pattern. * Each value is a List containing the Rules for that pattern, in the * order that they were orginally registered. */ protected HashMap cache = new HashMap(); /** * The Digester instance with which this Rules instance is associated. */ protected Digester digester = null; /** * The namespace URI for which subsequently added <code>Rule</code> * objects are relevant, or <code>null</code> for matching independent * of namespaces. */ protected String namespaceURI = null; /** * The set of registered Rule instances, in the order that they were * originally registered. */ protected ArrayList rules = new ArrayList(); /** * Return the Digester instance with which this Rules instance is * associated. */ public Digester getDigester() { return (this.digester); } /** * Set the Digester instance with which this Rules instance is associated. * * @param digester The newly associated Digester instance */ public void setDigester(Digester digester) { this.digester = digester; } /** * Return the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. */ public String getNamespaceURI() { return (this.namespaceURI); } /** * Set the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. * * @param namespaceURI Namespace URI that must match on all * subsequently added rules, or <code>null</code> for matching * regardless of the current namespace URI */ public void setNamespaceURI(String namespaceURI) { this.namespaceURI = namespaceURI; } /** * Register a new Rule instance matching the specified pattern. * * @param pattern Nesting pattern to be matched for this Rule * @param rule Rule instance to be registered */ public void add(String pattern, Rule rule) { List list = (List) cache.get(pattern); if (list == null) { list = new ArrayList(); cache.put(pattern, list); } list.add(rule); rules.add(rule); if (this.namespaceURI != null) rule.setNamespaceURI(this.namespaceURI); } /** * Clear all existing Rule instance registrations. */ public void clear() { cache.clear(); rules.clear(); } /** * Return a List of all registered Rule instances that match the specified * nesting pattern, or a zero-length List if there are no matches. If more * than one Rule instance matches, they <strong>must</strong> be returned * in the order originally registered through the <code>add()</code> * method. * * @param pattern Nesting pattern to be matched * * @deprecated Call match(namespaceURI,pattern) instead. */ public List match(String pattern) { return (match(null, pattern)); } /** * Return a List of all registered Rule instances that match the specified * nesting pattern, or a zero-length List if there are no matches. If more * than one Rule instance matches, they <strong>must</strong> be returned * in the order originally registered through the <code>add()</code> * method. * * @param namespaceURI Namespace URI for which to select matching rules, * or <code>null</code> to match regardless of namespace URI * @param pattern Nesting pattern to be matched */ public List match(String namespaceURI, String pattern) { // List rulesList = (List) this.cache.get(pattern); List rulesList = lookup(namespaceURI, pattern); if ((rulesList == null) || (rulesList.size() < 1)) { // Find the longest key, ie more discriminant String longKey = ""; Iterator keys = this.cache.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.startsWith("*/")) { if (pattern.endsWith(key.substring(1))) { if (key.length() > longKey.length()) { // rulesList = (List) this.cache.get(key); rulesList = lookup(namespaceURI, key); longKey = key; } } } } } return (rulesList); } /** * Return a List of all registered Rule instances, or a zero-length List * if there are no registered Rule instances. If more than one Rule * instance has been registered, they <strong>must</strong> be returned * in the order originally registered through the <code>add()</code> * method. */ public List rules() { return (this.rules); } /** * Return a List of Rule instances for the specified pattern that also * match the specified namespace URI (if any). If there are no such * rules, return <code>null</code>. * * @param namespaceURI Namespace URI to match, or <code>null</code> to * select matching rules regardless of namespace URI * @param pattern Pattern to be matched */ protected List lookup(String namespaceURI, String pattern) { // Optimize when no namespace URI is specified List list = (List) this.cache.get(pattern); if (list == null) { return (null); } if ((namespaceURI == null) || (namespaceURI.length() == 0)) { return (list); } // Select only Rules that match on the specified namespace URI ArrayList results = new ArrayList(); Iterator items = list.iterator(); while (items.hasNext()) { Rule item = (Rule) items.next(); if ((namespaceURI.equals(item.getNamespaceURI())) || (item.getNamespaceURI() == null)) { results.add(item); } } return (results); } }
package org.apache.commons.lang; import java.util.NoSuchElementException; import java.util.StringTokenizer; /** * <code>WordWrapUtils</code> is a utility class to assist with word wrapping. * * @author Henri Yandell * @author Stephen Colebourne * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @version $Id: WordWrapUtils.java,v 1.3 2003/05/20 21:11:07 ggregory Exp $ */ public class WordWrapUtils { /** * <p><code>WordWrapUtils</code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>WordWrapUtils.woodWrap("foo bar");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public WordWrapUtils() { } // Wrapping /** * Wraps a block of text to a specified line length. * <p> * This method takes a block of text, which might have long lines in it * and wraps the long lines based on the supplied wrapColumn parameter. * It was initially implemented for use by VelocityEmail. If there are tabs * in inString, you are going to get results that are a bit strange, * since tabs are a single character but are displayed as 4 or 8 * spaces. Remove the tabs. * * @param str text which is in need of word-wrapping * @param newline the characters that define a newline * @param wrapColumn the column to wrap the words at * @return the text with all the long lines word-wrapped */ public static String wrapText(String str, String newline, int wrapColumn) { StringTokenizer lineTokenizer = new StringTokenizer(str, newline, true); StringBuffer stringBuffer = new StringBuffer(); while (lineTokenizer.hasMoreTokens()) { try { String nextLine = lineTokenizer.nextToken(); if (nextLine.length() > wrapColumn) { // This line is long enough to be wrapped. nextLine = wrapLine(nextLine, newline, wrapColumn); } stringBuffer.append(nextLine); } catch (NoSuchElementException nsee) { // thrown by nextToken(), but I don't know why it would break; } } return (stringBuffer.toString()); } /** * Wraps a single line of text. * Called by wrapText() to do the real work of wrapping. * * @param line a line which is in need of word-wrapping * @param newline the characters that define a newline * @param wrapColumn the column to wrap the words at * @return a line with newlines inserted */ private static String wrapLine(String line, String newline, int wrapColumn) { StringBuffer wrappedLine = new StringBuffer(); while (line.length() > wrapColumn) { int spaceToWrapAt = line.lastIndexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } // This must be a really long word or URL. Pass it // through unchanged even though it's longer than the // wrapColumn would allow. This behavior could be // dependent on a parameter for those situations when // someone wants long words broken at line length. else { spaceToWrapAt = line.indexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } else { wrappedLine.append(line); line = ""; } } } // Whatever is left in line is short enough to just pass through wrappedLine.append(line); return (wrappedLine.toString()); } // Word wrapping /** * Create a word-wrapped version of a String. Wrap at 80 characters and * use newlines as the delimiter. If a word is over 80 characters long * use a - sign to split it. */ public static String wordWrap(String str) { return wordWrap(str, 80, "\n", "-"); } /** * Create a word-wrapped version of a String. Wrap at a specified width and * use newlines as the delimiter. If a word is over the width in lenght * use a - sign to split it. */ public static String wordWrap(String str, int width) { return wordWrap(str, width, "\n", "-"); } /** * Word-wrap a string. * * @param str String to word-wrap * @param width int to wrap at * @param delim String to use to separate lines * @param split String to use to split a word greater than width long * * @return String that has been word wrapped */ public static String wordWrap(String str, int width, String delim, String split) { int sz = str.length(); /// shift width up one. mainly as it makes the logic easier width++; // our best guess as to an initial size StringBuffer buffer = new StringBuffer(sz / width * delim.length() + sz); // every line will include a delim on the end width = width - delim.length(); int idx = -1; String substr = null; // beware: i is rolled-back inside the loop for (int i = 0; i < sz; i += width) { // on the last line if (i > sz - width) { buffer.append(str.substring(i)); break; } // the current line substr = str.substring(i, i + width); // is the delim already on the line idx = substr.indexOf(delim); if (idx != -1) { buffer.append(substr.substring(0, idx)); buffer.append(delim); i -= width - idx - delim.length(); // Erase a space after a delim. Is this too obscure? if(substr.length() > idx + 1) { if (substr.charAt(idx + 1) != '\n') { if (Character.isWhitespace(substr.charAt(idx + 1))) { i++; } } } continue; } idx = -1; // figure out where the last space is char[] chrs = substr.toCharArray(); for (int j = width; j > 0; j if (Character.isWhitespace(chrs[j - 1])) { idx = j; break; } } // idx is the last whitespace on the line. if (idx == -1) { for (int j = width; j > 0; j if (chrs[j - 1] == '-') { idx = j; break; } } if (idx == -1) { buffer.append(substr); buffer.append(delim); } else { if (idx != width) { idx++; } buffer.append(substr.substring(0, idx)); buffer.append(delim); i -= width - idx; } } else { buffer.append(substr.substring(0, idx)); buffer.append(StringUtils.repeat(" ", width - idx)); buffer.append(delim); i -= width - idx; } } return buffer.toString(); } }
package org.jdesktop.swingx; import java.util.ArrayList; import java.io.StringWriter; import java.io.PrintWriter; /*import org.jdesktop.jdic.desktop.Desktop; import org.jdesktop.jdic.desktop.DesktopException; import org.jdesktop.jdic.desktop.Message; */ public class MailErrorReporter extends ErrorReporter { private String mailAddr; private ArrayList<String> toList = new ArrayList<String>(); public MailErrorReporter(String address) { super(); this.mailAddr = address; toList.add(this.mailAddr); } /** * Get the mail address to which send error report * * @return mail address */ public String getMailAddr() { return mailAddr; } /** * Set the address to which we will send mail * * @param mailAddr */ public void setMailAddr(String mailAddr) { toList.remove(this.mailAddr); this.mailAddr = mailAddr; toList.add(this.mailAddr); } /** * Report given incident by popping up system default mail user agent with prepared message * * @param info <code>IncidentInfo</code> which incorporates all the information on error */ public void reportIncident(IncidentInfo info) { /* Message msg = new Message(); msg.setToAddrs(toList); msg.setSubject(info.getHeader()); msg.setBody(getMessageBody(info)); try { Desktop.mail(msg); } catch (DesktopException e) {} */ } /** * This method is used to extract text message from the provided <code>IncidentInfo</code>. * Override this method to change text formatting or contents. * * @param incident - Incapsulates all the information about error * @return String to be used as a body message in report. */ public String getMessageBody(IncidentInfo incident) { String body = incident.getBasicErrorMessage(); if(incident.getDetailedErrorMessage() != null) { body.concat("\n"+incident.getDetailedErrorMessage()); } if(incident.getErrorException() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); incident.getErrorException().printStackTrace(pw); body = body + "\n } return body; } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.packet.DefaultPacketExtension; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.profile.VCardManager; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.image.BufferedImage; import java.io.File; import java.net.MalformedURLException; import java.net.URL; /** * Represent a single contact within the <code>ContactList</code>. */ public class ContactItem extends JPanel { private JLabel imageLabel; private JLabel nicknameLabel; private JLabel descriptionLabel; private String nickname; private String fullyQualifiedJID; private Icon icon; private String status; private String groupName; boolean available; private Presence presence; private String hash = ""; private File contactsDir; private JLabel sideIcon; /** * Creates a new instance of a contact. * * @param nickname the nickname of the contact. * @param fullyQualifiedJID the fully-qualified jid of the contact (ex. derek@jivesoftware.com) */ public ContactItem(String nickname, String fullyQualifiedJID) { setLayout(new GridBagLayout()); // Set default presence presence = new Presence(Presence.Type.unavailable); contactsDir = new File(SparkManager.getUserDirectory(), "contacts"); nicknameLabel = new JLabel(); descriptionLabel = new JLabel(); imageLabel = new JLabel(); sideIcon = new JLabel(); nicknameLabel.setHorizontalTextPosition(JLabel.LEFT); nicknameLabel.setHorizontalAlignment(JLabel.LEFT); nicknameLabel.setText(nickname); descriptionLabel.setFont(new Font("Dialog", Font.PLAIN, 11)); descriptionLabel.setForeground((Color)UIManager.get("ContactItemDescription.foreground")); descriptionLabel.setHorizontalTextPosition(JLabel.LEFT); descriptionLabel.setHorizontalAlignment(JLabel.LEFT); this.setOpaque(true); add(imageLabel, new GridBagConstraints(0, 0, 1, 2, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(0, 10, 0, 0), 0, 0)); add(nicknameLabel, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0)); add(descriptionLabel, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 2, 0), 0, 0)); add(sideIcon, new GridBagConstraints(3, 0, 1, 2, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 0), 0, 0)); setNickname(nickname); this.fullyQualifiedJID = fullyQualifiedJID; } /** * Returns the nickname of the contact. * * @return the nickname. */ public String getNickname() { return nickname; } /** * Sets the nickname of the contact. * * @param nickname the contact nickname. */ public void setNickname(String nickname) { this.nickname = nickname; nicknameLabel.setText(StringUtils.unescapeNode(nickname)); } /** * Returns the fully qualified JID of the contact. (If available). Otherwise will * return the bare jid. * * @return the fully qualified jid (ex. derek@jivesoftware.com). */ public String getJID() { return fullyQualifiedJID; } /** * Returns the icon showing the contacts current state or presence. * * @return the icon. */ public Icon getIcon() { return icon; } /** * Sets the current icon to use. * * @param icon the current icon to use. */ public void setIcon(Icon icon) { this.icon = icon; imageLabel.setIcon(icon); } /** * Returns the contacts current status based on their presence. * * @return the contacts current status. */ public String getStatus() { return status; } /** * Sets the contacts current status. * * @param status the contacts current status. */ public void setStatus(String status) { this.status = status; } /** * Returns the name of the <code>ContactGroup</code> that this contact belongs to. * * @return the name of the <code>ContactGroup</code>. */ public String getGroupName() { return groupName; } /** * Sets the name of the <code>ContactGrouop</code> that this contact belongs to. * * @param groupName the name of the ContactGroup. */ public void setGroupName(String groupName) { this.groupName = groupName; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } /** * Returns the <code>JLabel</code> showing the users nickname. * * @return the nickname label. */ public JLabel getNicknameLabel() { return nicknameLabel; } /** * Returns the <code>JLabel</code> representing the description. * * @return the description label. */ public JLabel getDescriptionLabel() { return descriptionLabel; } /** * Returns the current presence of the contact. * * @return the users current presence. */ public Presence getPresence() { return presence; } /** * Sets the current presence on this contact item. * * @param presence the presence. */ public void setPresence(Presence presence) { this.presence = presence; final PacketExtension packetExtension = presence.getExtension("x", "vcard-temp:x:update"); // Handle vCard update packet. if (packetExtension != null) { DefaultPacketExtension o = (DefaultPacketExtension)packetExtension; String hash = o.getValue("photo"); if (hash != null) { this.hash = hash; if (!hashExists(hash)) { updateAvatar(hash); } } } updatePresenceIcon(presence); } /** * Checks to see if the hash already exists. * * @param hash the hash. * @return true if the hash exists, otherwise false. */ private boolean hashExists(String hash) { contactsDir.mkdirs(); final File imageFile = new File(contactsDir, hash); return imageFile.exists(); } /** * Returns the url of the avatar belonging to this contact. * * @return the url of the avatar. * @throws MalformedURLException thrown if the address is invalid. */ public URL getAvatarURL() throws MalformedURLException { contactsDir.mkdirs(); if (ModelUtil.hasLength(hash)) { final File imageFile = new File(contactsDir, hash); if (imageFile.exists()) { return imageFile.toURL(); } } return null; } /** * Persists the avatar locally based on the new hash. * * @param hash the new hash. */ private void updateAvatar(final String hash) { Runnable updateRunnable = new Runnable() { public void run() { contactsDir.mkdirs(); final File imageFile = new File(contactsDir, hash); VCard vcard = SparkManager.getVCardManager().reloadVCard(getJID()); try { byte[] bytes = vcard.getAvatar(); if (bytes != null) { ImageIcon icon = new ImageIcon(bytes); icon = VCardManager.scale(icon); if (icon != null && icon.getIconWidth() != -1) { BufferedImage image = GraphicUtils.convert(icon.getImage()); ImageIO.write(image, "PNG", imageFile); } } } catch (Exception e) { Log.error("Unable to update avatar in Contact Item.", e); } } }; TaskEngine.getInstance().submit(updateRunnable); } public String toString() { return nicknameLabel.getText(); } /** * Updates the icon of the user based on their presence. * * @param presence the users presence. */ public void updatePresenceIcon(Presence presence) { ChatManager chatManager = SparkManager.getChatManager(); boolean handled = chatManager.fireContactItemPresenceChanged(this, presence); if (handled) { return; } String status = presence.getStatus(); Icon statusIcon = SparkRes.getImageIcon(SparkRes.GREEN_BALL); boolean isAvailable = false; if (status == null && presence.isAvailable()) { Presence.Mode mode = presence.getMode(); if (mode == Presence.Mode.available) { status = "Available"; isAvailable = true; } else if (mode == Presence.Mode.away) { status = "I'm away"; statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY); } else if (mode == Presence.Mode.chat) { status = "I'm free to chat"; } else if (mode == Presence.Mode.dnd) { status = "Do not disturb"; statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY); } else if (mode == Presence.Mode.xa) { status = "Extended away"; statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY); } } if (presence.isAvailable() && (presence.getMode() == Presence.Mode.dnd || presence.getMode() == Presence.Mode.away || presence.getMode() == Presence.Mode.xa)) { statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY); } else if (presence.isAvailable()) { isAvailable = true; } else if (!presence.isAvailable()) { getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); getNicknameLabel().setForeground((Color)UIManager.get("ContactItemOffline.color")); RosterEntry entry = SparkManager.getConnection().getRoster().getEntry(getJID()); if (entry != null && (entry.getType() == RosterPacket.ItemType.none || entry.getType() == RosterPacket.ItemType.from) && RosterPacket.ItemStatus.SUBSCRIPTION_PENDING == entry.getStatus()) { // Do not move out of group. setIcon(SparkRes.getImageIcon(SparkRes.SMALL_QUESTION)); getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); setStatusText("Pending"); } else { setIcon(null); setFont(new Font("Dialog", Font.PLAIN, 11)); getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); setAvailable(false); if (ModelUtil.hasLength(status)) { setStatusText(status); } else { setStatusText(""); } } sideIcon.setIcon(null); setAvailable(false); return; } Icon sIcon = PresenceManager.getIconFromPresence(presence); if (sIcon != null) { setIcon(sIcon); } else { setIcon(statusIcon); } if (status != null) { setStatus(status); } if (status != null && status.toLowerCase().indexOf("phone") != -1) { statusIcon = SparkRes.getImageIcon(SparkRes.ON_PHONE_IMAGE); setIcon(statusIcon); } // Always change nickname label to black. getNicknameLabel().setForeground((Color)UIManager.get("ContactItemNickname.foreground")); if (isAvailable) { getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); if ("Online".equals(status) || Res.getString("available").equalsIgnoreCase(status)) { setStatusText(""); } else { setStatusText(status); } } else if (presence.isAvailable()) { getNicknameLabel().setFont(new Font("Dialog", Font.ITALIC, 11)); getNicknameLabel().setForeground(Color.gray); if (status != null) { setStatusText(status); } } setAvailable(true); } /** * Sets the status label text based on the users status. * * @param status the users status. */ public void setStatusText(String status) { setStatus(status); if (ModelUtil.hasLength(status)) { getDescriptionLabel().setText(" - " + status); } else { getDescriptionLabel().setText(""); } } /** * The icon to use to show extra information about this contact. An example would be to * represent that this user is from a 3rd party transport. * * @param icon the icon to use. */ public void setSideIcon(Icon icon) { sideIcon.setIcon(icon); } /** * Shows that the user is coming online. */ public void showUserComingOnline() { // Change Font getNicknameLabel().setFont(new Font("Dialog", Font.BOLD, 11)); getNicknameLabel().setForeground(new Color(255, 128, 0)); } /** * Shows that the user is going offline. */ public void showUserGoingOfflineOnline() { // Change Font getNicknameLabel().setFont(new Font("Dialog", Font.BOLD, 11)); getNicknameLabel().setForeground(Color.red); } }
package com.mfk.web.maker.client; import java.util.Vector; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.search.client.DrawMode; import com.google.gwt.search.client.ExpandMode; import com.google.gwt.search.client.ImageResult; import com.google.gwt.search.client.ImageSearch; import com.google.gwt.search.client.KeepHandler; import com.google.gwt.search.client.LinkTarget; import com.google.gwt.search.client.Result; import com.google.gwt.search.client.ResultSetSize; import com.google.gwt.search.client.SafeSearchValue; import com.google.gwt.search.client.SearchControl; import com.google.gwt.search.client.SearchControlOptions; import com.google.gwt.search.client.SearchResultsHandler; import com.google.gwt.search.client.SearchStartingHandler; import com.google.gwt.search.client.WebSearch; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; // TODO(mjkelly): See this example: // https://code.google.com/apis/ajax/playground/#raw_search /** * Entry point classes define <code>onModuleLoad()</code>. */ public class MfkMaker implements EntryPoint { /** * This is the entry point method. */ public static Image selected; public static Image images[] = { null, null, null }; public static Button setButtons[] = { new Button("Set Item 1"), new Button("Set Item 2"), new Button("Set Item 3") }; // the actual image results public static Vector<Image> results = new Vector<Image>(); // the UI panel that displays the search results static Panel resultPanel = new FlowPanel(); // The query that led to the displayed results. public static String resultsSearchQuery; static ImageSearch imageSearch = new ImageSearch(); static final EditDialog editDialog = new EditDialog(true); static Vector<MfkPanel> items = new Vector<MfkPanel>(); static final HorizontalPanel itemPanel = new HorizontalPanel(); static final DialogBox errorDialog = new DialogBox(); public void onModuleLoad() { RootPanel.get("created-items").add(MfkMaker.itemPanel); MfkMaker.itemPanel.setSpacing(10); for (int i = 1; i <= 3; i++) { SearchImage img = new SearchImage("/gwt/images/treehouse-" + i + ".jpeg", "treehouse"); System.out.println("setup q=" + img.getQuery()); MfkPanel item = new MfkPanel("Treehouse " + i, img); MfkMaker.addItem(item); } final SearchControlOptions options = new SearchControlOptions(); // TODO(mjkelly): reconsider this value. Remember to synchronize any // change with the server-side checking. imageSearch.setSafeSearch(SafeSearchValue.STRICT); imageSearch.setResultSetSize(ResultSetSize.LARGE); options.add(imageSearch, ExpandMode.OPEN); options.setKeepLabel("<b>Keep It!</b>"); options.setLinkTarget(LinkTarget.BLANK); MfkMaker.editDialog.setAnimationEnabled(true); final ClickHandler resultClick = new ClickHandler() { public void onClick(ClickEvent event) { Image source = (Image) event.getSource(); MfkMaker.editDialog.setImage(source); } }; // This handles the displayed result list. imageSearch.addSearchResultsHandler(new SearchResultsHandler() { public void onSearchResults(SearchResultsEvent event) { JsArray<? extends Result> results = event.getResults(); System.out.println("List handler! #results = " + results.length()); for (int i = 0; i < results.length(); i++) { ImageResult r = (ImageResult) results.get(i); Image thumb = new Image(r.getThumbnailUrl()); thumb.setHeight(String.valueOf(r.getThumbnailHeight())); thumb.setWidth(String.valueOf(r.getThumbnailWidth())); thumb.addStyleName("search-result"); thumb.addClickHandler(resultClick); resultPanel.add(thumb); MfkMaker.results.add(thumb); MfkMaker.editDialog.setSearchThrobber(false); } } }); // This handles the auto-set image. imageSearch.addSearchResultsHandler(new SearchResultsHandler() { public void onSearchResults(SearchResultsEvent event) { JsArray<? extends Result> results = event.getResults(); System.out.println("Top-result handler! #results = " + results.length() + ", search = " + MfkMaker.resultsSearchQuery); if (results.length() >= 1) { ImageResult r = (ImageResult) results.get(0); Image image = new Image(r.getThumbnailUrl()); MfkMaker.editDialog.autoSetImage(image); MfkMaker.editDialog.setAutoThrobber(false); } } }); // The submit button. Button submit_btn = new Button("Create"); submit_btn.addClickHandler(new SubmitHandler()); RootPanel.get("submit").add(submit_btn); } /** * Add an item to the page. * * @param item * the MfkPanel to add */ public static void addItem(MfkPanel item) { MfkMaker.items.add(item); MfkMaker.itemPanel.add(item); } public static void showError(String title, String message) { MfkMaker.errorDialog.hide(); MfkMaker.errorDialog.clear(); VerticalPanel panel = new VerticalPanel(); MfkMaker.errorDialog.add(panel); panel.add(new HTML("<p><b>" + title + "</b></p>")); panel.add(new HTML("<p>" + message + "</p>")); Button closeButton = new Button("OK"); closeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { MfkMaker.errorDialog.hide(); } }); panel.add(closeButton); MfkMaker.errorDialog.center(); MfkMaker.errorDialog.show(); } } class EditDialog extends DialogBox { private static String THROBBER_URL = "/gwt/loading.gif"; private MfkPanel item = null; private SearchImage editImage = new SearchImage(); private TextBox editTitle = new TextBox(); private Image autoThrobber = new Image(EditDialog.THROBBER_URL); private HorizontalPanel searchThrobber = new HorizontalPanel(); private Button searchButton = new Button("Search"); private TextBox searchBox = new TextBox(); // These are all bookkeeping for auto-search: // Last time we sent a search. Maintained by maybeSearch. private long lastSearchMillis = 0; // Last time the text box changed. Maintained by repeatingTimer. private long lastChangeMillis = 0; // Last search text. Maintained by maybeSearch. // NOTE: This is distinct from MfkMaker.resultSearchQuery -- this is used // only for maybeSearch's retry logic. private String lastSearch = ""; // Timer that drives actual searching. private Timer repeatingTimer; // The expanding search panel. private VerticalPanel search = new VerticalPanel(); public EditDialog() { this(false); } public EditDialog(boolean b) { super(b); HorizontalPanel searchControls = new HorizontalPanel(); this.searchButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { doSearch(); } }); this.searchBox.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == '\n' || event.getCharCode() == '\r') { doSearch(); } } }); searchControls.add(this.searchBox); searchControls.add(this.searchButton); HorizontalPanel moreImagesTitle = new HorizontalPanel(); moreImagesTitle.add(new HTML("Search for more images:")); HTML hideLink = new HTML("[hide]"); hideLink.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { search.setVisible(false); } }); hideLink.setStylePrimaryName("fakelink"); moreImagesTitle.add(hideLink); this.search.add(new HTML("<hr>")); this.search.add(moreImagesTitle); this.search.add(searchControls); this.searchThrobber.add(new Image(EditDialog.THROBBER_URL)); this.searchThrobber.add(new HTML("Loading...")); this.searchThrobber.setSpacing(10); this.searchThrobber.setVisible(false); this.search.add(searchThrobber); this.search.add(MfkMaker.resultPanel); this.search.setSpacing(5); } public void editItem(final MfkPanel item) { this.item = item; System.out.println("Showing dialog for :" + item); this.editImage.setUrlAndQuery(item.image.getUrl(), item.image .getQuery()); this.editTitle.setText(item.title); this.autoThrobber.setVisible(false); this.search.setVisible(false); long now = System.currentTimeMillis(); this.lastSearch = item.title; this.lastChangeMillis = this.lastSearchMillis = now; // This just keeps track of when the last change in the box was. // If it misses a keystroke, our time is a little old, but that's okay. // (We still throttle searches.) this.editTitle.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { lastChangeMillis = System.currentTimeMillis(); setAutoThrobber(true); } }); // This checks repeatedly if we should search. this.repeatingTimer = new Timer() { public void run() { maybeSearch(); } }; this.repeatingTimer.scheduleRepeating(250); VerticalPanel p = new VerticalPanel(); p.setSpacing(5); // TODO: put this in CSS, come up with a well-reasoned value p.setWidth("600px"); Button create = new Button("<b>Save</b>"); create.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { System.out.println("Should create item here"); hide(); // update the existing item item.setTitle(editTitle.getText()); item.setImage(editImage); } }); Button cancel = new Button("Cancel"); cancel.addClickHandler(new ClickHandler() { public void onClick(ClickEvent e) { hide(); } }); p.add(new HTML("<b>Name:</b>")); HorizontalPanel titlePanel = new HorizontalPanel(); titlePanel.add(editTitle); titlePanel.add(autoThrobber); p.add(titlePanel); p.add(new HTML("<b>Image:</b>")); p.add(editImage); p.add(new HTML("Not the image you wanted?")); HTML link = new HTML("See more images."); link.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { search.setVisible(!search.isVisible()); if (search.isVisible()) { searchBox.setText(editTitle.getText()); doSearch(); } } }); link.setStylePrimaryName("fakelink"); p.add(link); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.setSpacing(5); buttonPanel.add(create); buttonPanel.add(cancel); p.add(buttonPanel); p.add(search); this.setWidget(p); this.show(); this.center(); this.editTitle.setFocus(true); } /** * This is the logic that determines if we should search. */ public void maybeSearch() { long now = System.currentTimeMillis(); String text = this.editTitle.getText(); if (now - this.lastChangeMillis > 250) { if (now - this.lastSearchMillis > 1000) { this.lastSearchMillis = now; if (!text.equals(this.lastSearch) && !text.isEmpty()) { this.lastSearch = text; System.out.println("maybeSearch: <" + text + ">"); this.doAutoSearch(); } } } } private void doAutoSearch() { String text = this.editTitle.getText(); this.searchBox.setText(text); this.doSearch(); } private void doSearch() { MfkMaker.editDialog.setSearchThrobber(true); MfkMaker.resultPanel.clear(); MfkMaker.results.clear(); MfkMaker.resultsSearchQuery = this.searchBox.getText(); MfkMaker.imageSearch.execute(this.searchBox.getText()); } /** * Turn on or off the throbber. * * @param enabled */ public void setAutoThrobber(boolean enabled) { this.autoThrobber.setVisible(enabled); } public void setSearchThrobber(boolean enabled) { this.searchThrobber.setVisible(enabled); } /** * Set the image for the item under edit. */ public void setImage(Image image) { System.out.println("Set edit image url = " + image.getUrl() + " (from = " + MfkMaker.resultsSearchQuery + ")"); this.editImage.setUrlAndQuery(image.getUrl(), MfkMaker.resultsSearchQuery); } public void autoSetImage(Image image) { if (this.shouldAutoSet()) { this.setImage(image); } } private boolean shouldAutoSet() { return !this.search.isVisible(); } public void hide() { super.hide(); this.item = null; if (this.repeatingTimer != null) this.repeatingTimer.cancel(); } public MfkPanel getItem() { return this.item; } } class MfkPanel extends VerticalPanel { // The user-visible title for the entity public String title = ""; // The user-visible image for the entity. public SearchImage image = new SearchImage(); public MfkPanel(String title, SearchImage image) { this.setTitle(title); this.setImage(image); System.out.println("MfkPanel: title:" + title); this.addStyleName("mfkpanel"); } public void setImage(SearchImage image) { this.image.setUrlAndQuery(image.getUrl(), image.getQuery()); this.refresh(); } public void setTitle(String title) { this.title = title; this.refresh(); } /** * Refresh the UI elements of the page. */ private void refresh() { this.clear(); Button editButton = new Button("Edit"); final MfkPanel outerThis = this; editButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { MfkMaker.editDialog.editItem(outerThis); } }); HTML title = new HTML(this.title); title.addStyleName("itemtitle"); this.add(title); this.add(this.image); this.add(editButton); } public String toString() { return "<MfkPanel: " + this.title + ", url=" + this.image.getUrl() + ">"; } } // TODO(mjkelly): Do client-side validation here. class SubmitHandler implements ClickHandler { public void onClick(ClickEvent event) { MfkPanel[] p = { MfkMaker.items.get(0), MfkMaker.items.get(1), MfkMaker.items.get(2) }; String url = "/rpc/create/"; RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url); builder.setHeader("Content-Type", "application/x-www-form-urlencoded"); StringBuffer reqData = new StringBuffer(); URL.encodeQueryString(url); reqData.append("n1=").append(URL.encodeQueryString(p[0].title)); reqData.append("&n2=").append(URL.encodeQueryString(p[1].title)); reqData.append("&n3=").append(URL.encodeQueryString(p[2].title)); reqData.append("&u1=").append( URL.encodeQueryString(p[0].image.getUrl())); reqData.append("&u2=").append( URL.encodeQueryString(p[1].image.getUrl())); reqData.append("&u3=").append( URL.encodeQueryString(p[2].image.getUrl())); reqData.append("&q1=").append( URL.encodeQueryString(p[0].image.getQuery())); reqData.append("&q2=").append( URL.encodeQueryString(p[1].image.getQuery())); reqData.append("&q3=").append( URL.encodeQueryString(p[2].image.getQuery())); System.out.println("request data = " + reqData); try { builder.sendRequest(reqData.toString(), new RequestCallback() { public void onError(Request request, Throwable exception) { System.out.println("Error creating new Triple"); } public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 200) { String[] responseParts = response.getText().split(":", 2); if (responseParts[0].equals("ok")) { System.out.println("Successful creation request: " + response.getText()); } else { System.out.println("Error: " + responseParts[1]); MfkMaker.showError("Error Creating Your MFK", "The server says: " + responseParts[1]); } } else { System.out.println( "Server-side error creating new MFK: " + "Response code: " + response.getStatusCode() + "; response text: " + response.getText()); MfkMaker.showError("Server Error", "Response code " + response.getStatusCode() + ": " + response.getStatusText()); } } }); } catch (RequestException e) { System.out.println("Error sending vote: " + e); } } } /** * A simple image-holder with constant width and height, designed specifically * to hold the images from an image search. */ class SearchImage extends FlowPanel { private Image image; private String query; public SearchImage(String url, String query) { System.out.println("New SearchImage: " + url + ", " + query); this.image = new Image(url); this.query = new String(query); this.add(this.image); this.autoSize(); } public SearchImage() { this.image = new Image(); this.add(this.image); this.autoSize(); } public void setUrlAndQuery(String url, String query) { System.out.println("SearchImage.setUrl: url=" + url + ", q=" + query); this.image.setUrl(url); this.query = new String(query); } public String getUrl() { return this.image.getUrl(); } public String getQuery() { return this.query; } private void autoSize() { this.setWidth("145px"); this.setHeight("145px"); this.addStyleName("searchimage"); } public String toString() { return "<SearchImage url=" + this.image.getUrl() + ", q=" + this.query + ">"; } }
package org.reldb.dbrowser.loading; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; import org.reldb.dbrowser.ui.IconLoader; import org.reldb.dbrowser.utilities.FontSize; public class Loading { private static final int expectedMessageCount = 6; private static final int backgroundWidth = 600; private static final int backgroundHeight = 183; private static Loading loading = null; private Shell loadingShell; private Label lblAction; private ProgressBar progressBar; private int count = 0; private static Point getMonitorCenter(Shell shell) { Monitor primary = shell.getDisplay().getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = shell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; return new Point(x, y); } public static void open() { loading = new Loading(); loading.openInstance(); } public static void close() { if (loading != null) loading.closeInstance(); loading = null; } public static void action(String message) { if (loading != null) loading.setMessage(message); } public static boolean isDisplayed() { return loading != null; } private void openInstance() { loadingShell = createLoadingShell(); loadingShell.layout(); loadingShell.open(); count = 0; } private Shell createLoadingShell() { final Shell shell = new Shell(SWT.NO_TRIM); shell.setLayout(new FormLayout()); shell.setMinimumSize(backgroundWidth, backgroundHeight); shell.setSize(backgroundWidth, backgroundHeight); Image background = IconLoader.loadIconNormal("loading"); shell.setBackgroundImage(background); shell.setBackgroundMode(SWT.INHERIT_FORCE); Label lblTitle = new Label(shell, SWT.TRANSPARENT); lblTitle.setFont(FontSize.getThisFontInNewSize(lblTitle.getFont(), 24, SWT.BOLD)); lblTitle.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); FormData fd_lblTitle = new FormData(); fd_lblTitle.top = new FormAttachment(0, 0); fd_lblTitle.left = new FormAttachment(0, 10); fd_lblTitle.right = new FormAttachment(100, -10); lblTitle.setLayoutData(fd_lblTitle); lblTitle.setText("Loading"); progressBar = new ProgressBar(shell, SWT.NONE); progressBar.setMaximum(expectedMessageCount); progressBar.setMinimum(0); progressBar.setSelection(0); FormData fd_progressBar = new FormData(); fd_progressBar.bottom = new FormAttachment(100, -10); fd_progressBar.left = new FormAttachment(0, 10); fd_progressBar.right = new FormAttachment(100, -10); progressBar.setLayoutData(fd_progressBar); lblAction = new Label(shell, SWT.WRAP | SWT.TRANSPARENT); lblAction.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); FormData fd_lblAction = new FormData(); fd_lblAction.top = new FormAttachment(progressBar, -60); fd_lblAction.bottom = new FormAttachment(progressBar, -10); fd_lblAction.left = new FormAttachment(0, 10); fd_lblAction.right = new FormAttachment(100, -200); lblAction.setLayoutData(fd_lblAction); lblAction.setText("Starting..."); shell.setSize(background.getBounds().x, background.getBounds().y); shell.setLocation(getMonitorCenter(shell)); return shell; } private void closeInstance() { loadingShell.close(); loadingShell = null; } private void setMessage(final String message) { if (lblAction != null && !lblAction.isDisposed()) { String msg = message.trim().replaceAll("\n", ""); if (msg.length() == 0) return; lblAction.setText(msg); progressBar.setSelection(++count); loadingShell.layout(); loadingShell.getDisplay().readAndDispatch(); // needed on OS X } } }
package org.neo4j.impl.nioneo.xa; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Collection; import java.util.logging.Logger; import org.neo4j.impl.nioneo.store.DynamicRecord; import org.neo4j.impl.nioneo.store.NeoStore; import org.neo4j.impl.nioneo.store.NodeRecord; import org.neo4j.impl.nioneo.store.NodeStore; import org.neo4j.impl.nioneo.store.PropertyRecord; import org.neo4j.impl.nioneo.store.PropertyStore; import org.neo4j.impl.nioneo.store.PropertyType; import org.neo4j.impl.nioneo.store.Record; import org.neo4j.impl.nioneo.store.RelationshipRecord; import org.neo4j.impl.nioneo.store.RelationshipStore; import org.neo4j.impl.nioneo.store.RelationshipTypeRecord; import org.neo4j.impl.nioneo.store.RelationshipTypeStore; import org.neo4j.impl.transaction.xaframework.XaCommand; /** * Command implementations for all the commands that can be performed on a * Neo store. */ abstract class Command extends XaCommand { static Logger logger = Logger.getLogger( Command.class.getName() ); private Integer key; private boolean isInRecovery = false; Command( Integer key ) { this.key = key; } boolean isInRecoveryMode() { return isInRecovery; } void setIsInRecoveryMode() { isInRecovery = true; } Integer getKey() { return key; } static void writeDynamicRecord( DynamicRecord record, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { // id+in_use(byte)+prev_block(int)+nr_of_bytes(int)+next_block(int) buffer.clear(); byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.putInt( record.getId() ).put( inUse ).putInt( record.getPrevBlock() ).putInt( record.getLength() ).putInt( record.getNextBlock() ).put( record.getData() ); buffer.flip(); fileChannel.write( buffer ); } static DynamicRecord readDynamicRecord( FileChannel fileChannel, ByteBuffer buffer) throws IOException { // id+in_use(byte)+prev_block(int)+nr_of_bytes(int)+next_block(int) buffer.clear(); buffer.limit( 17 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int id = buffer.getInt(); byte inUseFlag = buffer.get(); boolean inUse = false; if ( inUseFlag == Record.IN_USE.byteValue() ) { inUse = true; } else if ( inUseFlag != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } DynamicRecord record = new DynamicRecord( id ); record.setInUse( inUse ); record.setPrevBlock( buffer.getInt() ); int nrOfBytes = buffer.getInt(); record.setNextBlock( buffer.getInt() ); buffer.clear(); buffer.limit( nrOfBytes ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); byte data[] = new byte[ nrOfBytes ]; buffer.get( data ); record.setData( data ); return record; } private static final byte NODE_COMMAND = (byte) 1; private static final byte PROP_COMMAND = (byte) 2; private static final byte REL_COMMAND = (byte) 3; private static final byte REL_TYPE_COMMAND = (byte) 4; static class NodeCommand extends Command { private NodeRecord record; private NodeStore store; NodeCommand( NodeStore store, NodeRecord record ) { super( record.getId() ); this.record = record; this.store = store; } @Override public void execute() { if ( isInRecoveryMode() ) { logger.fine( this.toString() ); } try { store.updateRecord( record ); } catch ( IOException e ) { throw new RuntimeException( e ); } } public String toString() { return "NodeCommand[" + record + "]"; } @Override public void writeToFile( FileChannel fileChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.put( NODE_COMMAND ); buffer.putInt( record.getId() ).put( inUse ).putInt( record.getNextRel() ).putInt( record.getNextProp() ); buffer.flip(); fileChannel.write( buffer ); } static Command readCommand( NeoStore neoStore, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 13 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int id = buffer.getInt(); byte inUseFlag = buffer.get(); boolean inUse = false; if ( inUseFlag == Record.IN_USE.byteValue() ) { inUse = true; } else if ( inUseFlag != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } NodeRecord record = new NodeRecord( id ); record.setInUse( inUse ); record.setNextRel( buffer.getInt() ); record.setNextProp( buffer.getInt() ); return new NodeCommand( neoStore.getNodeStore(), record ); } public boolean equals( Object o ) { if ( !( o instanceof NodeCommand ) ) { return false; } return getKey().equals( ( ( NodeCommand ) o ).getKey() ); } private volatile int hashCode = 0; public int hashCode() { if ( hashCode == 0 ) { hashCode = 3217 * record.getId(); } return hashCode; } } static class RelationshipCommand extends Command { private RelationshipRecord record; private RelationshipStore store; RelationshipCommand( RelationshipStore store, RelationshipRecord record ) { super( record.getId() ); this.record = record; this.store = store; } @Override public void execute() { if ( isInRecoveryMode() ) { logger.fine( this.toString() ); } try { store.updateRecord( record ); } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public String toString() { return "RelationshipCommand[" + record + "]"; } @Override public void writeToFile( FileChannel fileChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.put( REL_COMMAND ); buffer.putInt( record.getId() ).put( inUse ).putInt( record.getFirstNode() ).putInt( record.getSecondNode() ).putInt( record.getType() ).putInt( record.getFirstPrevRel() ).putInt( record.getFirstNextRel() ).putInt( record.getSecondPrevRel() ).putInt( record.getSecondNextRel() ).putInt( record.getNextProp() ); buffer.flip(); fileChannel.write( buffer ); } static Command readCommand( NeoStore neoStore, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 37 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int id = buffer.getInt(); byte inUseFlag = buffer.get(); boolean inUse = false; if ( ( inUseFlag & Record.IN_USE.byteValue() ) == Record.IN_USE.byteValue() ) { inUse = true; } else if ( ( inUseFlag & Record.IN_USE.byteValue() ) != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } RelationshipRecord record = new RelationshipRecord( id, buffer.getInt(), buffer.getInt(), buffer.getInt() ); record.setInUse( inUse ); record.setFirstPrevRel( buffer.getInt() ); record.setFirstNextRel( buffer.getInt() ); record.setSecondPrevRel( buffer.getInt() ); record.setSecondNextRel( buffer.getInt() ); record.setNextProp( buffer.getInt() ); return new RelationshipCommand( neoStore.getRelationshipStore(), record ); } @Override public boolean equals( Object o ) { if ( !( o instanceof RelationshipCommand ) ) { return false; } return getKey().equals( ( ( RelationshipCommand ) o ).getKey() ); } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { hashCode = 3217 * record.getId(); } return hashCode; } } static class PropertyCommand extends Command { private PropertyRecord record; private PropertyStore store; PropertyCommand( PropertyStore store, PropertyRecord record ) { super( record.getId() ); this.record = record; this.store = store; } @Override public void execute() { if ( isInRecoveryMode() ) { logger.fine( this.toString() ); } try { store.updateRecord( record ); } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public String toString() { return "PropertyCommand[" + record + "]"; } @Override public void writeToFile( FileChannel fileChannel, ByteBuffer buffer ) throws IOException { // id+in_use(byte)+type(int)+key_blockId(int)+prop_blockId(long)+ // prev_prop_id(int)+next_prop_id(int)+nr_key_records(int)+ // nr_value_records(int) buffer.clear(); byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.put( PROP_COMMAND ); buffer.putInt( record.getId() ).put( inUse ).putInt( record.getType().intValue() ).putInt( record.getKeyBlock() ).putLong( record.getPropBlock() ).putInt( record.getPrevProp() ).putInt( record.getNextProp() ); Collection<DynamicRecord> keyRecords = record.getKeyRecords(); buffer.putInt( keyRecords.size() ); Collection<DynamicRecord> valueRecords = record.getValueRecords(); buffer.putInt( valueRecords.size() ); buffer.flip(); fileChannel.write( buffer ); for ( DynamicRecord keyRecord : keyRecords ) { writeDynamicRecord( keyRecord, fileChannel, buffer ); } for ( DynamicRecord valueRecord : valueRecords ) { writeDynamicRecord( valueRecord, fileChannel, buffer ); } } static Command readCommand( NeoStore neoStore, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { // id+in_use(byte)+type(int)+key_blockId(int)+prop_blockId(long)+ // prev_prop_id(int)+next_prop_id(int)+nr_key_records(int)+ // nr_value_records(int) buffer.clear(); buffer.limit( 37 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int id = buffer.getInt(); byte inUseFlag = buffer.get(); boolean inUse = false; if ( ( inUseFlag & Record.IN_USE.byteValue() ) == Record.IN_USE.byteValue() ) { inUse = true; } else if ( inUseFlag != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } PropertyType type = getType( buffer.getInt() ); PropertyRecord record = new PropertyRecord( id, type ); record.setInUse( inUse ); record.setKeyBlock( buffer.getInt() ); record.setPropBlock( buffer.getLong() ); record.setPrevProp( buffer.getInt() ); record.setNextProp( buffer.getInt() ); int nrKeyRecords = buffer.getInt(); int nrValueRecords = buffer.getInt(); for ( int i = 0; i < nrKeyRecords; i++ ) { DynamicRecord dr = readDynamicRecord( fileChannel, buffer ); if ( dr == null ) { return null; } record.addKeyRecord( dr ); } for ( int i = 0; i < nrValueRecords; i++ ) { DynamicRecord dr = readDynamicRecord( fileChannel, buffer ); if ( dr == null ) { return null; } record.addValueRecord( dr ); } return new PropertyCommand( neoStore.getPropertyStore(), record ); } private static PropertyType getType( int type ) { switch ( type ) { case 1: return PropertyType.INT; case 2: return PropertyType.STRING; case 3: return PropertyType.BOOL; case 4: return PropertyType.DOUBLE; case 5: return PropertyType.FLOAT; case 6: return PropertyType.LONG; case 7: return PropertyType.BYTE; case 8: return PropertyType.CHAR; case 9: return PropertyType.ARRAY; } throw new RuntimeException( "Unkown property type:" + type ); } @Override public boolean equals( Object o ) { if ( !( o instanceof PropertyCommand ) ) { return false; } return getKey().equals( ( ( PropertyCommand ) o ).getKey() ); } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { hashCode = 3217 * record.getId(); } return hashCode; } } static class RelationshipTypeCommand extends Command { private RelationshipTypeRecord record; private RelationshipTypeStore store; RelationshipTypeCommand( RelationshipTypeStore store, RelationshipTypeRecord record ) { super( record.getId() ); this.record = record; this.store = store; } @Override public void execute() { if ( isInRecoveryMode() ) { logger.fine( this.toString() ); } try { store.updateRecord( record ); } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public String toString() { return "RelationshipTypeCommand[" + record + "]"; } @Override public void writeToFile( FileChannel fileChannel, ByteBuffer buffer ) throws IOException { // id+in_use(byte)+type_blockId(int)+nr_type_records(int) buffer.clear(); byte inUse = record.inUse() ? Record.IN_USE.byteValue() : Record.NOT_IN_USE.byteValue(); buffer.put( REL_TYPE_COMMAND ); buffer.putInt( record.getId() ).put( inUse ).putInt( record.getTypeBlock() ); Collection<DynamicRecord> typeRecords = record.getTypeRecords(); buffer.putInt( typeRecords.size() ); buffer.flip(); fileChannel.write( buffer ); for ( DynamicRecord typeRecord : typeRecords ) { writeDynamicRecord( typeRecord, fileChannel, buffer ); } } static Command readCommand( NeoStore neoStore, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { // id+in_use(byte)+type_blockId(int)+nr_type_records(int) buffer.clear(); buffer.limit( 13 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); int id = buffer.getInt(); byte inUseFlag = buffer.get(); boolean inUse = false; if ( ( inUseFlag & Record.IN_USE.byteValue() ) == Record.IN_USE.byteValue() ) { inUse = true; } else if ( inUseFlag != Record.NOT_IN_USE.byteValue() ) { throw new IOException( "Illegal in use flag: " + inUseFlag ); } RelationshipTypeRecord record = new RelationshipTypeRecord( id ); record.setInUse( inUse ); record.setTypeBlock( buffer.getInt() ); int nrTypeRecords = buffer.getInt(); for ( int i = 0; i < nrTypeRecords; i++ ) { DynamicRecord dr = readDynamicRecord( fileChannel, buffer ); if ( dr == null ) { return null; } record.addTypeRecord( dr ); } return new RelationshipTypeCommand( neoStore.getRelationshipTypeStore(), record ); } @Override public boolean equals( Object o ) { if ( !( o instanceof RelationshipTypeCommand ) ) { return false; } return getKey().equals( ( ( RelationshipTypeCommand ) o ).getKey() ); } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { hashCode = 3217 * record.getId(); } return hashCode; } } static Command readCommand( NeoStore neoStore, FileChannel fileChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 1 ); if ( fileChannel.read( buffer ) != buffer.limit() ) { return null; } buffer.flip(); byte commandType = buffer.get(); switch ( commandType ) { case NODE_COMMAND: return NodeCommand.readCommand( neoStore, fileChannel, buffer ); case PROP_COMMAND: return PropertyCommand.readCommand( neoStore, fileChannel, buffer ); case REL_COMMAND: return RelationshipCommand.readCommand( neoStore, fileChannel, buffer ); case REL_TYPE_COMMAND: return RelationshipTypeCommand.readCommand( neoStore, fileChannel, buffer ); default: throw new IOException( "Unkown command type[" + commandType + "]" ); } } }
package dynamake.transcription; import java.io.Serializable; import java.util.Stack; import dynamake.models.Location; import dynamake.models.Model; public class VirtualMachine<T> { public interface VMInstruction extends Serializable { void execute(VMProcess scope); } public static class Instruction { public static final int TYPE_PUSH_REF_LOC = 0; public static final int TYPE_PUSH = 1; public static final int TYPE_POP = 2; public static final int TYPE_DUP = 3; public static final int TYPE_SWAP = 4; public static final int TYPE_STOP = 5; public static final int TYPE_JUMP = 6; public static final int TYPE_RET = 7; public static final int TYPE_EXIT = 8; public static final int TYPE_BEGIN_LOG = 9; public static final int TYPE_POST = 10; public static final int TYPE_END_LOG = 11; public static final int TYPE_COMMIT = 12; public static final int TYPE_REJECT = 13; public static final int TYPE_CUSTOM = 14; public final int type; public final Object operand; public Instruction(int type) { this.type = type; this.operand = null; } public Instruction(int type, Object operand) { this.type = type; this.operand = operand; } } private interface VMProcess { void pushReferenceLocation(); void push(Object value); Object pop(); Object peek(); void dup(); void swap(); void stop(); void jump(int delta); void ret(); void execute(Instruction[] body); } private static class Scope { public final Location referenceLocation; public final Stack<Object> stack = new Stack<Object>(); public int i; public final Instruction[] body; public Scope(Location referenceLocation, Instruction[] body) { this.referenceLocation = referenceLocation; this.body = body; } } private static class ScopedProcess implements VMProcess { public Scope currentScope; public Stack<Scope> scopeStack = new Stack<Scope>(); @Override public void pushReferenceLocation() { push(currentScope.referenceLocation); } @Override public void push(Object value) { currentScope.stack.push(value); } @Override public Object pop() { return currentScope.stack.pop(); } @Override public Object peek() { return currentScope.stack.peek(); } @Override public void dup() { currentScope.stack.push(currentScope.stack.peek()); } @Override public void swap() { Object top = currentScope.stack.get(currentScope.stack.size() - 1); currentScope.stack.set(currentScope.stack.size() - 1, currentScope.stack.get(currentScope.stack.size() - 2)); currentScope.stack.set(currentScope.stack.size() - 2, top); } @Override public void stop() { Scope stoppedScope = currentScope; currentScope = scopeStack.pop(); currentScope.stack.push(stoppedScope); // Push scope as "continuation" } @Override public void jump(int delta) { currentScope.i += delta; } @Override public void ret() { currentScope = scopeStack.pop(); } @Override public void execute(Instruction[] body) { scopeStack.push(new Scope(currentScope.referenceLocation, body)); } } public void execute(T reference, Instruction[] body) { ScopedProcess process = new ScopedProcess(); Location referenceLocation = ((Model)reference).getLocator().locate(); process.scopeStack.push(new Scope(referenceLocation, body)); boolean exitRequested = false; testShouldExit: if(!exitRequested) { while(true) { Instruction instruction = process.currentScope.body[process.currentScope.i]; switch(instruction.type) { case Instruction.TYPE_PUSH_REF_LOC: process.currentScope.stack.push(process.currentScope.referenceLocation); process.currentScope.i++; continue; case Instruction.TYPE_PUSH: process.currentScope.stack.push(instruction.operand); process.currentScope.i++; continue; case Instruction.TYPE_POP: process.currentScope.stack.pop(); process.currentScope.i++; continue; case Instruction.TYPE_DUP: process.currentScope.stack.push(process.currentScope.stack.peek()); process.currentScope.i++; continue; case Instruction.TYPE_SWAP: Object top = process.currentScope.stack.get(process.currentScope.stack.size() - 1); process.currentScope.stack.set(process.currentScope.stack.size() - 1, process.currentScope.stack.get(process.currentScope.stack.size() - 2)); process.currentScope.stack.set(process.currentScope.stack.size() - 2, top); process.currentScope.i++; continue; case Instruction.TYPE_STOP: Scope stoppedScope = process.currentScope; process.currentScope = process.scopeStack.pop(); process.currentScope.stack.push(stoppedScope); // Push scope as "continuation" // Otherwise, probably, history handler needs to be invoked here (instead) process.currentScope.i++; continue; case Instruction.TYPE_JUMP: process.currentScope.i += (int)instruction.operand; continue; case Instruction.TYPE_RET: process.currentScope = process.scopeStack.pop(); process.currentScope.i++; continue; case Instruction.TYPE_EXIT: exitRequested = true; break testShouldExit; case Instruction.TYPE_BEGIN_LOG: // Somehow, start a new log of some kind (for instance for adding new history, or changing the existing history, of a model) process.currentScope.i++; continue; case Instruction.TYPE_POST: // Somehow, pop and post to the log process.currentScope.i++; continue; case Instruction.TYPE_END_LOG: // Somehow, tell the logger to commit process.currentScope.i++; continue; case Instruction.TYPE_COMMIT: // Persist changes made since last commit process.currentScope.i++; continue; case Instruction.TYPE_REJECT: // Rollback changes made since last commit process.currentScope.i++; continue; case Instruction.TYPE_CUSTOM: VMInstruction customInstruction = (VMInstruction)instruction.operand; customInstruction.execute(process); process.currentScope.i++; continue; } } } } }
/** * Given a binary tree, flatten it to a linked list in-place. * * For example, * Given * * 1 * / \ * 2 5 * / \ \ * 3 4 6 * The flattened tree should look like: * 1 * \ * 2 * \ * 3 * \ * 4 * \ * 5 * \ * 6 * * Hints: * If you notice carefully in the flattened tree, each node's right child * points to the next node of a pre-order traversal. * * Tags: Tree, DFS */ class FlatenBinaryTreeToLinkedList { public static void main(String[] args) { } /** * Add root's right subtree to left node's rightmost child * Then set the root's left subtree as root's right subtree * And set root's left child to null * Move root to its right child and repeat */ public void flatten(TreeNode root) { while (root != null) { if (root.left != null) { // check left child TreeNode n = root.left; while (n.right != null) n = n.right; // rightmost child of left n.right = root.right; // insert right subtree to its right (acsending order, if descending, don't need this step) root.right = root.left; // set left subtree as right subtree root.left = null; // set left to null } root = root.right; // move to right child } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
package com.restfb.types; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import com.restfb.Facebook; import com.restfb.util.DateUtils; import com.restfb.util.ReflectionUtils; public class Photo extends NamedFacebookType { @Facebook private CategorizedFacebookType from; @Facebook private String picture; @Facebook private String source; @Facebook private Integer height; @Facebook private Integer width; @Facebook private String link; @Facebook private String icon; @Facebook("created_time") private String createdTime; @Facebook("updated_time") private String updatedTime; @Facebook(contains = Tag.class) private List<Tag> tags = new ArrayList<Tag>(); public static class Tag extends NamedFacebookType { @Facebook private Integer x; @Facebook private Integer y; @Facebook("created_time") private String createdTime; /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return ReflectionUtils.hashCode(this); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object that) { return ReflectionUtils.equals(this, that); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return ReflectionUtils.toString(this); } /** * X coordinate (as a percentage of distance from left vs. width). * * @return X coordinate (as a percentage of distance from left vs. width). */ public Integer getX() { return x; } /** * Y coordinate (as a percentage of distance from top vs. height). * * @return Y coordinate (as a percentage of distance from top vs. height). */ public Integer getY() { return y; } /** * Date this tag was created. * * @return Date this tag was created. */ public Date getCreatedTime() { return DateUtils.toDateFromLongFormat(createdTime); } } /** * An object containing the name and ID of the user who posted the photo. * * @return An object containing the name and ID of the user who posted the * photo. */ public CategorizedFacebookType getFrom() { return from; } /** * The album-sized view of the photo. * * @return The album-sized view of the photo. */ public String getPicture() { return picture; } /** * The full-sized source of the photo. * * @return The full-sized source of the photo. */ public String getSource() { return source; } /** * The height of the photo, in pixels. * * @return The height of the photo, in pixels. */ public Integer getHeight() { return height; } /** * The width of the photo, in pixels. * * @return The width of the photo, in pixels. */ public Integer getWidth() { return width; } /** * A link to the photo on Facebook. * * @return A link to the photo on Facebook. */ public String getLink() { return link; } /** * The icon-sized source of the photo. * * @return The icon-sized source of the photo. */ public String getIcon() { return icon; } /** * The time the photo was initially published. * * @return The time the photo was initially published. */ public Date getCreatedTime() { return DateUtils.toDateFromLongFormat(createdTime); } /** * The last time the photo or its caption was updated. * * @return The last time the photo or its caption was updated. */ public Date getUpdatedTime() { return DateUtils.toDateFromLongFormat(updatedTime); } /** * An array containing the users and their positions in this photo. The x and * y coordinates are percentages from the left and top edges of the photo, * respectively. * * @return An array containing the users and their positions in this photo. * The x and y coordinates are percentages from the left and top edges * of the photo, respectively. */ public List<Tag> getTags() { return Collections.unmodifiableList(tags); } }
package com.nexstream.konnectedsdk; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import org.json.JSONException; import org.json.JSONObject; public class PaymentActivity extends AppCompatActivity { WebView myWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String package_name = getApplication().getPackageName(); Resources resources = getApplication().getResources(); setContentView(resources.getIdentifier("activity_payment", "layout", package_name)); myWebView = (WebView) findViewById(resources.getIdentifier("webview", "id", package_name)); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new WebAppInterface(this), "Android"); myWebView.loadUrl(getIntent().getExtras().getString("url")); myWebView.setWebViewClient(new WebViewClient()); } public class WebAppInterface { Context mContext; WebAppInterface(Context c) { mContext = c; } @JavascriptInterface public void paymentResult(String json) { try { JSONObject jsonObj = new JSONObject(json); Bundle conData = new Bundle(); conData.putString("amount", jsonObj.getString("amount")); conData.putString("status", jsonObj.getString("status")); conData.putString("code", jsonObj.getString("code")); conData.putString("desc", jsonObj.getString("desc")); conData.putString("tranId", jsonObj.getString("tranId")); Intent intent = new Intent(); intent.putExtras(conData); setResult(RESULT_OK, intent); } catch (JSONException e) { e.printStackTrace(); } finish(); } } }
package com.buschmais.cdo.api; import java.util.Map; /** * Defines methods to manage the lifecycle of composite instances, query execution and transaction management. */ public interface CdoManager { /** * Begin a transaction. */ void begin(); /** * Commit all changes of the current transaction. */ void commit(); /** * Rollback all changes from the current transaction. */ void rollback(); /** * Find all composite instances according to the given type and value (e.g. from an index). * * @param <T> The composite type. * @param type The interface of the composite type. * @param value The value. * @return An {@Iterable} returning the composite instance. */ <T> Iterable<T> find(Class<T> type, Object value); /** * Create a new composite instance. * * @param <T> The expected return type. Note that it must be assignable to at least one of the interfaces specified for the types. * @param types The interfaces the composite type shall implement. * @return The composite instance. */ <T> T create(Class<?>... types); /** * Migrates the type of a composite instance to the given target and returns it. The original instance will not be usable anymore after migration. * * @param <T> The composite type. * @param <M> The migrated composite type. Note that it be assignable to at least one of the interfaces specified for types. * @param instance The instance. * @param targetTypes The target interfaces which shall be implemented by the migrated instance.. * @return The migrated instance. */ <T, M> M migrate(T instance, Class<?>... targetTypes); /** * Migrates the type of a composite instance to the given target and returns it. The original instance will not be usable anymore after migration. * * @param <T> The composite type. * @param <M> The migrated composite type. Note that it be assignable to at least one of the interfaces specified for types. * @param instance The instance. * @param migrationHandler The {@link MigrationHandler} to be used to migrate data (e.g. properties) to the new type. * @param targetTypes The target interfaces which shall be implemented by the migrated instance.. * @return The migrated instance. */ <T, M> M migrate(T instance, MigrationHandler<T, M> migrationHandler, Class<?>... targetTypes); /** * Deletes a composite instance. * * @param <T> The composite type. * @param instance The instance. */ <T> void delete(T instance); QueryResult executeQuery(String query); QueryResult executeQuery(String query, Map<String, Object> parameters); /** * Close the {@CdoManager}. */ void close(); interface MigrationHandler<T, M> { void migrate(T instance, M target); } }
package com.github.podd.utils; import info.aduna.iteration.Iterations; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import org.openrdf.OpenRDFException; import org.openrdf.model.Model; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.LinkedHashModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.model.vocabulary.OWL; import org.openrdf.query.GraphQuery; import org.openrdf.query.QueryResults; import org.openrdf.query.TupleQuery; import org.openrdf.query.impl.DatasetImpl; import org.openrdf.query.resultio.helpers.QueryResultCollector; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParser; import org.openrdf.rio.Rio; import org.openrdf.rio.helpers.StatementCollector; import org.openrdf.sail.memory.MemoryStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author kutila * */ public class RdfUtility { private final static Logger log = LoggerFactory.getLogger(RdfUtility.class); /** * Helper method to execute a given SPARQL Graph query. * * @param graphQuery * @param contexts * @return * @throws OpenRDFException */ public static Model executeGraphQuery(final GraphQuery graphQuery, final URI... contexts) throws OpenRDFException { final DatasetImpl dataset = new DatasetImpl(); for(final URI uri : contexts) { dataset.addDefaultGraph(uri); } graphQuery.setDataset(dataset); final Model results = new LinkedHashModel(); final long before = System.currentTimeMillis(); graphQuery.evaluate(new StatementCollector(results)); final long total = System.currentTimeMillis() - before; RdfUtility.log.debug("graph query took {}", Long.toString(total)); if(total > 50 && RdfUtility.log.isDebugEnabled()) { new Throwable().printStackTrace(); } else if(total > 30 && RdfUtility.log.isTraceEnabled()) { new Throwable().printStackTrace(); } return results; } /** * Helper method to execute a given SPARQL Tuple query, which may have had bindings attached. * * @param tupleQuery * @param contexts * @return * @throws OpenRDFException */ public static QueryResultCollector executeTupleQuery(final TupleQuery tupleQuery, final URI... contexts) throws OpenRDFException { final DatasetImpl dataset = new DatasetImpl(); for(final URI uri : contexts) { dataset.addDefaultGraph(uri); } tupleQuery.setDataset(dataset); final QueryResultCollector results = new QueryResultCollector(); final long before = System.currentTimeMillis(); QueryResults.report(tupleQuery.evaluate(), results); final long total = System.currentTimeMillis() - before; RdfUtility.log.debug("tuple query took {}", Long.toString(total)); if(total > 50 && RdfUtility.log.isDebugEnabled()) { new Throwable().printStackTrace(); } else if(total > 30 && RdfUtility.log.isTraceEnabled()) { new Throwable().printStackTrace(); } return results; } /** * Given a set of RDF Statements, and a Root node, this method finds any nodes that are not * connected to the Root node. * * A <b>Node</b> is a Value that is of type URI (i.e. Literals are ignored). * * A direct connection between two nodes exist if there is a Statement with the two nodes as the * Subject and the Object. * * @param root * The Root of the Graph, from which connectedness is calculated. * @param connection * A RepositoryConnection * @param context * The Graph containing statements. * @return A <code>Set</code> containing any URIs that are not connected to the Root. * @throws RepositoryException */ public static Set<URI> findDisconnectedNodes(final URI root, final RepositoryConnection connection, final URI... context) throws RepositoryException { final List<URI> exclusions = Arrays.asList(new URI[] { root, OWL.THING, OWL.ONTOLOGY, OWL.INDIVIDUAL, ValueFactoryImpl.getInstance().createURI("http://www.w3.org/2002/07/owl#NamedIndividual"), }); // - identify nodes that should be connected to the root final Set<URI> nodesToCheck = new HashSet<URI>(); final List<Statement> allStatements = Iterations.asList(connection.getStatements(null, null, null, false, context)); for(final Statement s : allStatements) { final Value objectValue = s.getObject(); if(objectValue instanceof URI && !exclusions.contains(objectValue)) { nodesToCheck.add((URI)objectValue); } final Value subjectValue = s.getSubject(); if(subjectValue instanceof URI && !exclusions.contains(subjectValue)) { nodesToCheck.add((URI)subjectValue); } } // RdfUtility.log.info("{} nodes to check for connectivity.", nodesToCheck.size()); // for(final URI u : objectsToCheck) // System.out.println(" " + u); // - check for connectivity final Queue<URI> queue = new LinkedList<URI>(); final Set<URI> visitedNodes = new HashSet<URI>(); // to handle cycles queue.add(root); visitedNodes.add(root); while(!queue.isEmpty()) { final URI currentNode = queue.remove(); final List<URI> children = RdfUtility.getImmediateChildren(currentNode, connection, context); for(final URI child : children) { // visit child node if(nodesToCheck.contains(child)) { nodesToCheck.remove(child); if(nodesToCheck.isEmpty()) { // all identified nodes are connected. return nodesToCheck; } } if(!visitedNodes.contains(child)) { queue.add(child); visitedNodes.add(child); } } } RdfUtility.log.debug("{} unconnected node(s). {}", nodesToCheck.size(), nodesToCheck); return nodesToCheck; } /** * Internal helper method to retrieve the direct child objects of a given object. * * @param node * @param connection * @param context * @return * @throws RepositoryException */ private static List<URI> getImmediateChildren(final URI node, final RepositoryConnection connection, final URI... context) throws RepositoryException { final List<URI> children = new ArrayList<URI>(); final List<Statement> childStatements = Iterations.asList(connection.getStatements(node, null, null, false, context)); for(final Statement s : childStatements) { if(s.getObject() instanceof URI) { children.add((URI)s.getObject()); } } return children; } /** * Helper method to load an {@link InputStream} into an {@link Model}. * * @param resourceStream * The input stream with RDF statements * @param format * Format found in the input RDF data * @return an {@link Model} populated with the statements from the input stream. * * @throws OpenRDFException * @throws IOException */ public static Model inputStreamToModel(final InputStream resourceStream, final RDFFormat format) throws OpenRDFException, IOException { if(resourceStream == null) { throw new IOException("Inputstream was null"); } return Rio.parse(resourceStream, "", format); } /** * Given an artifact, this method evaluates whether all Objects within the artifact are * connected to the Top Object. * * @param inputStream * Input stream containing the artifact statements * @param format * The RDF format in which the statements are provided * @return True if the artifact is structurally valid, false otherwise */ public static boolean isConnectedStructure(final InputStream inputStream, RDFFormat format) { if(inputStream == null) { throw new NullPointerException("Input stream must not be null"); } if(format == null) { format = RDFFormat.RDFXML; } final URI context = ValueFactoryImpl.getInstance().createURI("urn:concrete:random"); Repository tempRepository = null; RepositoryConnection connection = null; try { // create a temporary in-memory repository tempRepository = new SailRepository(new MemoryStore()); tempRepository.initialize(); connection = tempRepository.getConnection(); connection.begin(); // load artifact statements into repository connection.add(inputStream, "", format, context); // DebugUtils.printContents(connection, context); return RdfUtility.isConnectedStructure(connection, context); } catch(final Exception e) { // better to throw an exception containing error details RdfUtility.log.error("An exception in checking connectedness of artifact", e); return false; } finally { try { if(connection != null && connection.isOpen()) { connection.rollback(); connection.close(); } if(tempRepository != null) { tempRepository.shutDown(); } } catch(final Exception e) { RdfUtility.log.error("Exception while releasing resources", e); } } } /** * Given an artifact, this method evaluates whether all Objects within the artifact are * connected to the Top Object. * * @param connection * The RepositoryConnection * @param context * The Context within the RepositoryConnection. * @return True if all internal objects are connected to the top object, false otherwise. * @throws RepositoryException */ public static boolean isConnectedStructure(final RepositoryConnection connection, final URI... context) throws RepositoryException { // - find artifact and top object URIs final List<Statement> topObjects = Iterations.asList(connection.getStatements(null, PODD.PODD_BASE_HAS_TOP_OBJECT, null, false, context)); if(topObjects.size() != 1) { RdfUtility.log.info("Artifact should have exactly 1 Top Object"); return false; } final URI artifactUri = (URI)topObjects.get(0).getSubject(); final Set<URI> disconnectedNodes = RdfUtility.findDisconnectedNodes(artifactUri, connection, context); if(disconnectedNodes == null || disconnectedNodes.isEmpty()) { return true; } else { return false; } } }
package test.beast.app.beauti; import java.io.File; import org.fest.swing.fixture.JTabbedPaneFixture; import org.junit.Test; public class SimpleClockModelTest extends BeautiBase { /** check the standard clock models are there and result in correct behaviour **/ @Test public void simpleClockModelTest() throws Exception { warning("Load anolis.nex"); importAlignment("examples/nexus", new File("anolis.nex")); JTabbedPaneFixture f = beautiFrame.tabbedPane(); f.selectTab("Clock Model"); warning("Change to Relaxed Clock - exponential"); beautiFrame.comboBox().selectItem("Relaxed Clock Exponential"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "birthRate.t:anolis", "expRateCategories.c:anolis"); assertOperatorsEqual("YuleBirthRateScaler.t:anolis", "YuleModelTreeScaler.t:anolis", "YuleModelTreeRootScaler.t:anolis", "YuleModelUniformOperator.t:anolis", "YuleModelSubtreeSlide.t:anolis", "YuleModelNarrow.t:anolis", "YuleModelWide.t:anolis", "YuleModelWilsonBalding.t:anolis", "ExpCategoriesRandomWalk.c:anolis", "ExpCategoriesSwapOperator.c:anolis", "ExpCategoriesUniform.c:anolis"); assertPriorsEqual("YuleModel.t:anolis", "YuleBirthRatePrior.t:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "YuleModel.t:anolis", "birthRate.t:anolis", "rateStat.c:anolis"); warning("Change to Relaxed Clock - log normal"); beautiFrame.comboBox().selectItem("Relaxed Clock Log Normal"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "birthRate.t:anolis", "ucldStdev.c:anolis", "rateCategories.c:anolis"); assertOperatorsEqual("YuleBirthRateScaler.t:anolis", "YuleModelTreeScaler.t:anolis", "YuleModelTreeRootScaler.t:anolis", "YuleModelUniformOperator.t:anolis", "YuleModelSubtreeSlide.t:anolis", "YuleModelNarrow.t:anolis", "YuleModelWide.t:anolis", "YuleModelWilsonBalding.t:anolis", "ucldStdevScaler.c:anolis", "CategoriesRandomWalk.c:anolis", "CategoriesSwapOperator.c:anolis", "CategoriesUniform.c:anolis"); assertPriorsEqual("YuleModel.t:anolis", "YuleBirthRatePrior.t:anolis", "ucldStdevPrior.c:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "YuleModel.t:anolis", "birthRate.t:anolis", "ucldStdev.c:anolis", "rate.c:anolis"); warning("Change to Random Local Clock"); beautiFrame.comboBox().selectItem("Random Local Clock"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "birthRate.t:anolis", "Indicators.c:anolis", "clockrates.c:anolis"); assertOperatorsEqual("YuleBirthRateScaler.t:anolis", "YuleModelTreeScaler.t:anolis", "YuleModelTreeRootScaler.t:anolis", "YuleModelUniformOperator.t:anolis", "YuleModelSubtreeSlide.t:anolis", "YuleModelNarrow.t:anolis", "YuleModelWide.t:anolis", "YuleModelWilsonBalding.t:anolis", "IndicatorsBitFlip.c:anolis", "ClockRateScaler.c:anolis"); assertPriorsEqual("YuleModel.t:anolis", "YuleBirthRatePrior.t:anolis", "RRatesPrior.c:sanolis", "RRateChangesPrior.c:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "YuleModel.t:anolis", "birthRate.t:anolis", "Indicators.c:anolis", "clockrates.c:anolis", "RRateChanges.c:anolis"); warning("Change to Strickt Clock"); beautiFrame.comboBox().selectItem("Strict Clock"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "birthRate.t:anolis"); assertOperatorsEqual("YuleBirthRateScaler.t:anolis", "YuleModelTreeScaler.t:anolis", "YuleModelTreeRootScaler.t:anolis", "YuleModelUniformOperator.t:anolis", "YuleModelSubtreeSlide.t:anolis", "YuleModelNarrow.t:anolis", "YuleModelWide.t:anolis", "YuleModelWilsonBalding.t:anolis"); assertPriorsEqual("YuleModel.t:anolis", "YuleBirthRatePrior.t:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "YuleModel.t:anolis", "birthRate.t:anolis"); makeSureXMLParses(); } /** switch to coalescent tree prior, then * check the standard clock models are there and result in correct behaviour **/ @Test public void simpleClockModelTest2() throws Exception { warning("Load anolis.nex"); importAlignment("examples/nexus", new File("anolis.nex")); JTabbedPaneFixture f = beautiFrame.tabbedPane(); f.selectTab("Priors"); warning("Change to Coalescent - constant population"); beautiFrame.comboBox("TreeDistribution").selectItem("Coalescent Constant Population"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "popSize.t:anolis"); assertOperatorsEqual("CoalescentConstantTreeScaler.t:anolis", "CoalescentConstantTreeRootScaler.t:anolis", "CoalescentConstantUniformOperator.t:anolis", "CoalescentConstantSubtreeSlide.t:anolis", "CoalescentConstantNarrow.t:anolis", "CoalescentConstantWide.t:anolis", "CoalescentConstantWilsonBalding.t:anolis", "PopSizeScaler.t:anolis"); assertPriorsEqual("CoalescentConstant.t:anolis", "PopSizePrior.t:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "popSize.t:anolis", "CoalescentConstant.t:anolis"); f.selectTab("Clock Model"); warning("Change to Relaxed Clock - exponential"); beautiFrame.comboBox().selectItem("Relaxed Clock Exponential"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "popSize.t:anolis", "expRateCategories.c:anolis"); assertOperatorsEqual("CoalescentConstantTreeScaler.t:anolis", "CoalescentConstantTreeRootScaler.t:anolis", "CoalescentConstantUniformOperator.t:anolis", "CoalescentConstantSubtreeSlide.t:anolis", "CoalescentConstantNarrow.t:anolis", "CoalescentConstantWide.t:anolis", "CoalescentConstantWilsonBalding.t:anolis", "PopSizeScaler.t:anolis", "ExpCategoriesRandomWalk.c:anolis", "ExpCategoriesSwapOperator.c:anolis", "ExpCategoriesUniform.c:anolis"); assertPriorsEqual("CoalescentConstant.t:anolis", "PopSizePrior.t:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "popSize.t:anolis", "CoalescentConstant.t:anolis", "rateStat.c:anolis"); warning("Change to Relaxed Clock - log normal"); beautiFrame.comboBox().selectItem("Relaxed Clock Log Normal"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "popSize.t:anolis", "ucldStdev.c:anolis", "rateCategories.c:anolis"); assertOperatorsEqual("CoalescentConstantTreeScaler.t:anolis", "CoalescentConstantTreeRootScaler.t:anolis", "CoalescentConstantUniformOperator.t:anolis", "CoalescentConstantSubtreeSlide.t:anolis", "CoalescentConstantNarrow.t:anolis", "CoalescentConstantWide.t:anolis", "CoalescentConstantWilsonBalding.t:anolis", "PopSizeScaler.t:anolis", "ucldStdevScaler.c:anolis", "CategoriesRandomWalk.c:anolis", "CategoriesSwapOperator.c:anolis", "CategoriesUniform.c:anolis"); assertPriorsEqual("CoalescentConstant.t:anolis", "PopSizePrior.t:anolis", "ucldStdevPrior.c:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "popSize.t:anolis", "CoalescentConstant.t:anolis", "ucldStdev.c:anolis", "rate.c:anolis"); warning("Change to Random Local Clock"); beautiFrame.comboBox().selectItem("Random Local Clock"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "popSize.t:anolis", "Indicators.c:anolis", "clockrates.c:anolis"); assertOperatorsEqual("CoalescentConstantTreeScaler.t:anolis", "CoalescentConstantTreeRootScaler.t:anolis", "CoalescentConstantUniformOperator.t:anolis", "CoalescentConstantSubtreeSlide.t:anolis", "CoalescentConstantNarrow.t:anolis", "CoalescentConstantWide.t:anolis", "CoalescentConstantWilsonBalding.t:anolis", "PopSizeScaler.t:anolis", "IndicatorsBitFlip.c:anolis", "ClockRateScaler.c:anolis"); assertPriorsEqual("CoalescentConstant.t:anolis", "PopSizePrior.t:anolis", "RRatesPrior.c:sanolis", "RRateChangesPrior.c:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "popSize.t:anolis", "CoalescentConstant.t:anolis", "Indicators.c:anolis", "clockrates.c:anolis", "RRateChanges.c:anolis"); warning("Change to Strickt Clock"); beautiFrame.comboBox().selectItem("Strict Clock"); printBeautiState(f); assertStateEquals("Tree.t:anolis", "popSize.t:anolis"); assertOperatorsEqual("CoalescentConstantTreeScaler.t:anolis", "CoalescentConstantTreeRootScaler.t:anolis", "CoalescentConstantUniformOperator.t:anolis", "CoalescentConstantSubtreeSlide.t:anolis", "CoalescentConstantNarrow.t:anolis", "CoalescentConstantWide.t:anolis", "CoalescentConstantWilsonBalding.t:anolis", "PopSizeScaler.t:anolis"); assertPriorsEqual("CoalescentConstant.t:anolis", "PopSizePrior.t:anolis"); assertTraceLogEqual("posterior", "likelihood", "prior", "treeLikelihood.anolis", "TreeHeight.t:anolis", "popSize.t:anolis", "CoalescentConstant.t:anolis"); makeSureXMLParses(); } }
package com.apruve; import static org.junit.Assert.*; import org.junit.Test; public class ApruveEnvironmentTest { @Test public void testBaseUrl() { assertEquals("https://app.apruve.com", ApruveEnvironment.PROD.getBaseUrl()); assertEquals("https://test.apruve.com", ApruveEnvironment.TEST.getBaseUrl()); } @Test public void testApiUrl() { assertEquals("https://app.apruve.com/api/v3", ApruveEnvironment.PROD.getApiV3Url()); assertEquals("https://test.apruve.com/api/v3", ApruveEnvironment.TEST.getApiV3Url()); } @Test public void testJsUrl() { assertEquals("https://app.apruve.com/js/apruve.js", ApruveEnvironment.PROD.getJsUrl()); assertEquals("https://test.apruve.com/js/apruve.js", ApruveEnvironment.TEST.getJsUrl()); } @Test public void testJsTag() { assertEquals("<script src=\"https://app.apruve.com/js/apruve.js\" type=\"text/javascript\"></script>", ApruveEnvironment.PROD.getJsTag()); assertEquals("<script src=\"https://test.apruve.com/js/apruve.js\" type=\"text/javascript\"></script>", ApruveEnvironment.TEST.getJsTag()); } }
package net.anotheria.moskito.web; import net.anotheria.moskito.core.dynamic.EntryCountLimitedOnDemandStatsProducer; import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer; import net.anotheria.moskito.core.dynamic.OnDemandStatsProducerException; import net.anotheria.moskito.core.predefined.Constants; import net.anotheria.moskito.core.predefined.FilterStats; import net.anotheria.moskito.core.predefined.FilterStatsFactory; import net.anotheria.moskito.core.registry.ProducerRegistryFactory; import net.anotheria.moskito.core.stats.Interval; import org.apache.log4j.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; /** * Base class for filter based traffic monitoring. */ public abstract class MoskitoFilter implements Filter{ /** * Logger instance, available for all subclasses. */ protected Logger log; /** * Parameter name for the init parameter for the limit of dynamic case names (number of names) in the filter config. If the number of cases will exceed this limit, * the new cases will be ignored (to prevent memory leakage). */ public static final String INIT_PARAM_LIMIT = "limit"; /** * Constant for use-cases which are over limit. In case we gather all request urls and we set a limit of 1000 it may well happen, that we actually have more than the set limit. * In this case it is good to know how many requests those, 'other' urls produce. */ public static final String OTHER = "-other-"; /** * Cached object for stats that are not covered by gathered stats. */ private FilterStats otherStats = null; /** * The internal producer instance. */ private OnDemandStatsProducer<FilterStats> onDemandProducer; protected MoskitoFilter(){ log = Logger.getLogger(getClass()); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (onDemandProducer==null){ log.error("Access to filter before it's inited!"); chain.doFilter(req, res); return; } FilterStats defaultStats = onDemandProducer.getDefaultStats(); FilterStats caseStats = null; String caseName = extractCaseName(req, res); try{ if (caseName!=null) caseStats = onDemandProducer.getStats(caseName); }catch(OnDemandStatsProducerException e){ log.info("Couldn't get stats for case : "+caseName+", probably limit reached"); caseStats = otherStats; } defaultStats.addRequest(); if (caseStats!=null) caseStats.addRequest(); try{ long startTime = System.nanoTime(); chain.doFilter(req, res); long exTime = System.nanoTime() - startTime; defaultStats.addExecutionTime(exTime); if (caseStats!=null) caseStats.addExecutionTime(exTime); }catch(ServletException e){ defaultStats.notifyServletException(); if (caseStats!=null) caseStats.notifyServletException(); throw e; }catch(IOException e){ defaultStats.notifyIOException(); if (caseStats!=null) caseStats.notifyIOException(); throw e; }catch(RuntimeException e){ defaultStats.notifyRuntimeException(); if (caseStats!=null) caseStats.notifyRuntimeException(); throw e; }catch(Error e){ defaultStats.notifyError(); if (caseStats!=null) caseStats.notifyError(); throw e; }finally{ defaultStats.notifyRequestFinished(); if (caseStats!=null) caseStats.notifyRequestFinished(); } } @Override public void init(FilterConfig config) throws ServletException { int limit = -1; String pLimit = config.getInitParameter(INIT_PARAM_LIMIT); if (pLimit!=null) try{ limit = Integer.parseInt(pLimit); }catch(NumberFormatException ignored){ log.warn("couldn't parse limit \""+pLimit+"\", assume -1 aka no limit."); } onDemandProducer = limit == -1 ? new OnDemandStatsProducer<FilterStats>(getProducerId(), getCategory(), getSubsystem(), new FilterStatsFactory(getMonitoringIntervals())) : new EntryCountLimitedOnDemandStatsProducer<FilterStats>(getProducerId(), getCategory(), getSubsystem(), new FilterStatsFactory(getMonitoringIntervals()), limit); ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(onDemandProducer); //force request uri filter to create 'other' stats. try{ if (limit!=-1) otherStats = onDemandProducer.getStats(OTHER); }catch(OnDemandStatsProducerException e){ log.error("Can't create default stats for limit excess", e); } } @Override public void destroy(){ } /** * Overwrite this to provide a name allocation mechanism to make request -> name mapping. * @param req ServletRequest. * @param res ServletResponse. * @return name of the use case for stat storage. */ protected abstract String extractCaseName(ServletRequest req, ServletResponse res ); /** * Returns the producer id. Override this method if you want a useful name in your logs. Default is class name. */ public String getProducerId() { return getClass().getSimpleName(); } /** * Overwrite this method to register the filter in a category of your choice. Default is 'filter'. * @return the category of this producer. */ protected String getCategory() { return "filter"; } /** * Override this to register the filter as specially defined subsystem. Default is 'default'. * @return the subsystem of this producer. */ protected String getSubsystem(){ return "default"; } protected Interval[] getMonitoringIntervals(){ return Constants.getDefaultIntervals(); } protected OnDemandStatsProducer<FilterStats> getProducer(){ return onDemandProducer; } protected FilterStats getOtherStats(){ return otherStats; } }
package com.github.underscore; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.junit.jupiter.api.Test; /** * Underscore library unit test. * * @author Valentyn Kolesnikov */ class ArraysTest { /* _.first([5, 4, 3, 2, 1]); => 5 _.first([5, 4, 3, 2, 1], 2); => [5, 4] */ @Test void first() { // static, chain, object assertEquals("5", Underscore.first(asList(5, 4, 3, 2, 1)).toString()); assertEquals("5", Underscore.chain(asList(5, 4, 3, 2, 1)).first().item().toString()); assertEquals("0", new Underscore<>(Underscore.range(3)).first().toString()); // static, chain, object with int assertEquals("[5, 4]", Underscore.chain(asList(5, 4, 3, 2, 1)).first(2).value().toString()); assertEquals("[5, 4]", Underscore.first(asList(5, 4, 3, 2, 1), 2).toString()); assertEquals("[0, 1]", new Underscore<>(Underscore.range(3)).first(2).toString()); // static, chain, object with larger int assertEquals("[a, b]", Underscore.first(asList("a", "b"), 4).toString()); assertEquals("[a, b]", Underscore.chain(asList("a", "b")).first(4).toString()); assertEquals("[0, 1, 2]", new Underscore<>(Underscore.range(3)).first(4).toString()); // static, chain, object with wrong int assertEquals("[]", Underscore.first(asList("a", "b"), 0).toString()); assertEquals("[]", Underscore.first(Underscore.range(3), -2).toString()); assertEquals("[]", new Underscore<>(Underscore.range(3)).first(0).toString()); assertEquals("[]", new Underscore<>(Underscore.range(3)).first(-1).toString()); assertEquals("[]", Underscore.chain(singletonList("a")).first(-100).value().toString()); // array assertEquals(5, Underscore.first(new Integer[] {5, 4, 3, 2, 1}).intValue()); // static, chain, object with predicate final int resultPred = Underscore.first(asList(5, 4, 3, 2, 1), item -> item % 2 == 0); assertEquals(4, resultPred); final int resultPredObj = new Underscore<>(asList(5, 4, 3, 2, 1)).first(item -> item % 2 == 0); assertEquals(4, resultPredObj); final int resultChainPred = Underscore.chain(asList(5, 4, 3, 2, 1)).first(item -> item % 2 == 0).item(); assertEquals(4, resultChainPred); // static, chain, object with predicate and int final List<Integer> result1 = new Underscore<>(Underscore.range(7)).first(item -> item % 2 == 0, 2); assertEquals("[0, 2]", result1.toString()); final List<Integer> result2 = Underscore.first(Underscore.range(7), item -> item < 1, 4); assertEquals("[0]", result2.toString()); final Underscore.Chain<Integer> result3 = Underscore.chain(Underscore.range(7)).first(item -> item < 2, 4); assertEquals("[0, 1]", result3.toString()); final List<Integer> result4 = new Underscore<>(Underscore.range(3)).first(item -> item > 2, -5); assertEquals("[]", result4.toString()); final List<String> result5 = Underscore.first(asList("aa", "bbbb"), item -> item.length() < 3, -2); assertEquals("[]", result5.toString()); final Underscore.Chain<Integer> result6 = Underscore.chain(Underscore.range(7)).first(item -> item < 2, -1); assertEquals("[]", result6.toString()); } @Test void firstOrNull() { final Integer result = Underscore.firstOrNull(asList(5, 4, 3, 2, 1)); assertEquals("5", result.toString()); final Integer resultObj = new Underscore<>(asList(5, 4, 3, 2, 1)).firstOrNull(); assertEquals("5", resultObj.toString()); final Integer resultChain = Underscore.chain(asList(5, 4, 3, 2, 1)).firstOrNull().item(); assertEquals("5", resultChain.toString()); assertNull(Underscore.firstOrNull(Collections.emptyList())); assertNull(new Underscore<>(Collections.<Integer>emptyList()).firstOrNull()); final int resultPred = Underscore.firstOrNull(asList(5, 4, 3, 2, 1), item -> item % 2 == 0); assertEquals(4, resultPred); final int resultPredChain = Underscore.chain(asList(5, 4, 3, 2, 1)).firstOrNull(item -> item % 2 == 0).item(); assertEquals(4, resultPredChain); assertNull(Underscore.firstOrNull(Collections.<Integer>emptyList(), item -> item % 2 == 0)); final int resultPredObj = new Underscore<>(asList(5, 4, 3, 2, 1)).firstOrNull(item -> item % 2 == 0); assertEquals(4, resultPredObj); assertNull( new Underscore<>(Collections.<Integer>emptyList()) .firstOrNull(item -> item % 2 == 0)); } @Test @SuppressWarnings("unchecked") void firstEmpty() { List<Object> iterable = Collections.emptyList(); assertThrows(NoSuchElementException.class, () -> Underscore.first(iterable)); } /* _.head([5, 4, 3, 2, 1]); => 5 _.head([5, 4, 3, 2, 1], 2); => [5, 4] */ @Test void head() { final Integer result = Underscore.head(asList(5, 4, 3, 2, 1)); assertEquals("5", result.toString()); final Integer resultObj = new Underscore<>(asList(5, 4, 3, 2, 1)).head(); assertEquals("5", resultObj.toString()); final List<Integer> resultList = Underscore.head(asList(5, 4, 3, 2, 1), 2); assertEquals("[5, 4]", resultList.toString()); final List<Integer> resultListObj = new Underscore<>(asList(5, 4, 3, 2, 1)).head(2); assertEquals("[5, 4]", resultListObj.toString()); final int resultInt = Underscore.head(new Integer[] {5, 4, 3, 2, 1}); assertEquals(5, resultInt); } /* _.singleOrNull([5, 4, 3, 2, 1]); => null _.singleOrNull([5]); => 5 */ @Test void singleOrNull() { Underscore<Integer> uWithMoreElement = new Underscore<>(asList(1, 2, 3)); Underscore<Integer> uWithOneElement = new Underscore<>(singletonList(1)); final Integer result1 = Underscore.singleOrNull(asList(1, 2, 3)); assertNull(result1); final int result2 = Underscore.singleOrNull(singletonList(1)); assertEquals(1, result2); final Integer result3 = Underscore.singleOrNull(new ArrayList<>()); assertNull(result3); final Integer result4 = Underscore.singleOrNull(asList(1, 2, 3), item -> item % 2 == 1); assertNull(result4); final int result5 = Underscore.singleOrNull(asList(1, 2, 3), item -> item % 2 == 0); assertEquals(2, result5); final Integer result6 = Underscore.singleOrNull(asList(1, 2, 3), item -> item == 5); assertNull(result6); final Integer result7 = uWithMoreElement.singleOrNull(); assertNull(result7); final Integer result8 = uWithOneElement.singleOrNull(); assertEquals(result8, Integer.valueOf(1)); final Integer result9 = uWithMoreElement.singleOrNull(item -> item % 2 == 0); assertEquals(result9, Integer.valueOf(2)); final Integer result10 = uWithMoreElement.singleOrNull(item -> item % 2 == 1); assertNull(result10); } /* _.rest([5, 4, 3, 2, 1]); => [4, 3, 2, 1] _.rest([5, 4, 3, 2, 1], 2); => [3, 2, 1] */ @Test void rest() { final List<Integer> result = Underscore.rest(asList(5, 4, 3, 2, 1)); assertEquals("[4, 3, 2, 1]", result.toString()); final List<Integer> resultChain = Underscore.chain(asList(5, 4, 3, 2, 1)).rest().value(); assertEquals("[4, 3, 2, 1]", resultChain.toString()); final List<Integer> result2 = Underscore.rest(asList(5, 4, 3, 2, 1), 2); assertEquals("[3, 2, 1]", result2.toString()); final List<Integer> result2Chain = Underscore.chain(asList(5, 4, 3, 2, 1)).rest(2).value(); assertEquals("[3, 2, 1]", result2Chain.toString()); final Object[] resultArray = Underscore.rest(new Integer[] {5, 4, 3, 2, 1}); assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); final Object[] resultArray2 = Underscore.rest(new Integer[] {5, 4, 3, 2, 1}, 2); assertEquals("[3, 2, 1]", asList(resultArray2).toString()); } @Test void chunk() { assertEquals( "[[a, b, c], [d]]", Underscore.chunk(asList("a", "b", "c", "d"), 3).toString()); assertEquals( "[[a, b], [c, d]]", Underscore.chunk(asList("a", "b", "c", "d"), 2).toString()); assertEquals("[]", Underscore.chunk(asList("a", "b", "c", "d"), 0).toString()); assertEquals("[]", Underscore.chunk(asList(1.1, 2.2, 3.3, 4.4), -2).toString()); assertEquals( "[[0, 1], [3, 4], [6]]", Underscore.chunk(Underscore.range(7), 2, 3).toString()); assertEquals("[[], [], []]", Underscore.chunk(Underscore.range(7), 0, 3).toString()); assertEquals("[]", Underscore.chunk(Underscore.range(7), -2, 3).toString()); assertEquals("[]", Underscore.chunk(Underscore.range(7), 2, 0).toString()); assertEquals("[]", Underscore.chunk(Underscore.range(7), 2, -2).toString()); assertEquals( "[[a, b], [c, d]]", new Underscore<>(asList("a", "b", "c", "d")).chunk(2).toString()); assertEquals("[]", new Underscore<>(asList("a", "b", "c", "d")).chunk(0).toString()); assertEquals( "[[0, 1, 2], [2, 3, 4], [4, 5]]", new Underscore<>(Underscore.range(6)).chunk(3, 2).toString()); assertEquals("[]", new Underscore<>(Underscore.range(7)).chunk(3, 0).toString()); assertEquals( "[[a, b], [c, d]]", Underscore.chain(asList("a", "b", "c", "d")).chunk(2).value().toString()); assertEquals( "[]", Underscore.chain(asList("a", "b", "c", "d")).chunk(0).value().toString()); assertEquals( "[[a, b], [b, c], [c, d], [d]]", Underscore.chain(asList("a", "b", "c", "d")).chunk(2, 1).value().toString()); assertEquals( "[]", Underscore.chain(asList("a", "b", "c", "d")).chunk(4, 0).value().toString()); } @Test void chunkFill() { assertEquals( "[[a, b, c], [d, fill, fill]]", Underscore.chunkFill(asList("a", "b", "c", "d"), 3, "fill").toString()); assertEquals( "[[a, b], [c, d]]", Underscore.chunkFill(asList("a", "b", "c", "d"), 2, "fill").toString()); assertEquals("[]", Underscore.chunkFill(asList("a", "b", "c", "d"), 0, "fill").toString()); assertEquals("[]", Underscore.chunkFill(asList(1.1, 2.2, 3.3, 4.4), -2, 0.0).toString()); assertEquals( "[[0, 1], [3, 4], [6, 500]]", Underscore.chunkFill(Underscore.range(7), 2, 3, 500).toString()); assertEquals( "[[], [], []]", Underscore.chunkFill(Underscore.range(7), 0, 3, 500).toString()); assertEquals("[]", Underscore.chunkFill(Underscore.range(7), -2, 3, 500).toString()); assertEquals("[]", Underscore.chunkFill(Underscore.range(7), 2, 0, 500).toString()); assertEquals("[]", Underscore.chunkFill(Underscore.range(7), 2, -2, 500).toString()); assertEquals( "[[a, b, c], [d, fill, fill]]", new Underscore<>(asList("a", "b", "c", "d")).chunkFill(3, "fill").toString()); assertEquals( "[]", new Underscore<>(asList("a", "b", "c", "d")).chunkFill(0, "fill").toString()); assertEquals( "[[0, 1, 2], [2, 3, 4], [4, 5, 500]]", new Underscore<>(Underscore.range(6)).chunkFill(3, 2, 500).toString()); assertEquals("[]", new Underscore<>(Underscore.range(7)).chunkFill(3, 0, 500).toString()); assertEquals( "[[a, b], [c, d]]", Underscore.chain(asList("a", "b", "c", "d")) .chunkFill(2, "fill") .value() .toString()); assertEquals( "[]", Underscore.chain(asList("a", "b", "c", "d")) .chunkFill(0, "fill") .value() .toString()); assertEquals( "[[a, b], [b, c], [c, d], [d, fill]]", Underscore.chain(asList("a", "b", "c", "d")) .chunkFill(2, 1, "fill") .value() .toString()); assertEquals( "[]", Underscore.chain(asList("a", "b", "c", "d")) .chunkFill(4, 0, "fill") .value() .toString()); } @Test void cycle() { assertEquals("[]", Underscore.cycle(Underscore.range(5), 0).toString()); assertEquals("[]", Underscore.cycle(Underscore.newArrayList(), 5).toString()); assertEquals("[4, 3, 2, 1, 0]", Underscore.cycle(Underscore.range(5), -1).toString()); assertEquals( "[0, 1, 2, 0, 1, 2, 0, 1, 2]", Underscore.cycle(Underscore.range(3), 3).toString()); assertEquals("[]", new Underscore<>(asList("a", "b", "c")).cycle(0).toString()); assertEquals( "[c, b, a, c, b, a]", new Underscore<>(asList("a", "b", "c")).cycle(-2).toString()); assertEquals( "[a, b, c, a, b, c, a, b, c]", new Underscore<>(asList("a", "b", "c")).cycle(3).toString()); assertEquals("[]", Underscore.chain(Underscore.range(10)).cycle(0).value().toString()); assertEquals( "[0, 0, 0, 0, 0]", Underscore.chain(Underscore.range(1)).cycle(5).value().toString()); assertEquals( "[3, 2, 1, 0]", Underscore.chain(Underscore.range(4)).cycle(-1).value().toString()); } /* _.repeat('a', 5); => [a, a, a, a, a] _.repeat('a', 0); => [] _.repeat('a', -1); => [] _.repeat(null, 3); => [null, null, null] */ @Test void repeat() { assertEquals("[a, a, a, a, a]", Underscore.repeat('a', 5).toString()); assertEquals("[]", Underscore.repeat('a', 0).toString()); assertEquals("[]", Underscore.repeat('a', -1).toString()); assertEquals("[apple, apple, apple]", Underscore.repeat("apple", 3).toString()); assertEquals("[100, 100, 100]", Underscore.repeat(100, 3).toString()); assertEquals("[2.5, 2.5, 2.5]", Underscore.repeat(2.5, 3).toString()); assertEquals("[null, null, null]", Underscore.repeat(null, 3).toString()); } @Test void interpose() { assertEquals( "[0, 500, 1, 500, 2, 500, 3]", Underscore.interpose(Underscore.range(4), 500).toString()); assertEquals("[]", Underscore.interpose(Underscore.newArrayList(), 500).toString()); assertEquals("[]", Underscore.interpose(Underscore.newArrayList(), null).toString()); assertEquals( "[0, 1, 2, 3]", Underscore.interpose(Underscore.newArrayList(Underscore.range(4)), null) .toString()); assertEquals("[0]", Underscore.interpose(Underscore.range(1), 500).toString()); assertEquals( "[a, interpose, b, interpose, c]", new Underscore<>(asList("a", "b", "c")).interpose("interpose").toString()); assertEquals("[a]", new Underscore<>(singletonList("a")).interpose("interpose").toString()); assertEquals("[a, b]", new Underscore<>(singletonList("a, b")).interpose(null).toString()); assertEquals("[a]", Underscore.chain(singletonList("a")).interpose("interpose").toString()); assertEquals( "[]", Underscore.chain(Underscore.newArrayList()).interpose("interpose").toString()); assertEquals( "[a, b, c]", Underscore.chain(asList("a", "b", "c")).interpose(null).toString()); assertEquals( "[?, interpose, !, interpose, -]", Underscore.chain(asList("?", "!", "-")).interpose("interpose").toString()); } @Test void interposeByList() { List<String> list1 = Underscore.newArrayList(); List<Integer> list2 = Underscore.newArrayList(); assertEquals( "[0, 100, 1, 200, 2, 300, 3]", Underscore.interposeByList(Underscore.range(4), Underscore.range(100, 600, 100)) .toString()); assertEquals( "[]", Underscore.interposeByList(list2, Underscore.range(100, 300, 50)).toString()); assertEquals( "[100, 200, 300]", Underscore.interposeByList(Underscore.range(100, 400, 100), list2).toString()); assertEquals( "[100, 200, 300]", Underscore.interposeByList(Underscore.range(100, 400, 100), null).toString()); list2.add(1); assertEquals( "[1]", Underscore.interposeByList(list2, Underscore.range(100, 300, 50)).toString()); assertEquals( "[0, 100, 1, 2, 3]", Underscore.interposeByList(Underscore.range(4), Underscore.newIntegerList(100)) .toString()); assertEquals( "[a, zzz, b, c]", new Underscore<>(asList("a", "b", "c")) .interposeByList(singletonList("zzz")) .toString()); assertEquals( "[a, b, c]", new Underscore<>(asList("a", "b", "c")).interposeByList(null).toString()); assertEquals( "[a]", new Underscore<>(singletonList("a")) .interposeByList(singletonList("zzz")) .toString()); assertEquals( "[a, b, c]", new Underscore<>(asList("a", "b", "c")).interposeByList(list1).toString()); assertEquals( "[a, aaa, b, bbb, c]", new Underscore<>(asList("a", "b", "c")) .interposeByList(asList("aaa", "bbb", "ccc")) .toString()); assertEquals( "[a]", Underscore.chain(singletonList("a")) .interposeByList(asList("aaa", "bbb", "ccc")) .toString()); assertEquals( "[aaa, bbb, ccc]", Underscore.chain(asList("aaa", "bbb", "ccc")).interposeByList(null).toString()); list2.clear(); assertEquals("[]", Underscore.chain(list2).interposeByList(Underscore.range(6)).toString()); assertEquals( "[?, aaa, !, bbb, -]", Underscore.chain(asList("?", "!", "-")) .interposeByList(asList("aaa", "bbb", "ccc")) .toString()); } /* _.tail([5, 4, 3, 2, 1]); => [4, 3, 2, 1] _.tail([5, 4, 3, 2, 1], 2); => [3, 2, 1] */ @Test void tail() { final List<Integer> result = Underscore.tail(asList(5, 4, 3, 2, 1)); assertEquals("[4, 3, 2, 1]", result.toString()); final List<Integer> result2 = Underscore.tail(asList(5, 4, 3, 2, 1), 2); assertEquals("[3, 2, 1]", result2.toString()); final Object[] resultArray = Underscore.tail(new Integer[] {5, 4, 3, 2, 1}); assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); final List<Integer> resultArrayObj = new Underscore<>(asList(5, 4, 3, 2, 1)).tail(); assertEquals("[4, 3, 2, 1]", resultArrayObj.toString()); final Object[] resultArray2 = Underscore.tail(new Integer[] {5, 4, 3, 2, 1}, 2); assertEquals("[3, 2, 1]", asList(resultArray2).toString()); final List<Integer> resultArray2Obj = new Underscore<>(asList(5, 4, 3, 2, 1)).tail(2); assertEquals("[3, 2, 1]", resultArray2Obj.toString()); } /* _.drop([5, 4, 3, 2, 1]); => [4, 3, 2, 1] _.drop([5, 4, 3, 2, 1], 2); => [3, 2, 1] */ @Test void drop() { final List<Integer> result = Underscore.drop(asList(5, 4, 3, 2, 1)); assertEquals("[4, 3, 2, 1]", result.toString()); final List<Integer> result2 = Underscore.drop(asList(5, 4, 3, 2, 1), 2); assertEquals("[3, 2, 1]", result2.toString()); final Object[] resultArray = Underscore.drop(new Integer[] {5, 4, 3, 2, 1}); assertEquals("[4, 3, 2, 1]", asList(resultArray).toString()); final Object[] resultArray2 = Underscore.drop(new Integer[] {5, 4, 3, 2, 1}, 2); assertEquals("[3, 2, 1]", asList(resultArray2).toString()); } /* _.replace([1, 2, 3, 4], predicate(a) { return a > 2; }, 100); => [1, 2, 100, 100] _.replace([1, 2, 3, 4], null, 100); => [1, 2, 3, 4] */ @SuppressWarnings("serial") @Test void replace() { assertEquals( "[100, 1, 100, 3, 100, 5]", Underscore.replace(Underscore.range(6), arg -> arg % 2 == 0, 100).toString()); assertEquals( "[0, 1, 2, 3, 4]", Underscore.replace(Underscore.range(5), null, 100).toString()); assertEquals( "[a, aa, b, b]", new Underscore<>(asList("a", "aa", "aaa", "aaaa")) .replace(arg -> arg.length() > 2, "b") .toString()); assertEquals( "[a, aa, cc, ccc]", new Underscore<>(asList("a", "aa", "cc", "ccc")).replace(null, "b").toString()); Set<Integer> set = new LinkedHashSet<>(); set.addAll(Underscore.range(7)); assertEquals( "[0, 1, 2, 100, 100, 100, 100]", Underscore.chain(set).replace(arg -> arg > 2, 100).toString()); } /* _.replaceIndexed([a, b, c, d], predicateIndexed(a, b) { return a > 2; }, z); => [a, b, z, z] _.replaceIndexed([a, b, c, d], null, z); => [a, b, c, d] */ @SuppressWarnings("serial") @Test void replaceIndexed() { assertEquals( "[0, 1, 2, 3, 100, 100]", Underscore.replaceIndexed(Underscore.range(6), (i, arg) -> i > 2 && arg > 3, 100) .toString()); assertEquals( "[0, 1, 2, 3, 4]", Underscore.replaceIndexed(Underscore.range(5), null, 100).toString()); assertEquals( "[a, bc, ddd, f]", new Underscore<>(asList("a", "bc", "ddd", "eeee")) .replaceIndexed((i, arg) -> arg.length() > 2 && i > 2, "f") .toString()); assertEquals( "[a, aa, cc, ccc]", new Underscore<>(asList("a", "aa", "cc", "ccc")) .replaceIndexed(null, "b") .toString()); List<Integer> list = new ArrayList<>(); list.add(100); list.add(22); list.add(88); list.add(6530); list.add(-25); list.add(-1000); assertEquals( "[100, 0, 88, 6530, 0, -1000]", Underscore.chain(list).replaceIndexed((i, arg) -> arg < 23 && i < 5, 0).toString()); } /* _.initial([5, 4, 3, 2, 1]); => [5, 4, 3, 2] _.initial([5, 4, 3, 2, 1], 2); => [5, 4, 3] */ @Test @SuppressWarnings("unchecked") void initial() { final List<Integer> result = Underscore.initial(asList(5, 4, 3, 2, 1)); assertEquals("[5, 4, 3, 2]", result.toString()); final List<Integer> resultChain = Underscore.chain(asList(5, 4, 3, 2, 1)).initial().value(); assertEquals("[5, 4, 3, 2]", resultChain.toString()); final List<Integer> resultList = Underscore.initial(asList(5, 4, 3, 2, 1), 2); assertEquals("[5, 4, 3]", resultList.toString()); final List<Integer> resultListChain = Underscore.chain(asList(5, 4, 3, 2, 1)).initial(2).value(); assertEquals("[5, 4, 3]", resultListChain.toString()); final Integer[] resultArray = Underscore.initial(new Integer[] {5, 4, 3, 2, 1}); assertEquals("[5, 4, 3, 2]", asList(resultArray).toString()); final Integer[] resultListArray = Underscore.initial(new Integer[] {5, 4, 3, 2, 1}, 2); assertEquals("[5, 4, 3]", asList(resultListArray).toString()); List<Integer> res = new Underscore(asList(1, 2, 3, 4, 5)).initial(); assertEquals(asList(1, 2, 3, 4), res, "initial one item did not work"); res = new Underscore(asList(1, 2, 3, 4, 5)).initial(3); assertEquals(asList(1, 2), res, "initial multi item did not wok"); } /* _.last([5, 4, 3, 2, 1]); => 1 */ @Test @SuppressWarnings("unchecked") void last() { final Integer result = Underscore.last(asList(5, 4, 3, 2, 1)); assertEquals("1", result.toString()); final List<Integer> resultTwo = Underscore.last(asList(5, 4, 3, 2, 1), 2); assertEquals("[2, 1]", resultTwo.toString()); final Object resultChain = Underscore.chain(asList(5, 4, 3, 2, 1)).last().item(); assertEquals("1", resultChain.toString()); final Object resultChainTwo = Underscore.chain(asList(5, 4, 3, 2, 1)).last(2).value(); assertEquals("[2, 1]", resultChainTwo.toString()); final Integer resultArray = Underscore.last(new Integer[] {5, 4, 3, 2, 1}); assertEquals("1", resultArray.toString()); Integer res = new Underscore<>(asList(1, 2, 3, 4, 5)).last(); assertEquals(5, res.intValue(), "last one item did not work"); List<Integer> resList = new Underscore(asList(1, 2, 3, 4, 5)).last(3); assertEquals(asList(3, 4, 5), resList, "last multi item did not wok"); final int resultPred = Underscore.last(asList(5, 4, 3, 2, 1), item -> item % 2 == 0); assertEquals(2, resultPred); final int resultPredObj = new Underscore<>(asList(5, 4, 3, 2, 1)).last(item -> item % 2 == 0); assertEquals(2, resultPredObj); } @Test void lastOrNull() { final Integer result = Underscore.lastOrNull(asList(5, 4, 3, 2, 1)); assertEquals("1", result.toString()); final Integer resultObj = new Underscore<>(asList(5, 4, 3, 2, 1)).lastOrNull(); assertEquals("1", resultObj.toString()); final Integer resultChain = Underscore.chain(asList(5, 4, 3, 2, 1)).lastOrNull().item(); assertEquals("1", resultChain.toString()); assertNull(Underscore.lastOrNull(Collections.emptyList())); assertNull(new Underscore<>(Collections.<Integer>emptyList()).lastOrNull()); final int resultPred = Underscore.lastOrNull(asList(5, 4, 3, 2, 1), item -> item % 2 == 0); assertEquals(2, resultPred); final int resultPredChain = Underscore.chain(asList(5, 4, 3, 2, 1)).lastOrNull(item -> item % 2 == 0).item(); assertEquals(2, resultPredChain); assertNull(Underscore.lastOrNull(Collections.<Integer>emptyList(), item -> item % 2 == 0)); final int resultPredObj = new Underscore<>(asList(5, 4, 3, 2, 1)).lastOrNull(item -> item % 2 == 0); assertEquals(2, resultPredObj); assertNull( new Underscore<>(Collections.<Integer>emptyList()) .lastOrNull(item -> item % 2 == 0)); } /* _.compact([0, 1, false, 2, '', 3]); => [1, 2, 3] */ @Test @SuppressWarnings("unchecked") void compact() { final List<?> result = Underscore.compact(asList(0, 1, false, 2, "", 3)); assertEquals("[1, 2, 3]", result.toString()); final List<?> result2 = Underscore.compact(Arrays.<Object>asList(0, 1, false, 2, "", 3), 1); assertEquals("[0, false, 2, , 3]", result2.toString()); final List<?> result3 = Underscore.compact(asList(0, 1, null, 2, "", 3)); assertEquals("[1, 2, 3]", result3.toString()); final List<?> resultChain = Underscore.chain(asList(0, 1, false, 2, "", 3)).compact().value(); assertEquals("[1, 2, 3]", resultChain.toString()); final List<?> result2Chain = Underscore.chain(Arrays.<Object>asList(0, 1, false, 2, "", 3)).compact(1).value(); assertEquals("[0, false, 2, , 3]", result2Chain.toString()); final List<?> result4 = new Underscore(asList(0, 1, false, 2, "", 3)).compact(); assertEquals("[1, 2, 3]", result4.toString()); final List<?> result5 = new Underscore(asList(0, 1, false, 2, "", 3)).compact(1); assertEquals("[0, false, 2, , 3]", result5.toString()); final List<?> result6 = new Underscore(asList(0, 1, null, 2, "", 3)).compact(1); assertEquals("[0, null, 2, , 3]", result6.toString()); final List<?> result7 = new Underscore(asList(0, 1, null, 2, "", 3)).compact((Integer) null); assertEquals("[0, 1, 2, , 3]", result7.toString()); final Object[] resultArray = Underscore.compact(new Object[] {0, 1, false, 2, "", 3}); assertEquals("[1, 2, 3]", asList(resultArray).toString()); final Object[] resultArray2 = Underscore.compact(new Object[] {0, 1, false, 2, "", 3}, 1); assertEquals("[0, false, 2, , 3]", asList(resultArray2).toString()); } /* _.flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; */ @Test @SuppressWarnings("unchecked") void flatten() { final List<Integer> result = Underscore.flatten( asList(1, asList(2, asList(3, singletonList(singletonList(4)))))); assertEquals("[1, 2, 3, 4]", result.toString()); final List<Integer> result2 = Underscore.flatten( asList(1, asList(2, asList(3, singletonList(singletonList(4))))), true); assertEquals("[1, 2, [3, [[4]]]]", result2.toString()); final List<Integer> result3 = Underscore.flatten( asList(1, asList(2, asList(3, singletonList(singletonList(4))))), false); assertEquals("[1, 2, 3, 4]", result3.toString()); final List<Integer> resultObj = new Underscore(asList(1, asList(2, asList(3, singletonList(singletonList(4)))))) .flatten(); assertEquals("[1, 2, 3, 4]", resultObj.toString()); final List<Integer> resultObj2 = new Underscore(asList(1, asList(2, asList(3, singletonList(singletonList(4)))))) .flatten(true); assertEquals("[1, 2, [3, [[4]]]]", resultObj2.toString()); final List<Integer> resultObj3 = new Underscore(asList(1, asList(2, asList(3, singletonList(singletonList(4)))))) .flatten(false); assertEquals("[1, 2, 3, 4]", resultObj3.toString()); } /* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); => [2, 3, 4] */ @Test void without() { final List<Integer> result = Underscore.without(asList(1, 2, 1, 0, 3, 1, 4), 0, 1); assertEquals("[2, 3, 4]", result.toString()); final List<Integer> result2 = Underscore.without(asList(1, 2, 1, 0, 3, 1, 4), 1); assertEquals("[2, 0, 3, 4]", result2.toString()); final List<Integer> result3 = Underscore.without(asList(null, 2, null, 0, 3, null, 4), (Integer) null); assertEquals("[2, 0, 3, 4]", result3.toString()); final Object[] resultArray = Underscore.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 0, 1); assertEquals("[2, 3, 4]", asList(resultArray).toString()); final Object[] resultArray2 = Underscore.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 1); assertEquals("[2, 0, 3, 4]", asList(resultArray2).toString()); } /* _.sortedIndex([10, 20, 30, 40, 50], 35); => 3 */ @Test void sortedIndex() { final Integer result = Underscore.sortedIndex(asList(10, 20, 30, 40, 50), 35); assertEquals(3, result.intValue()); final Integer result2 = Underscore.sortedIndex(new Integer[] {10, 20, 30, 40, 50}, 35); assertEquals(3, result2.intValue()); final Integer result3 = Underscore.sortedIndex(asList(10, 20, 30, 40, 50), 60); assertEquals(-1, result3.intValue()); } @Test void sortedIndex2() { class Person implements Comparable<Person> { public final String name; public final Integer age; public Person(final String name, final Integer age) { this.name = name; this.age = age; } public int compareTo(Person person) { return person.age - this.age; } public String toString() { return name + ", " + age; } } final int result = Underscore.<Person>sortedIndex( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 50), "age"); assertEquals(1, result); final int result2 = Underscore.<Person>sortedIndex( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 70), "age"); assertEquals(-1, result2); final int resultArray = Underscore.<Person>sortedIndex( new Person[] { new Person("moe", 40), new Person("moe", 50), new Person("curly", 60) }, new Person("moe", 50), "age"); assertEquals(1, resultArray); } @Test void sortedIndex2Error() { class Person implements Comparable<Person> { public int compareTo(Person person) { return 0; } } Person person = new Person(); List<Person> personList = singletonList(person); assertThrows( IllegalArgumentException.class, () -> Underscore.sortedIndex(personList, person, "age")); } /* _.uniq([1, 2, 1, 3, 1, 4]); => [1, 2, 3, 4] */ @Test void uniq() { final List<Integer> result = Underscore.uniq(asList(1, 2, 1, 3, 1, 4)); assertEquals("[1, 2, 3, 4]", result.toString()); final Object[] resultArray = Underscore.uniq(new Integer[] {1, 2, 1, 3, 1, 4}); assertEquals("[1, 2, 3, 4]", asList(resultArray).toString()); class Person { public final String name; public final Integer age; public Person(final String name, final Integer age) { this.name = name; this.age = age; } public String toString() { return name + ", " + age; } } final Collection<Person> resultObject = Underscore.uniq( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), person -> person.name); assertEquals("[moe, 50, curly, 60]", resultObject.toString()); final List<Person> resultObjectChain = Underscore.chain( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))) .uniq(person -> person.name) .value(); assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString()); assertEquals( "[1, 2, 3, 4, 5]", Underscore.chain(asList(1, 2, 3, 3, 4, 5)).uniq().value().toString()); final Object[] resultObjectArray = Underscore.uniq( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)) .toArray(new Person[] {}), person -> person.name); assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString()); } /* _.distinct([1, 2, 1, 3, 1, 4]); => [1, 2, 3, 4] */ @Test void distinct() { final List<Integer> result = Underscore.distinct(asList(1, 2, 1, 3, 1, 4)); assertEquals("[1, 2, 3, 4]", result.toString()); final Object[] resultArray = Underscore.distinct(new Integer[] {1, 2, 1, 3, 1, 4}); assertEquals("[1, 2, 3, 4]", asList(resultArray).toString()); class Person { public final String name; public final Integer age; public Person(final String name, final Integer age) { this.name = name; this.age = age; } public String toString() { return name + ", " + age; } } final Collection<Person> resultObject = Underscore.distinctBy( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), person -> person.name); assertEquals("[moe, 50, curly, 60]", resultObject.toString()); final List<String> resultObjectChain = Underscore.chain( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))) .distinctBy(person -> person.name) .value(); assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString()); assertEquals( "[1, 2, 3, 4, 5]", Underscore.chain(asList(1, 2, 3, 3, 4, 5)).distinct().value().toString()); final Object[] resultObjectArray = Underscore.distinctBy( asList( new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)) .toArray(new Person[] {}), person -> person.name); assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString()); } /* _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2] */ @Test @SuppressWarnings("unchecked") void intersection() { final List<Integer> result = Underscore.intersection(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); assertEquals("[1, 2]", result.toString()); final List<Integer> resultObj = new Underscore(asList(1, 2, 3)) .intersectionWith(asList(101, 2, 1, 10), asList(2, 1)); assertEquals("[1, 2]", resultObj.toString()); final List<Integer> resultChain = Underscore.chain(asList(1, 2, 3)) .intersection(asList(101, 2, 1, 10), asList(2, 1)) .value(); assertEquals("[1, 2]", resultChain.toString()); final Object[] resultArray = Underscore.intersection(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); assertEquals("[1, 2]", asList(resultArray).toString()); } /* _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2, 3, 101, 10] */ @Test @SuppressWarnings("unchecked") void union() { final List<Integer> result = Underscore.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1)); assertEquals("[1, 2, 3, 101, 10]", result.toString()); final List<Integer> resultObj = new Underscore(asList(1, 2, 3)).unionWith(asList(101, 2, 1, 10), asList(2, 1)); assertEquals("[1, 2, 3, 101, 10]", resultObj.toString()); final List<Integer> resultChain = Underscore.chain(asList(1, 2, 3)) .union(asList(101, 2, 1, 10), asList(2, 1)) .value(); assertEquals("[1, 2, 3, 101, 10]", resultChain.toString()); final Object[] resultArray = Underscore.union(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10}); assertEquals("[1, 2, 3, 101, 10]", asList(resultArray).toString()); } /* _.difference([1, 2, 3, 4, 5], [5, 2, 10]); => [1, 3, 4] */ @Test @SuppressWarnings("unchecked") void difference() { final List<Integer> result = Underscore.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10)); assertEquals("[1, 3, 4]", result.toString()); final List<Integer> resultObj = new Underscore(asList(1, 2, 3, 4, 5)).differenceWith(asList(5, 2, 10)); assertEquals("[1, 3, 4]", resultObj.toString()); final List<Integer> resultChain = Underscore.chain(asList(1, 2, 3, 4, 5)).difference(asList(5, 2, 10)).value(); assertEquals("[1, 3, 4]", resultChain.toString()); final List<Integer> resultList = Underscore.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10), asList(8, 4)); assertEquals("[1, 3]", resultList.toString()); final Object[] resultArray = Underscore.difference(new Integer[] {1, 2, 3, 4, 5}, new Integer[] {5, 2, 10}); assertEquals("[1, 3, 4]", asList(resultArray).toString()); final Object[] resultArray2 = Underscore.difference( new Integer[] {1, 2, 3, 4, 5}, new Integer[] {5, 2, 10}, new Integer[] {8, 4}); assertEquals("[1, 3]", asList(resultArray2).toString()); } /* _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] */ @Test @SuppressWarnings("unchecked") void zip() { final List<List<String>> result = Underscore.zip( asList("moe", "larry", "curly"), asList("30", "40", "50"), asList("true", "false", "false")); assertEquals( "[[moe, 30, true], [larry, 40, false], [curly, 50, false]]", result.toString()); } /* _.unzip(["moe", 30, true], ["larry", 40, false], ["curly", 50, false]); => [['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]] */ @Test @SuppressWarnings("unchecked") void unzip() { final List<List<String>> result = Underscore.unzip( asList("moe", "30", "true"), asList("larry", "40", "false"), asList("curly", "50", "false")); assertEquals( "[[moe, larry, curly], [30, 40, 50], [true, false, false]]", result.toString()); } /* _.object(['moe', 'larry', 'curly'], [30, 40, 50]); => {moe: 30, larry: 40, curly: 50} */ @Test void object() { final List<Tuple<String, String>> result = Underscore.object(asList("moe", "larry", "curly"), asList("30", "40", "50")); assertEquals("[(moe, 30), (larry, 40), (curly, 50)]", result.toString()); } /* _.indexOf([1, 2, 3], 2); => 1 */ @Test void indexOf() { final Integer result = Underscore.indexOf(asList(1, 2, 3), 2); assertEquals(1, result.intValue()); final Integer resultArray = Underscore.indexOf(new Integer[] {1, 2, 3}, 2); assertEquals(1, resultArray.intValue()); } /* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); => 4 */ @Test void lastIndexOf() { final Integer result = Underscore.lastIndexOf(asList(1, 2, 3, 1, 2, 3), 2); assertEquals(4, result.intValue()); final Integer resultArray = Underscore.lastIndexOf(new Integer[] {1, 2, 3, 1, 2, 3}, 2); assertEquals(4, resultArray.intValue()); } @Test void findIndex() { final Integer result = Underscore.findIndex(asList(1, 2, 3), item -> item % 2 == 0); assertEquals(1, result.intValue()); final Integer resultNotFound = Underscore.findIndex(asList(1, 2, 3), item -> item > 3); assertEquals(-1, resultNotFound.intValue()); final Integer resultArray = Underscore.findIndex(new Integer[] {1, 2, 3}, item -> item % 2 == 0); assertEquals(1, resultArray.intValue()); } @Test void findLastIndex() { final Integer result = Underscore.findLastIndex(asList(1, 2, 3, 4, 5), item -> item % 2 == 0); assertEquals(3, result.intValue()); final Integer resultNotFound = Underscore.findLastIndex(asList(1, 2, 3, 4, 5), item -> item > 5); assertEquals(-1, resultNotFound.intValue()); final Integer resultArray = Underscore.findLastIndex(new Integer[] {1, 2, 3, 4, 5}, item -> item % 2 == 0); assertEquals(3, resultArray.intValue()); } /* _.binarySearch([1, 3, 5], 3); => 1 _.binarySearch([1, 3, 5], 2); => -2 _.binarySearch([1, 3, 5], null); => -1 _.binarySearch([null, 2, 4, 6], null); => 0 */ @Test void binarySearch() { final Integer[] array = {1, 3, 5}; assertEquals(1, Underscore.binarySearch(array, 3)); assertEquals(-2, Underscore.binarySearch(array, 2)); assertEquals(-1, Underscore.binarySearch(array, null)); final Integer[] array2 = {null, 2, 4, 6}; assertEquals(0, Underscore.binarySearch(array2, null)); assertEquals(1, Underscore.binarySearch(array2, 2)); assertEquals(-2, Underscore.binarySearch(array2, 1)); final Character[] array3 = {'b', 'c', 'e'}; assertEquals(0, Underscore.binarySearch(array3, 'b')); assertEquals(-3, Underscore.binarySearch(array3, 'd')); final String[] array4 = {"bird", "camel", "elephant"}; assertEquals(0, Underscore.binarySearch(array4, "bird")); assertEquals(-1, Underscore.binarySearch(array4, "ant")); final List<Integer> list1 = asList(1, 3, 5); assertEquals(1, Underscore.binarySearch(list1, 3)); assertEquals(-2, Underscore.binarySearch(list1, 2)); assertEquals(-1, Underscore.binarySearch(list1, null)); final List<Integer> list2 = asList(null, 2, 4, 6); assertEquals(0, Underscore.binarySearch(list2, null)); assertEquals(1, Underscore.binarySearch(list2, 2)); assertEquals(-2, Underscore.binarySearch(list2, 1)); final List<Character> list3 = asList('b', 'c', 'e'); assertEquals(0, Underscore.binarySearch(list3, 'b')); assertEquals(-3, Underscore.binarySearch(list3, 'd')); final List<String> list4 = asList("bird", "camel", "elephant"); assertEquals(0, Underscore.binarySearch(list4, "bird")); assertEquals(-1, Underscore.binarySearch(list4, "ant")); } /* _.range(10); => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] _.range(1, 11); => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] _.range(0, 30, 5); => [0, 5, 10, 15, 20, 25] _.range(0, -10, -1); => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] _.range(0); => [] */ @Test void range() { final List<Integer> result = Underscore.range(10); assertEquals("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", result.toString()); final List<Integer> resultChain = Underscore.chain("").range(10).value(); assertEquals("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", resultChain.toString()); final List<Integer> result2 = Underscore.range(1, 11); assertEquals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", result2.toString()); final List<Integer> result2Chain = Underscore.chain("").range(1, 11).value(); assertEquals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", result2Chain.toString()); final List<Integer> result3 = Underscore.range(0, 30, 5); assertEquals("[0, 5, 10, 15, 20, 25]", result3.toString()); final List<Integer> result3Chain = Underscore.chain("").range(0, 30, 5).value(); assertEquals("[0, 5, 10, 15, 20, 25]", result3Chain.toString()); final List<Integer> result4 = Underscore.range(0, -10, -1); assertEquals("[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]", result4.toString()); final List<Integer> result5 = Underscore.range(0); assertEquals("[]", result5.toString()); final List<Integer> result6 = Underscore.range(8, 5); assertEquals("[8, 7, 6]", result6.toString()); final List<Integer> result7 = Underscore.range(0); assertEquals("[]", result7.toString()); final List<Integer> result8 = Underscore.range(1, 10, 0); assertEquals("[]", result8.toString()); final List<Character> result9 = Underscore.range('a', 'd', 1); assertEquals("[a, b, c]", result9.toString()); final List<Character> result10 = Underscore.range('a', 'd'); assertEquals("[a, b, c]", result10.toString()); final List<Character> result11 = Underscore.range('d'); assertEquals("[a, b, c]", result11.toString()); final List<Character> result12 = Underscore.range('d', 'a', -1); assertEquals("[d, c, b]", result12.toString()); final List<Character> result13 = Underscore.range('d', 'a'); assertEquals("[d, c, b]", result13.toString()); final List<Character> result14 = Underscore.range('d', 'a', 0); assertEquals("[]", result14.toString()); } /* _.lastIndex([1, 2, 3, 4, 5]); => 4 */ @Test void lastIndex() { assertEquals(4, Underscore.lastIndex(asList(1, 2, 3, 4, 5))); assertEquals(4, Underscore.lastIndex(new Integer[] {1, 2, 3, 4, 5})); assertEquals(4, Underscore.lastIndex(new int[] {1, 2, 3, 4, 5})); } }
package com.unidev.myip; import com.unidev.platform.web.WebUtils; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @Controller public class MyIPController { @Autowired private HttpServletRequest request; @Autowired private WebUtils webUtils; @RequestMapping(value = "/", consumes = MediaType.TEXT_HTML_VALUE) @ResponseBody public String html() { return "htmlBody"; } @RequestMapping(value = "/", consumes = MediaType.TEXT_PLAIN_VALUE) @ResponseBody public String plainText() { return "plainText"; } @RequestMapping(value = "/", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public JSONObject jsonRequest() { String ip = extractClinetIp(); JSONObject jsonObject = new JSONObject(); jsonObject.put("ip", ip); return jsonObject; } /** * Extract client IP from http request * @return */ protected String extractClinetIp() { String clientId = webUtils.getClientIp(request); return clientId; } }
package control; import data.*; import gui.centerarea.CameraShotBlock; import gui.centerarea.DirectorShotBlock; import gui.centerarea.TimetableBlock; import gui.headerarea.DirectorDetailView; import gui.headerarea.DoubleTextField; import gui.root.RootHeaderArea; import gui.root.RootPane; import gui.styling.StyledCheckbox; import gui.styling.StyledMenuButton; import gui.styling.StyledTextfield; import javafx.beans.InvalidationListener; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.stage.Stage; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.testfx.framework.junit.ApplicationTest; import java.util.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class DetailViewControllerTest extends ApplicationTest { private ControllerManager manager; private DirectorDetailView detailView; private DetailViewController detailViewController; private DoubleTextField beginCountField, endCountField, paddingBeforeField, paddingAfterField; private Pane pane; @Before public void initialize() { manager = Mockito.mock(ControllerManager.class); RootPane rootPane = Mockito.mock(RootPane.class); RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class); detailView = Mockito.mock(DirectorDetailView.class); when(manager.getRootPane()).thenReturn(rootPane); when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea); when(rootHeaderArea.getDetailView()).thenReturn(detailView); // Add necessary fields beginCountField = new DoubleTextField("0"); endCountField = new DoubleTextField("0"); paddingBeforeField = new DoubleTextField("0"); paddingAfterField = new DoubleTextField("0"); when(detailView.getDescriptionField()).thenReturn(new StyledTextfield()); when(detailView.getNameField()).thenReturn(new StyledTextfield()); when(detailView.getBeginCountField()).thenReturn(beginCountField); when(detailView.getEndCountField()).thenReturn(endCountField); when(detailView.getPaddingBeforeField()).thenReturn(paddingBeforeField); when(detailView.getPaddingAfterField()).thenReturn(paddingAfterField); when(detailView.getEndCountField()).thenReturn(endCountField); when(detailView.getEndCountField()).thenReturn(endCountField); when(detailView.getSelectCamerasButton()).thenReturn(new StyledMenuButton()); detailViewController = spy(new DetailViewController(manager)); } @Test public void camerasDropdownChangeListenerRemoved() { // Setup mocks ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class); DirectorShot shot = Mockito.mock(DirectorShot.class); DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0)); ScriptingProject project = Mockito.mock(ScriptingProject.class); TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class); TimelineController timelineController = Mockito.mock(TimelineController.class); CameraShot cameraShot1 = Mockito.mock(CameraShot.class); CameraShot cameraShot2 = Mockito.mock(CameraShot.class); Set<CameraShot> shotList = new HashSet<>(Arrays.asList(cameraShot1, cameraShot2)); CameraShotBlock cameraShotBlock1 = Mockito.mock(CameraShotBlock.class); CameraShotBlock cameraShotBlock2 = Mockito.mock(CameraShotBlock.class); DirectorTimelineController directorTimelineController = Mockito.mock(DirectorTimelineController.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(manager.getScriptingProject()).thenReturn(project); when(shotBlock.getShot()).thenReturn(shot); when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock); when(change.getRemoved()).thenReturn(changeList); when(manager.getTimelineControl()).thenReturn(timelineController); when(manager.getDirectorTimelineControl()).thenReturn(directorTimelineController); when(shot.getCameraShots()).thenReturn(shotList); when(timelineController.getShotBlockForShot(cameraShot1)).thenReturn(cameraShotBlock1); when(timelineController.getShotBlockForShot(cameraShot2)).thenReturn(cameraShotBlock2); when(cameraShotBlock1.getTimetableNumber()).thenReturn(100); // Call method under testing detailViewController.camerasDropdownChangeListener(change); // verify Mockito.verify(shot, times(1)).getTimelineIndices(); Mockito.verify(shot, times(2)).getCameraShots(); assertEquals(1, shotList.size()); assertTrue(shotList.contains(cameraShot1)); assertFalse(shotList.contains(cameraShot2)); } @Test public void camerasDropdownChangeListenerAdded() { // Setup mocks ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class); DirectorShot shot = Mockito.mock(DirectorShot.class); DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0)); ScriptingProject project = Mockito.mock(ScriptingProject.class); TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class); TimelineController timelineController = Mockito.mock(TimelineController.class); ArrayList<CameraTimeline> timelines = new ArrayList<>(); CameraTimeline timeline = Mockito.mock(CameraTimeline.class); timelines.add(timeline); DirectorTimelineController directorTimelineController = Mockito.mock(DirectorTimelineController.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(manager.getScriptingProject()).thenReturn(project); when(shotBlock.getShot()).thenReturn(shot); when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock); when(change.getAddedSubList()).thenReturn(changeList); when(manager.getTimelineControl()).thenReturn(timelineController); when(manager.getDirectorTimelineControl()).thenReturn(directorTimelineController); when(change.wasAdded()).thenReturn(true); when(project.getCameraTimelines()).thenReturn(timelines); // Call method under testing detailViewController.camerasDropdownChangeListener(change); // verify Mockito.verify(timeline, times(1)).addShot(anyObject()); Mockito.verify(manager, times(1)).setActiveShotBlock(shotBlock); } @Test public void instrumentsDropdownChangeListenerRemoved() { // Setup mocks ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class); DirectorShot shot = Mockito.mock(DirectorShot.class); DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0)); ArrayList<Instrument> instrumentList1 = new ArrayList<>(Arrays.asList(new Instrument("name", "description"))); ArrayList<Instrument> instrumentList2 = new ArrayList<>(Arrays.asList(new Instrument("name", "description"))); ArrayList<Instrument> instrumentList3 = new ArrayList<>(Arrays.asList(new Instrument("name", "description"))); ScriptingProject project = Mockito.mock(ScriptingProject.class); TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(project.getInstruments()).thenReturn(instrumentList1); when(manager.getScriptingProject()).thenReturn(project); when(shotBlock.getInstruments()).thenReturn(instrumentList2); when(shotBlock.getShot()).thenReturn(shot); when(shot.getInstruments()).thenReturn(instrumentList3); when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock); when(change.getRemoved()).thenReturn(changeList); // Call method under testing detailViewController.instrumentsDropdownChangeListener(change); // verify assertFalse(instrumentList1.isEmpty()); assertTrue(instrumentList2.isEmpty()); assertTrue(instrumentList3.isEmpty()); Mockito.verify(shotBlock, times(1)).recompute(); Mockito.verify(timetableBlock, times(1)).removeInstrument(anyObject()); } @Test public void instrumentsDropdownChangeListenerAdded() { // Setup mocks ListChangeListener.Change change = Mockito.mock(ListChangeListener.Change.class); DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); ArrayList<Integer> changeList = new ArrayList<>(Arrays.asList(0)); ArrayList<Instrument> instrumentList1 = new ArrayList<>(); ArrayList<Instrument> instrumentList2 = new ArrayList<>(Arrays.asList(new Instrument("name", "description"))); ScriptingProject project = Mockito.mock(ScriptingProject.class); TimetableBlock timetableBlock = Mockito.mock(TimetableBlock.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(project.getInstruments()).thenReturn(instrumentList2); when(manager.getScriptingProject()).thenReturn(project); when(shotBlock.getInstruments()).thenReturn(instrumentList1); when(shotBlock.getTimetableBlock()).thenReturn(timetableBlock); when(change.getAddedSubList()).thenReturn(changeList); when(change.wasAdded()).thenReturn(true); // Call method under testing detailViewController.instrumentsDropdownChangeListener(change); // verify assertEquals(1, instrumentList1.size()); assertEquals(1, instrumentList1.size()); Mockito.verify(shotBlock, times(1)).recompute(); Mockito.verify(timetableBlock, times(1)).addInstrument(anyObject()); } private void setupPaddingUpdateHelperTests(DirectorShot shot, DirectorShotBlock shotBlock, TimelineController timelineController) { // Make mocks CameraShot cameraShot = Mockito.mock(CameraShot.class); CameraShotBlock cameraShotBlock = Mockito.mock(CameraShotBlock.class); // Mock all the methods when(shotBlock.getShot()).thenReturn(shot); when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(manager.getTimelineControl()).thenReturn(timelineController); when(shot.getCameraShots()).thenReturn(new HashSet<CameraShot>(Arrays.asList(cameraShot))); when(shot.getBeginCount()).thenReturn(0.0); when(timelineController.getShotBlockForShot(anyObject())).thenReturn(cameraShotBlock); } @Test public void beforePaddingUpdateHelper() { DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); DirectorShot shot = Mockito.mock(DirectorShot.class); TimelineController timelineController = Mockito.mock(TimelineController.class); setupPaddingUpdateHelperTests(shot, shotBlock, timelineController); // Call method under testing detailViewController.beforePaddingFocusListener(null, true, false); // Verify assertEquals(0.0, shot.getFrontShotPadding(), 0); assertEquals(0.0, shotBlock.getPaddingBefore(), 0); Mockito.verify(timelineController, times(1)).recomputeAllCollisions(); } @Test public void afterPaddingFocusListener() { DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); DirectorShot shot = Mockito.mock(DirectorShot.class); TimelineController timelineController = Mockito.mock(TimelineController.class); setupPaddingUpdateHelperTests(shot, shotBlock, timelineController); // Call method under testing detailViewController.afterPaddingFocusListener(null, true, false); // Verify assertEquals(0.0, shot.getEndShotPadding(), 0); assertEquals(0.0, shotBlock.getPaddingAfter(), 0); Mockito.verify(timelineController, times(1)).recomputeAllCollisions(); } @Test public void reInitForCameraBlock() { StyledMenuButton menuButton = new StyledMenuButton(); when(detailView.getSelectInstrumentsButton()).thenReturn(menuButton); detailViewController.reInitForCameraBlock(); Mockito.verify(detailView, times(2)).getNameField(); Mockito.verify(detailView, times(2)).getDescriptionField(); Mockito.verify(detailView, times(4)).getBeginCountField(); Mockito.verify(detailView, times(4)).getEndCountField(); } @Test public void reInitForDirectorBlock() { StyledMenuButton menuButton = new StyledMenuButton(); when(detailView.getSelectInstrumentsButton()).thenReturn(menuButton); detailViewController.reInitForDirectorBlock(); Mockito.verify(detailView, times(2)).getPaddingBeforeField(); Mockito.verify(detailView, times(2)).getPaddingAfterField(); } @Test public void constructor() { assertNotNull(detailViewController); } @Test public void beginCountUpdateHelper() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); KeyEvent keyEvent = new KeyEvent(KeyEvent.ANY, "", "", KeyCode.ENTER, false, false, false, false); detailView.getBeginCountField().getOnKeyPressed().handle(keyEvent); verify(block, times(1)).setBeginCount(0); verify(shot, times(1)).setBeginCount(0); } @Test public void endCountUpdateHelper() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); KeyEvent keyEvent = new KeyEvent(KeyEvent.ANY, "", "", KeyCode.ENTER, false, false, false, false); detailView.getEndCountField().getOnKeyPressed().handle(keyEvent); verify(block, times(1)).setEndCount(0); verify(shot, times(1)).setEndCount(0); } @Test public void activeBlockChangedActiveBlockNull() { detailViewController.activeBlockChanged(); verify(detailView, times(1)).resetDetails(); } @Test public void beginCountFocusedProperty() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); detailViewController.beginCountFocusListener(new ObservableValue<Boolean>() { @Override public void addListener(ChangeListener<? super Boolean> listener) { } @Override public void removeListener(ChangeListener<? super Boolean> listener) { } @Override public Boolean getValue() { return null; } @Override public void addListener(InvalidationListener listener) { } @Override public void removeListener(InvalidationListener listener) { } }, true, false); verify(block, times(1)).setBeginCount(0); verify(shot, times(1)).setBeginCount(0); } @Test public void endCountFocusedProperty() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); detailViewController.endCountFocusListener(new ObservableValue<Boolean>() { @Override public void addListener(ChangeListener<? super Boolean> listener) { } @Override public void removeListener(ChangeListener<? super Boolean> listener) { } @Override public Boolean getValue() { return null; } @Override public void addListener(InvalidationListener listener) { } @Override public void removeListener(InvalidationListener listener) { } }, true, false); verify(block, times(1)).setEndCount(0); verify(shot, times(1)).setEndCount(0); } @Test public void nameFieldTextProperty() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); detailViewController.nameTextChangedListener(new ObservableValue<String>() { @Override public void addListener(ChangeListener<? super String> listener) { } @Override public void removeListener(ChangeListener<? super String> listener) { } @Override public String getValue() { return null; } @Override public void addListener(InvalidationListener listener) { } @Override public void removeListener(InvalidationListener listener) { } }, "", "test newvalue"); verify(block, times(1)).setName("test newvalue"); verify(shot, times(1)).setName("test newvalue"); } @Test public void descriptionFieldTextProperty() { CameraShotBlock block = Mockito.mock(CameraShotBlock.class); CameraShot shot = Mockito.mock(CameraShot.class); when(manager.getActiveShotBlock()).thenReturn(block); when(block.getShot()).thenReturn(shot); detailViewController.descriptionTextChangedListener(new ObservableValue<String>() { @Override public void addListener(ChangeListener<? super String> listener) { } @Override public void removeListener(ChangeListener<? super String> listener) { } @Override public String getValue() { return null; } @Override public void addListener(InvalidationListener listener) { } @Override public void removeListener(InvalidationListener listener) { } }, "", "test newvalue"); verify(block, times(1)).setDescription("test newvalue"); verify(shot, times(1)).setDescription("test newvalue"); } @Test public void activeBlockChangedCamera() { // Setup mocks CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class); RootPane rootPane = Mockito.mock(RootPane.class); RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(manager.getRootPane()).thenReturn(rootPane); when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea); // Call method under testing detailViewController.activeBlockChanged(); // Verify all the things Mockito.verify(detailViewController, times(1)).reInitForCameraBlock(); Mockito.verify(rootHeaderArea, times(1)).reInitHeaderBar(anyObject()); } @Test public void activeBlockChangedDirector() { // Setup mocks DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); RootPane rootPane = Mockito.mock(RootPane.class); RootHeaderArea rootHeaderArea = Mockito.mock(RootHeaderArea.class); // Mock all the methods when(manager.getActiveShotBlock()).thenReturn(shotBlock); when(manager.getRootPane()).thenReturn(rootPane); when(rootPane.getRootHeaderArea()).thenReturn(rootHeaderArea); // Call method under testing detailViewController.activeBlockChanged(); // Verify all the things Mockito.verify(detailViewController, times(1)).reInitForDirectorBlock(); Mockito.verify(rootHeaderArea, times(1)).reInitHeaderBar(anyObject()); } @Test public void instrumentsDropdownListener() { // Setup mocks StyledMenuButton menuButton = new StyledMenuButton(); CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class); Instrument instrument = Mockito.mock(Instrument.class); ArrayList<Instrument> instrumentList = new ArrayList<>(Arrays.asList(instrument)); ScriptingProject project = Mockito.mock(ScriptingProject.class); List<StyledCheckbox> list = Mockito.mock(List.class); StyledCheckbox checkbox = Mockito.mock(StyledCheckbox.class); // Mock all the methods when(shotBlock.getInstruments()).thenReturn(instrumentList); detailViewController.setActiveCameraBlock(shotBlock); detailViewController.setActiveInstrumentBoxes(list); when(manager.getScriptingProject()).thenReturn(project); when(project.getInstruments()).thenReturn(instrumentList); doReturn(checkbox).when(detailViewController).getStyledCheckbox(anyString(), anyBoolean()); // Call method under testing detailViewController.instrumentsDropdownListener(null, false, true, menuButton); // Verify all the things assertEquals(1, menuButton.getItems().size()); Mockito.verify(list, times(1)).add(checkbox); } @Test public void instrumentsDropdownListenerFalse() { // Setup mocks StyledMenuButton menuButton = new StyledMenuButton(); List<StyledCheckbox> list = Mockito.mock(List.class); // Mock all the methods detailViewController.setActiveInstrumentBoxes(list); // Call method under testing detailViewController.instrumentsDropdownListener(null, true, false, menuButton); // Verify all the things Mockito.verify(list, times(1)).clear(); } @Test public void cameraDropdownListenerFalse() { // Setup mocks StyledMenuButton menuButton = new StyledMenuButton(); List<StyledCheckbox> list = Mockito.mock(List.class); // Mock all the methods detailViewController.setActiveCameraBoxes(list); // Call method under testing detailViewController.cameraDropdownListener(null, true, false, menuButton); // Verify all the things Mockito.verify(list, times(1)).clear(); } @Test public void camerasDropdownListener() { // Setup mocks StyledMenuButton menuButton = new StyledMenuButton(); DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); Camera camera = Mockito.mock(Camera.class); ArrayList<Camera> cameraList = new ArrayList<>(Arrays.asList(camera)); ScriptingProject project = Mockito.mock(ScriptingProject.class); List<StyledCheckbox> list = Mockito.mock(List.class); StyledCheckbox checkbox = Mockito.mock(StyledCheckbox.class); // Mock all the methods detailViewController.setActiveDirectorBlock(shotBlock); detailViewController.setActiveCameraBoxes(list); when(manager.getScriptingProject()).thenReturn(project); when(project.getCameras()).thenReturn(cameraList); doReturn(checkbox).when(detailViewController).getStyledCheckbox(anyString(), anyBoolean()); // Call method under testing detailViewController.cameraDropdownListener(null, false, true, menuButton); // Verify all the things assertEquals(1, menuButton.getItems().size()); Mockito.verify(list, times(1)).add(checkbox); } @Test public void getDetailView() { assertEquals(detailView, detailViewController.getDetailView()); } @Test public void getActiveDirectorBlock() { DirectorShotBlock shotBlock = Mockito.mock(DirectorShotBlock.class); detailViewController.setActiveDirectorBlock(shotBlock); assertEquals(shotBlock, detailViewController.getActiveDirectorBlock()); } @Test public void getActiveCameraBlock() { CameraShotBlock shotBlock = Mockito.mock(CameraShotBlock.class); detailViewController.setActiveCameraBlock(shotBlock); assertEquals(shotBlock, detailViewController.getActiveCameraBlock()); } @Test public void getActiveCameraBoxes() { List<StyledCheckbox> list = Mockito.mock(List.class); detailViewController.setActiveCameraBoxes(list); assertEquals(list, detailViewController.getActiveCameraBoxes()); } @Test public void getActiveInstrumentBoxes() { List<StyledCheckbox> list = Mockito.mock(List.class); detailViewController.setActiveInstrumentBoxes(list); assertEquals(list, detailViewController.getActiveInstrumentBoxes()); } @Override public void start(Stage stage) throws Exception { } }
package nars.plugin.mental; import java.util.ArrayList; import java.util.HashMap; import nars.core.EventEmitter; import nars.core.EventEmitter.EventObserver; import nars.core.Events; import nars.core.NAR; import nars.core.Parameters; import nars.core.Plugin; import nars.entity.BudgetValue; import nars.entity.Concept; import nars.entity.Sentence; import nars.entity.Stamp; import nars.entity.Task; import nars.entity.TruthValue; import nars.inference.BudgetFunctions; import nars.inference.TemporalRules; import nars.inference.TruthFunctions; import nars.io.Symbols; import nars.language.Conjunction; import nars.language.Implication; import nars.language.Term; /** * * @author tc */ public class ClassicalConditioningHelper implements Plugin { public boolean EnableAutomaticConditioning=true; public EventEmitter.EventObserver obs; public float saved_priority; public ArrayList<Task> lastElems=new ArrayList<>(); public int maxlen=20; public int conditionAllNSteps=3; public int cnt=0; NAR nar; public class Tuple { public final ArrayList<Task> x; public final double y; public Tuple(ArrayList<Task> x, double y) { this.x = x; this.y = y; } } public ArrayList<Task> cutoutAppend(int ind1,int ind2,ArrayList<Task> first,ArrayList<Task> second) { ArrayList<Task> res=new ArrayList<>(); for(int i=ind1;i<first.size()+ind2;i++) { res.add(first.get(i)); } for(Task t : second) { res.add(t); } return res; } public boolean TaskStringContains(ArrayList<Task> w,ArrayList<Task> content) { for(int i=0;i<w.size();i++) { boolean same=true; for(int j=0;j<content.size();j++) { if(i+j>=w.size()) { return false; } if(!w.get(i+j).sentence.term.equals(content.get(j).sentence.term)) { same=false; break; } } if(content.isEmpty()) { return false; } if(same) { return true; } } return false; } public int TaskStringEqualSequentialTermCount(ArrayList<Task> w,ArrayList<Task> content) { int cnt2=0; for(int i=0;i<w.size();i++) { boolean same=true; for(int j=0;i+j<w.size() && j<content.size();j++) { if(!w.get(i+j).sentence.term.equals(content.get(j).sentence.term)) { same=false; break; } } if(content.isEmpty()) { return 0; } if(same) { cnt2++; } } return cnt2; } public void classicalConditioning() { ArrayList<Task> st=new ArrayList(lastElems.size()); Task lastt=null; for(Task t: lastElems) { st.add(t); if(lastt!=null && Math.abs(t.sentence.getOccurenceTime()-lastt.sentence.getOccurenceTime())>nar.param.duration.get()*100) { st.add(null); //pause } lastt=t; } HashMap<Term,ArrayList<Task>> theoriess=new HashMap<>(); for(int k=0;k<st.size();k++) { for(int i=1;i<st.size();i++) { Task ev=st.get(i); Task lastev=st.get(i-1); if(true)//desired { ArrayList<Task> H=new ArrayList<>(); H.add(lastev); H.add(ev); //System.out.println(lastev.sentence.term); // System.out.println(ev.sentence.term); theoriess.put(ev.sentence.term, H); for(int j=i;j<st.size();j++) { Task ev2=st.get(j); Task lastev2=st.get(j-1); //forward conditioning if(lastev2.sentence.term.equals(lastev.sentence.term) && !ev2.sentence.term.equals(ev.sentence.term) && theoriess.keySet().contains(ev.sentence.term)) { theoriess.remove(ev.sentence.term); //extinction } } } } } ArrayList<ArrayList<Task>> theories=new ArrayList<>(); for(ArrayList<Task> t : theoriess.values()) { theories.add(t); } for(int i=0;i<2;i++) { ArrayList<ArrayList<Task>> theories2=new ArrayList<>(); for(ArrayList<Task> t : theories) { theories2.add(t); } for(ArrayList<Task> A : theories) { for(ArrayList<Task> B : theories) { if(A.size()==1 || B.size()==1) { continue; } while(A.contains(null)) { A.remove(null); } while(B.contains(null)) { B.remove(null); } boolean caseA=A.get(A.size()-1)==B.get(0); boolean caseB=A.size()>2 && B.size()>1 && A.get(A.size()-1)==B.get(1) && A.get(A.size()-2)==B.get(0); if((A.size()>1 && B.size()>1) && (caseA || caseB)) { ArrayList<Task> compoundT=null; if(caseA) { compoundT=cutoutAppend(0,-1,A,B); } if(caseB) { compoundT=cutoutAppend(0,-2,A,B); } theories2.add(compoundT); } } } theories=theories2; } System.out.println("found theories:"); ArrayList<ArrayList<Task>> filtered=new ArrayList<>(); //Filtered=[a for a in list(set([a.replace(" ","") for a in theories])) if len(a)>1] for(ArrayList<Task> t: theories) { if(t.size()>1) { //check if its not included: boolean included=false; for(ArrayList<Task> fil : filtered) { if(fil==null) { continue; } if(fil.size()!=t.size()) { continue; } else { boolean same=true; for(int i=0;i<t.size();i++) { if(!(t.get(i).sentence.term.equals(fil.get(i).sentence.term))) { //we need term equals this is why same=false; break; } } if(same) { included=true; } } } if(!included) { filtered.add(t); } } } ArrayList<Tuple> Ret=new ArrayList<>(); for(ArrayList<Task> a: filtered) { Ret.add(new Tuple(a,TaskStringEqualSequentialTermCount(st,a)*a.size())); } ArrayList<Tuple> ToRemove=new ArrayList<Tuple>(); for(Tuple T : Ret) { ArrayList<Task> a=T.x; double b=T.y; for(Tuple D : Ret) { ArrayList<Task> c=D.x; double d=D.y; if(a!=c && TaskStringContains(c,a) && d>=b) { //Ret.remove(T); ToRemove.add(T); } } } for(Tuple T : ToRemove) { Ret.remove(T); } double max=0; for(Tuple T : Ret) { if(T.y>max) { max=T.y; } } for(Tuple T : Ret) { if(T.y==max) { TruthValue Truth=null; Term[] wuh=new Term[T.x.size()-1]; Term pred=null; int i=0; for(Task t : T.x) { if(i==T.x.size()-1) { pred=t.sentence.term; } else { wuh[i]=t.sentence.term; } i++; if(Truth==null) { Truth=t.sentence.truth; } else { Truth=TruthFunctions.induction(Truth,t.sentence.truth); } } // Concept c=nar.memory.concept(pred); //if(c==null || !c.isDesired()) { // return; Conjunction con=(Conjunction) Conjunction.make(wuh, TemporalRules.ORDER_FORWARD); Implication res=Implication.make(con, pred,TemporalRules.ORDER_FORWARD); Stamp stamp=new Stamp(nar.memory); stamp.setOccurrenceTime(Stamp.ETERNAL); Sentence s=new Sentence(res,Symbols.JUDGMENT_MARK,Truth,stamp); Task TT=Task.make(s, new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY,Parameters.DEFAULT_JUDGMENT_DURABILITY, BudgetFunctions.truthToQuality(Truth)), lastElems.get(lastElems.size()-1)); nar.addInput(TT); boolean debugtillhere=true; break; } } } public void HandleInput(Task task) { if(!enabled) { return; } if(!task.isInput()) { return; } if(task.sentence.stamp.getOccurrenceTime()!=Stamp.ETERNAL && task.sentence.punctuation==Symbols.JUDGMENT_MARK) { lastElems.add(task); if(lastElems.size()>maxlen) { lastElems.remove(0); } if(cnt%conditionAllNSteps==0 && EnableAutomaticConditioning) { classicalConditioning(); } cnt++; } } boolean enabled=false; @Override public boolean setEnabled(NAR n, boolean enabled) { this.enabled=enabled; this.nar=n; if(obs==null) { saved_priority=Parameters.DEFAULT_JUDGMENT_PRIORITY; obs=new EventObserver() { @Override public void event(Class event, Object[] a) { //is not working, keep for later: if (event!=Events.TaskImmediateProcess.class) return; Task task = (Task)a[0]; try{ HandleInput(task); } catch(Exception ex){} } }; } if(enabled) { Parameters.DEFAULT_JUDGMENT_PRIORITY=(float) 0.01; } else { Parameters.DEFAULT_JUDGMENT_PRIORITY=saved_priority; } n.memory.event.set(obs, enabled, Events.TaskImmediateProcess.class); return true; } }
import org.junit.Before; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; public class TestR250 { @Test public void test01() { R250 objetoBase = new R250(); String[] inputGrid = new String[] {}; assertEquals(0, objetoBase.detectarRectangulos(inputGrid)); } public void test02() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "" }; assertEquals(0, objetoBase.detectarRectangulos(inputGrid)); } public void test03() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { " " }; assertEquals(0, objetoBase.detectarRectangulos(inputGrid)); } public void test04() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "+-+", "| |", "+-+" }; assertEquals(1, objetoBase.detectarRectangulos(inputGrid)); } public void test05() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { " +-+", " | |", "+-+-+", "| | ", "+-+ " }; assertEquals(2, objetoBase.detectarRectangulos(inputGrid)); } public void test06() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { " +-+", " | |", "+-+-+", "| | |", "+-+-+" }; assertEquals(5, objetoBase.detectarRectangulos(inputGrid)); } public void test07() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "+ assertEquals(1, objetoBase.detectarRectangulos(inputGrid)); } public void test08() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "++", "||", "++" }; assertEquals(1, objetoBase.detectarRectangulos(inputGrid)); } public void test09() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "++", "++" }; assertEquals(1, objetoBase.detectarRectangulos(inputGrid)); } public void test10() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { " +-+", " |", "+-+-+", "| | -", "+-+-+" }; assertEquals(1, objetoBase.detectarRectangulos(inputGrid)); } public void test11() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "+ "+ assertEquals(3, objetoBase.detectarRectangulos(inputGrid)); } public void test12() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "+ "+ assertEquals(2, objetoBase.detectarRectangulos(inputGrid)); } public void test13() { R250 objetoBase = new R250(); String[] inputGrid = new String[] { "+ "+ assertEquals(60, objetoBase.detectarRectangulos(inputGrid)); } }
package es.uvigo.esei.daa.rest; import static es.uvigo.esei.daa.TestUtils.assertOkStatus; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; import javax.ws.rs.core.Application; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.SpringLifecycleListener; import org.glassfish.jersey.test.JerseyTest; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; 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; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.filter.RequestContextFilter; import es.uvigo.esei.daa.TestUtils; import es.uvigo.esei.daa.entities.Event; import es.uvigo.esei.daa.services.pojo.EventPojo; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/applicationContext.xml" }) @TransactionConfiguration(defaultRollback = true) @Transactional public class EventTest extends JerseyTest { @Autowired private SessionFactory sessionFactory; @Autowired TransactionTemplate txTemplate; @BeforeClass public static void setUpBeforeClass() throws Exception { TestUtils.createFakeContext(); } @BeforeTransaction public void verifyInitialDatabaseState() throws Exception { // logic to verify the initial state before a transaction is started TestUtils.initTestDatabase(); } @Before public void setUp() throws Exception { super.setUp(); } @AfterTransaction public void afterTransaction() throws Exception { TestUtils.clearTestDatabase(); } @After public void tearDown() throws Exception { super.tearDown(); } @Override protected Application configure() { ResourceConfig rc = new ResourceConfig(); rc.register(EventResource.class); rc.register(RequestContextFilter.class); rc.register(JacksonFeature.class); rc.property("contextConfigLocation", "classpath:spring/applicationContext.xml"); return rc; } @Override protected void configureClient(ClientConfig config) { super.configureClient(config); config.property("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE); } @Test public void testList() throws IOException { final Response response = target("event").request().get(); assertOkStatus(response); final List<EventPojo> events = response .readEntity(new GenericType<List<EventPojo>>() { }); assertEquals(1, events.size()); } }
package swarm.server.thirdparty.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.URLDecoder; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import swarm.server.account.E_Role; import swarm.server.account.ServerAccountManager; import swarm.server.account.UserSession; import swarm.server.app.A_ServerApp; import swarm.server.app.A_ServerJsonFactory; import swarm.server.app.ServerContext; import swarm.server.session.SessionManager; import swarm.server.transaction.ServerTransactionManager; import swarm.shared.account.SignInCredentials; import swarm.shared.account.SignInValidationResult; import swarm.shared.account.SignInValidator; import swarm.shared.app.BaseAppContext; import swarm.shared.app.S_CommonApp; import swarm.shared.json.A_JsonFactory; import swarm.shared.json.I_JsonObject; import swarm.shared.transaction.S_Transaction; import swarm.shared.transaction.TransactionRequest; import swarm.shared.transaction.TransactionResponse; public class SignInServlet extends A_BaseServlet { private static final Logger s_logger = Logger.getLogger(SignInServlet.class.getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGetOrPost(req, resp, true); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGetOrPost(req, resp, false); } private void doGetOrPost(HttpServletRequest nativeRequest, HttpServletResponse nativeResponse, boolean isGet) throws ServletException, IOException { ServerContext context = A_ServerApp.getInstance().getContext(); SessionManager sessionMngr = context.sessionMngr; sessionMngr.onEnterScope(); ServerAccountManager accountMngr = context.accountMngr; ((A_ServerJsonFactory)context.jsonFactory).startScope(true); try { nativeResponse.setContentType("text/html"); I_JsonObject requestJson = null; String email = ""; String password = ""; boolean isSignedIn = sessionMngr.isAuthenticated(nativeRequest, nativeResponse); if( !isGet ) { if( nativeRequest.getParameter("signin") != null ) { email = nativeRequest.getParameter("email"); password = nativeRequest.getParameter("password"); if( !isSignedIn ) { SignInCredentials creds = new SignInCredentials(false, email, password); SignInValidationResult result = new SignInValidationResult(); UserSession session = accountMngr.attemptSignIn(creds, result); if( session != null ) { sessionMngr.startSession(session, nativeResponse, creds.rememberMe()); isSignedIn = true; } } } else if ( nativeRequest.getParameter("signout") != null ) { if( isSignedIn ) { sessionMngr.endSession(nativeRequest, nativeResponse); isSignedIn = false; } } } PrintWriter writer = nativeResponse.getWriter(); writer.write("<form method='POST'>"); if( isSignedIn ) { writer.write("<input type='submit' name='signout' value='Sign Out'>"); } else { writer.write("<input placeholder='E-mail' type='text' name='email' value='"+email+"' ></input>"); writer.write("<input placeholder='Password' type='password' name='password'></input>"); writer.write("<input type='submit' name='signin' value='Sign In'>"); } writer.write("</form>"); writer.flush(); } finally { ((A_ServerJsonFactory)context.jsonFactory).endScope(); sessionMngr.onExitScope(); } } }
package moe.banana.jsonapi2; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.JsonDataException; import com.squareup.moshi.Moshi; import com.squareup.moshi.Types; import moe.banana.jsonapi2.model.*; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.EOFException; import java.util.Collections; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SuppressWarnings("all") public class DocumentTest { @Test(expected = EOFException.class) public void deserialize_empty() throws Exception { getDocumentAdapter(Article.class).fromJson(""); } @Test public void deserialize_null() throws Exception { assertNull(getDocumentAdapter(null).fromJson("null")); } @Test public void deserialize_object() throws Exception { Document<Article> document = getDocumentAdapter(Article.class).fromJson(TestUtil.fromResource("/single.json")); assertFalse(document.isList()); assertOnArticle1(document.get()); } @Test public void deserialize_object_null() throws Exception { Document<Article> document = getDocumentAdapter(Article.class).fromJson(TestUtil.fromResource("/single_null.json")); assertNull(document.get()); } @Test public void deserialize_private_type() throws Exception { assertOnArticle1(getDocumentAdapter(Article2.class).fromJson(TestUtil.fromResource("/single.json")).get()); } @Test(expected = JsonDataException.class) public void deserialize_no_default() throws Exception { TestUtil.moshi(true, Article.class) .adapter(Types.newParameterizedType(Document.class, Article.class)) .fromJson(TestUtil.fromResource("/multiple_compound.json")); } @Test public void deserialize_polymorphic_type() throws Exception { Resource resource = getDocumentAdapter(Resource.class, Article.class).fromJson(TestUtil.fromResource("/single.json")).get(); assertThat(resource, instanceOf(Article.class)); assertOnArticle1(((Article) resource)); } @Test public void deserialize_polymorphic_fallback() throws Exception { Resource resource = getDocumentAdapter(Resource.class).fromJson(TestUtil.fromResource("/single.json")).get(); assertThat(resource.getId(), equalTo("1")); assertThat(resource, instanceOf(TestUtil.Default.class)); } @Test public void deserialize_multiple_objects() throws Exception { Document<Article> document = getDocumentAdapter(Article.class).fromJson(TestUtil.fromResource("/multiple_compound.json")); assertThat(document, notNullValue()); assertThat(document.size(), equalTo(1)); assertTrue(document.isList()); assertOnArticle1(document.get(0)); } @Test public void deserialize_multiple_polymorphic() throws Exception { Document<Resource> document = getDocumentAdapter(Resource.class, Article.class, Photo.class).fromJson(TestUtil.fromResource("/multiple_polymorphic.json")); assertThat(document.get(0), instanceOf(Article.class)); assertThat(document.get(1), instanceOf(Photo.class)); assertOnArticle1((Article) document.get(0)); } @Test public void deserialize_multiple_polymorphic_type_priority() throws Exception { Document<Resource> document = getDocumentAdapter(Resource.class, Photo2.class, Photo.class).fromJson(TestUtil.fromResource("/multiple_polymorphic.json")); assertThat(document.get(1), instanceOf(Photo2.class)); } @Test(expected = JsonDataException.class) public void deserialize_multiple_polymorphic_no_default() throws Exception { TestUtil.moshi(true, Article.class) .adapter(Types.newParameterizedType(Document.class, Resource.class)) .fromJson(TestUtil.fromResource("/multiple_polymorphic.json")); } @Test public void deserialize_unparameterized() throws Exception { Document document = getDocumentAdapter(null, Person.class).fromJson("{\"data\":{\"type\":\"people\",\"id\":\"5\"}}"); assertFalse(document.isList()); assertThat(document.get().getType(), equalTo("people")); assertThat(document.get(), instanceOf(Person.class)); } @Test public void serialize_empty() throws Exception { Document document = new Document(); assertThat(getDocumentAdapter(ResourceIdentifier.class).toJson(document), equalTo("{\"data\":null}")); assertThat(getDocumentAdapter(ResourceIdentifier.class).toJson(document.asList()), equalTo("{\"data\":[]}")); } @Test public void serialize_object() throws Exception { Article article = new Article(); article.setTitle("Nineteen Eighty-Four"); article.setAuthor(new HasOne<Person>("people", "5")); article.setComments(new HasMany<Comment>( new ResourceIdentifier("comments", "1"))); Document document = new Document(); document.set(article); assertThat(getDocumentAdapter(Article.class).toJson(document), equalTo( "{\"data\":{\"type\":\"articles\",\"attributes\":{\"title\":\"Nineteen Eighty-Four\"},\"relationships\":{\"author\":{\"data\":{\"type\":\"people\",\"id\":\"5\"}},\"comments\":{\"data\":[{\"type\":\"comments\",\"id\":\"1\"}]}}}}")); } @Test public void serialize_polymorphic() throws Exception { Article article = new Article(); article.setTitle("Nineteen Eighty-Four"); Document document = new Document(); document.set(article); assertThat(getDocumentAdapter(Resource.class).toJson(document), equalTo("{\"data\":{\"type\":\"articles\",\"attributes\":{\"title\":\"Nineteen Eighty-Four\"}}}")); } @Test public void serialize_multiple_polymorphic_compound() throws Exception { Document document = new Document(); Comment comment1 = new Comment(); comment1.setId("1"); comment1.setBody("Awesome!"); Person author = new Person(); author.setId("5"); author.setFirstName("George"); author.setLastName("Orwell"); Article article = new Article(); article.setTitle("Nineteen Eighty-Four"); article.setAuthor(new HasOne<Person>(author)); article.setComments(new HasMany<Comment>(comment1)); document.add(article); document.add(author); document.include(comment1); assertThat(getDocumentAdapter(Resource.class).toJson(document), equalTo("{\"data\":[" + "{\"type\":\"articles\",\"attributes\":{\"title\":\"Nineteen Eighty-Four\"},\"relationships\":{\"author\":{\"data\":{\"type\":\"people\",\"id\":\"5\"}},\"comments\":{\"data\":[{\"type\":\"comments\",\"id\":\"1\"}]}}}," + "{\"type\":\"people\",\"id\":\"5\",\"attributes\":{\"first-name\":\"George\",\"last-name\":\"Orwell\"}}" + "],\"included\":[{\"type\":\"comments\",\"id\":\"1\",\"attributes\":{\"body\":\"Awesome!\"}}]}")); } @Test public void deserialize_resource_identifier() throws Exception { Document document = getDocumentAdapter(ResourceIdentifier.class) .fromJson(TestUtil.fromResource("/relationship_single.json")); assertThat(document.get(), instanceOf(ResourceIdentifier.class)); assertThat(document.get().getId(), equalTo("12")); assertNull(getDocumentAdapter(ResourceIdentifier.class) .fromJson(TestUtil.fromResource("/relationship_single_null.json")).get()); } @Test public void deserialize_multiple_resource_identifiers() throws Exception { Document document = getDocumentAdapter(ResourceIdentifier.class) .fromJson(TestUtil.fromResource("/relationship_multi.json")); assertThat(document.size(), equalTo(2)); assertThat(document.get(0), instanceOf(ResourceIdentifier.class)); assertThat(document.get(1).getType(), equalTo("tags")); assertTrue(getDocumentAdapter(ResourceIdentifier.class) .fromJson(TestUtil.fromResource("/relationship_multi_empty.json")).isList()); } @Test public void serialize_resource_identifier() throws Exception { Document document = new Document(); document.set(new ResourceIdentifier("people", "5")); assertThat(getDocumentAdapter(ResourceIdentifier.class).toJson(document), equalTo("{\"data\":{\"type\":\"people\",\"id\":\"5\"}}")); } @Test public void serialize_multiple_resource_identifiers() throws Exception { Document document = new Document(); document.add(new ResourceIdentifier("people", "5")); document.add(new ResourceIdentifier("people", "11")); assertThat(getDocumentAdapter(ResourceIdentifier.class).toJson(document), equalTo("{\"data\":[{\"type\":\"people\",\"id\":\"5\"},{\"type\":\"people\",\"id\":\"11\"}]}")); } @Test public void serialize_errors() throws Exception { Error error = new Error(); error.setId("4"); error.setStatus("502"); error.setTitle("Internal error"); error.setCode("502000"); error.setDetail("Ouch! There's some trouble with our server."); Document document = new Document(); document.errors(Collections.singletonList(error)); assertThat(getDocumentAdapter(null).toJson(document), equalTo("{\"data\":null,\"error\":[{\"id\":\"4\",\"status\":\"502\",\"code\":\"502000\",\"title\":\"Internal error\",\"detail\":\"Ouch! There's some trouble with our server.\"}]}")); } @Test public void deserialize_errors() throws Exception { Document document1 = getDocumentAdapter(null).fromJson(TestUtil.fromResource("/errors.json")); assertTrue(document1.hasError()); assertEquals(document1.errors().size(), 2); Document document2 = getDocumentAdapter(null).fromJson(TestUtil.fromResource("/errors_empty.json")); assertFalse(document2.hasError()); } @Test public void deserialize_meta() throws Exception { Document document = getDocumentAdapter(null).fromJson(TestUtil.fromResource("/meta.json")); assertThat(document.getMeta().get(TestUtil.moshi().adapter(Meta.class)), instanceOf(Meta.class)); } @Test public void equality() throws Exception { Document<Article> document1 = getDocumentAdapter(Article.class).fromJson(TestUtil.fromResource("/multiple_compound.json")); Document<Resource> document2 = getDocumentAdapter(Resource.class, Article.class).fromJson(TestUtil.fromResource("/multiple_compound.json")); assertEquals(document1, document2); assertEquals(document1.hashCode(), document2.hashCode()); } @JsonApi(type = "articles") private static class Article2 extends Article { } public <T extends ResourceIdentifier> JsonAdapter<Document<T>> getDocumentAdapter(Class<T> typeParameter, Class<? extends Resource>... knownTypes) { Moshi moshi; if (typeParameter == null) { return (JsonAdapter) TestUtil.moshi(knownTypes).adapter(Document.class); } else if (typeParameter.getAnnotation(JsonApi.class) != null) { Class<? extends Resource>[] types = new Class[knownTypes.length + 1]; types[0] = (Class) typeParameter; for (int i = 0; i != knownTypes.length; i++) { types[i + 1] = knownTypes[i]; } moshi = TestUtil.moshi(types); } else { moshi = TestUtil.moshi(knownTypes); } return moshi.adapter(Types.newParameterizedType(Document.class, typeParameter)); } private void assertOnArticle1(Article article) { assertThat(article.getId(), equalTo("1")); assertThat(article.getType(), equalTo("articles")); assertThat(article.getTitle(), equalTo("JSON API paints my bikeshed!")); assertThat(article.getAuthor().get(), equalTo( new ResourceIdentifier("people", "9"))); assertThat(article.getComments().get(), hasItems( new ResourceIdentifier("comments", "5"), new ResourceIdentifier("comments", "12"))); } }
package system.scidb; import benchmark.caching.CachingBenchmarkDataManager; import benchmark.QueryExecutor; import benchmark.BenchmarkContext; import java.text.MessageFormat; import java.util.List; /** * @author Dimitar Misev <misev@rasdaman.com> */ public class SciDBCachingBenchmarkDataManager extends CachingBenchmarkDataManager<SciDBSystem> { public SciDBCachingBenchmarkDataManager(SciDBSystem systemController, QueryExecutor<SciDBSystem> queryExecutor, BenchmarkContext benchmarkContext) { super(systemController, queryExecutor, benchmarkContext); } @Override public long loadData() throws Exception { long totalTime = 0; List<String> sliceFilePaths = getSliceFilePaths(benchmarkContext); for (int i = 0; i < sliceFilePaths.size(); i++) { String arrayName = benchmarkContext.getArrayNameN(i); String createArray = String.format("CREATE ARRAY %s <v%d:float> [ d1=0:%d,%d,0, d2=0:%d,%d,0 ]", arrayName, i, BAND_WIDTH - 1, TILE_WIDTH, BAND_HEIGHT - 1, TILE_HEIGHT); queryExecutor.executeTimedQuery(createArray); String insertDataQuery = MessageFormat.format("INSERT( INPUT({0}, ''{1}'', 0, ''(float)''), {0});", arrayName, sliceFilePaths.get(i)); totalTime += queryExecutor.executeTimedQuery(insertDataQuery); } return totalTime; } @Override public long dropData() throws Exception { long totalTime = 0; for (int i = 0; i < ARRAY_NO; i++) { String arrayName = benchmarkContext.getArrayNameN(i); String dropCollectionQuery = MessageFormat.format("remove({0});", arrayName); totalTime += queryExecutor.executeTimedQuery(dropCollectionQuery); } return totalTime; } }
package org.kohsuke.github; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Properties; public class LifecycleTest extends AbstractGitHubApiTestBase { @Test public void testCreateRepository() throws IOException, GitAPIException, InterruptedException { GHMyself myself = gitHub.getMyself(); GHOrganization org = gitHub.getOrganization("github-api-test-org"); GHRepository repository = org.getRepository("github-api-test"); if (repository != null) { repository.delete(); Thread.sleep(1000); } repository = org.createRepository("github-api-test", "a test repository used to test kohsuke's github-api", "http://github-api.kohsuke.org/", "Core Developers", true); Thread.sleep(1000); // wait for the repository to become ready assertTrue(repository.getReleases().isEmpty()); try { GHMilestone milestone = repository.createMilestone("Initial Release", "first one"); GHIssue issue = repository.createIssue("Test Issue") .body("issue body just for grins") .milestone(milestone) .assignee(myself) .label("bug") .create(); File repoDir = new File(System.getProperty("java.io.tmpdir"), "github-api-test"); delete(repoDir); Git origin = Git.cloneRepository() .setBare(false) .setURI(repository.getSshUrl()) .setDirectory(repoDir) .setCredentialsProvider(getCredentialsProvider(myself)) .call(); commitTestFile(myself, repoDir, origin); GHRelease release = createRelease(repository); GHAsset asset = uploadAsset(release); updateAsset(release, asset); deleteAsset(release, asset); } finally { repository.delete(); } } private void updateAsset(GHRelease release, GHAsset asset) throws IOException { asset.setLabel("test label"); assertEquals("test label", release.getAssets().get(0).getLabel()); } private void deleteAsset(GHRelease release, GHAsset asset) throws IOException { asset.delete(); assertEquals(0, release.getAssets().size()); } private GHAsset uploadAsset(GHRelease release) throws IOException { GHAsset asset = release.uploadAsset(new File("pom.xml"), "application/text"); assertNotNull(asset); List<GHAsset> assets = release.getAssets(); assertEquals(1, assets.size()); assertEquals("pom.xml", assets.get(0).getName()); return asset; } private GHRelease createRelease(GHRepository repository) throws IOException { GHRelease builder = repository.createRelease("release_tag") .name("Test Release") .body("How exciting! To be able to programmatically create releases is a dream come true!") .create(); List<GHRelease> releases = repository.getReleases(); assertEquals(1, releases.size()); GHRelease release = releases.get(0); assertEquals("Test Release", release.getName()); return release; } private void commitTestFile(GHMyself myself, File repoDir, Git origin) throws IOException, GitAPIException { File dummyFile = createDummyFile(repoDir); DirCache cache = origin.add().addFilepattern(dummyFile.getName()).call(); origin.commit().setMessage("test commit").call(); origin.push().setCredentialsProvider(getCredentialsProvider(myself)).call(); } private UsernamePasswordCredentialsProvider getCredentialsProvider(GHMyself myself) throws IOException { Properties props = new Properties(); File homeDir = new File(System.getProperty("user.home")); FileInputStream in = new FileInputStream(new File(homeDir, ".github")); try { props.load(in); } finally { IOUtils.closeQuietly(in); } return new UsernamePasswordCredentialsProvider(props.getProperty("login"), props.getProperty("oauth")); } private void delete(File toDelete) { if (toDelete.isDirectory()) { for (File file : toDelete.listFiles()) { delete(file); } } toDelete.delete(); } private File createDummyFile(File repoDir) throws IOException { File file = new File(repoDir, "testFile-" + System.currentTimeMillis()); PrintWriter writer = new PrintWriter(new FileWriter(file)); try { writer.println("test file"); } finally { writer.close(); } return file; } }
package bugfree.example; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; /** * * @author ste */ public class ActivationKeyDAO { Map<String, Boolean> keys = new HashMap<>(); public void setValidationKeyValidity(final String username, boolean validity) { usernameSanityCheck(username); keys.put(username, validity); } public boolean isValidationKeyValid(final String username) { usernameSanityCheck(username); if (!keys.containsKey(username)) { return false; } return keys.get(username); } private void usernameSanityCheck(final String username) { if (StringUtils.isBlank(username)) { throw new IllegalArgumentException("username can not be blank"); } } }
package MWC.GenericData; import java.io.Serializable; import java.util.Date; public class HiResDate implements Serializable, Comparable<HiResDate> { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; // member variables /** * number of microseconds * */ long _micros; public static final String HI_RES_PROPERTY_NAME = "MWC_HI_RES"; /** * if the current application has alternate processing for hi-res & lo-res * timings, we check when asked, and remember the value here */ private static Boolean _hiResProcessing = null; // the marker for incomplete hi-res changes: // HI-RES NOT DONE // constructor /** * if the current application has alternate processing for hi-res & lo-res * timings, * * @param millis * @param micros */ public HiResDate(final long millis, final long micros) { this._micros = millis * 1000 + micros; } public HiResDate(final long millis) { this(millis, 0); } public HiResDate(final Date val) { this(val.getTime()); } public HiResDate(final HiResDate other) { _micros = other._micros; } public HiResDate() { this(new Date().getTime()); } // member methods public String toString() { return MWC.Utilities.TextFormatting.FormatRNDateTime.toString(this .getDate().getTime()) + ":" + super.toString(); } /** * when an application is capable of alternate time resolution processing * modes, this method indicates the user preference * * @return yes/no */ public static boolean inHiResProcessingMode() { if (_hiResProcessing == null) { final String hiRes = System.getProperty(HiResDate.HI_RES_PROPERTY_NAME); if (hiRes == null) { _hiResProcessing = Boolean.FALSE; } else _hiResProcessing = new Boolean(hiRes); } return _hiResProcessing.booleanValue(); } public long getMicros() { return _micros; } public Date getDate() { // throw new RuntimeException("not ready to handle long times"); return new Date(_micros / 1000); } public boolean greaterThan(final HiResDate other) { return getMicros() > other.getMicros(); } public boolean greaterThanOrEqualTo(final HiResDate other) { return getMicros() >= other.getMicros(); } public boolean lessThan(final HiResDate other) { return getMicros() < other.getMicros(); } public boolean lessThanOrEqualTo(final HiResDate other) { return getMicros() <= other.getMicros(); } /** * compare the supplied date to us * * @param o * other date * @return whether we're later than it */ public int compareTo(final HiResDate other) { int res = 0; if (this.greaterThan(other)) { res = 1; } else if (this.lessThan(other)) { res = -1; } else res = 0; return res; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (_micros ^ (_micros >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HiResDate other = (HiResDate) obj; if (_micros != other._micros) return false; return true; } }
package org.myrobotlab.test; import static org.junit.Assert.fail; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.LinkedBlockingQueue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestName; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.Runtime; import org.slf4j.Logger; public class AbstractTest { private static long coolDownTimeMs = 100; /** cached internet test value for tests */ static Boolean hasInternet = null; static boolean install = true; protected static boolean installed = true; public final static Logger log = LoggerFactory.getLogger(AbstractTest.class); static private boolean logWarnTestHeader = false; private static boolean releaseRemainingServices = true; private static boolean releaseRemainingThreads = false; protected transient Queue<Object> queue = new LinkedBlockingQueue<>(); static transient Set<Thread> threadSetStart = null; protected Set<Attachable> attached = new HashSet<>(); protected boolean printMethods = true; // private static boolean useDeprecatedThreadStop = false; @Rule public final TestName testName = new TestName(); static public String simpleName; private static boolean lineFeedFooter = true; public String getSimpleName() { return simpleName; } public String getName() { return testName.getMethodName(); } static public boolean hasInternet() { if (hasInternet == null) { hasInternet = Runtime.hasInternet(); } return hasInternet; } static public boolean isHeadless() { return Runtime.isHeadless(); } public static void main(String[] args) { try { AbstractTest test = new AbstractTest(); // LoggingFactory.init("INFO"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.giveToMonkey(test, "testFunction"); ChaosMonkey.startMonkeys(); ChaosMonkey.monkeyReport(); log.info("here"); } catch (Exception e) { log.error("main threw", e); } } // super globals - probably better not to use the mixin - but just initialize // statics in the // constructor of the AbstractTest @BeforeClass public static void setUpAbstractTest() throws Exception { String junitLogLevel = System.getProperty("junit.logLevel"); if (junitLogLevel != null) { Runtime.setLogLevel(junitLogLevel); } else { Runtime.setLogLevel("warn"); // error instead ? } log.info("setUpAbstractTest"); if (threadSetStart == null) { threadSetStart = Thread.getAllStackTraces().keySet(); } } static public List<String> getThreadNames(){ List <String> ret = new ArrayList<>(); Set<Thread> tds = Thread.getAllStackTraces().keySet(); for (Thread t : tds ) { ret.add(t.getName()); } return ret; } static public void sleep(int sleepMs) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { // don't care } } public static void sleep(long sleepTimeMs) { try { Thread.sleep(coolDownTimeMs); } catch (Exception e) { } } @AfterClass public static void tearDownAbstractTest() throws Exception { log.info("tearDownAbstractTest"); if (releaseRemainingServices) { releaseServices(); } if (logWarnTestHeader) { log.warn("=========== finished test {} ===========", simpleName); } if (lineFeedFooter) { System.out.println(); } } protected void installAll() throws ParseException, IOException { if (!installed) { log.warn("installing all services"); Runtime.install(); installed = true; } } public static void releaseServices() { // services to be cleaned up/released String[] services = Runtime.getServiceNames(); Set<String> releaseServices = new TreeSet<>(); for (String service : services) { // don't kill runtime - although in the future i hope this is possible if (!"runtime".equals(service)) { releaseServices.add(service); log.info("service {} left in registry - releasing", service); Runtime.releaseService(service); } } if (releaseServices.size() > 0) { log.info("attempted to release the following {} services [{}]", releaseServices.size(), String.join(",", releaseServices)); log.info("cooling down for {}ms for dependencies with asynchronous shutdown", coolDownTimeMs); sleep(coolDownTimeMs); } // check threads - kill stragglers // Set<Thread> stragglers = new HashSet<Thread>(); Set<Thread> threadSetEnd = Thread.getAllStackTraces().keySet(); Set<String> threadsRemaining = new TreeSet<>(); for (Thread thread : threadSetEnd) { if (!threadSetStart.contains(thread) && !"runtime_outbox_0".equals(thread.getName()) && !"runtime".equals(thread.getName())) { if (releaseRemainingThreads) { log.info("interrupting thread {}", thread.getName()); thread.interrupt(); /* * if (useDeprecatedThreadStop) { thread.stop(); } */ } else { // log.warn("thread {} marked as straggler - should be killed", // thread.getName()); threadsRemaining.add(thread.getName()); } } } if (threadsRemaining.size() > 0) { log.info("{} straggling threads remain [{}]", threadsRemaining.size(), String.join(",", threadsRemaining)); } log.info("finished the killing ..."); } public AbstractTest() { // default : make testing environment "virtual" Platform.setVirtual(true); simpleName = this.getClass().getSimpleName(); if (logWarnTestHeader) { log.warn("=========== starting test {} ===========", this.getClass().getSimpleName()); } if (install) { try { installAll(); } catch (Exception e) { log.error("installing services failed"); fail("installing service failed"); } } } public void setVirtual() { Platform.setVirtual(true); } public boolean isVirtual() { return Platform.isVirtual(); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public void testFunction() { log.info("tested testFunction"); } /* @Override public void attach(Attachable service) throws Exception { attached.add(service); } @Override public void attach(String serviceName) throws Exception { attach(Runtime.getService(serviceName)); } @Override public void detach(Attachable service) { attached.remove(service); } @Override public void detach(String serviceName) { detach(Runtime.getService(serviceName)); } @Override public void detach() { attached.clear(); } @Override public Set<String> getAttached() { Set<String> ret = new HashSet<>(); for (Attachable a : attached) { ret.add(a.getName()); } return ret; } @Override public boolean isAttached(Attachable instance) { return attached.contains(instance); } @Override public boolean isAttached(String name) { return isAttached(Runtime.getService(name)); } @Override public boolean isLocal() { return true; } */ }
package com.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.ChannelInfo; import com.dmdirc.parser.ClientInfo; import com.dmdirc.parser.IRCParser; import com.dmdirc.parser.IRCStringConverter; import com.dmdirc.parser.MyInfo; import com.dmdirc.parser.ParserError; import com.dmdirc.parser.ServerInfo; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.ServerWindow; import com.dmdirc.ui.interfaces.Window; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. * * @author chris */ public final class Server extends WritableFrameContainer implements Serializable { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new Hashtable<String, Channel>(); /** Open query windows on the server. */ private final List<Query> queries = new ArrayList<Query>(); /** The IRC Parser instance handling this server. */ private transient IRCParser parser; /** The raw frame used for this server instance. */ private Raw raw; /** The ServerWindow corresponding to this server. */ private ServerWindow window; /** The details of the server we're connecting to. */ private ServerInfo serverInfo; /** The profile we're using. */ private transient Identity profile; /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** Channels we're meant to auto-join. */ private final List<String> autochannels; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** The last activated internal frame for this server. */ private FrameContainer activeFrame = this; /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private IRCStringConverter converter = new IRCStringConverter(); /** The parser factory to use. */ private final ParserFactory parserFactory; /** * Creates a new instance of Server. Does not auto-join any channels, and * uses a default {@link ParserFactory}. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile) { this(server, port, password, ssl, profile, new ArrayList<String>()); } /** * Creates a new instance of Server. Uses a default {@link ParserFactory}. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use * @param autochannels A list of channels to auto-join when we connect */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile, final List<String> autochannels) { this(server, port, password, ssl, profile, autochannels, new ParserFactory()); } /** * Creates a new instance of Server. * * @since 0.6 * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use * @param autochannels A list of channels to auto-join when we connect * @param factory The {@link ParserFactory} to use to create parsers */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile, final List<String> autochannels, final ParserFactory factory) { super("server-disconnected", new ConfigManager("", "", server)); serverInfo = new ServerInfo(server, port, password); serverInfo.setSSL(ssl); window = Main.getUI().getServer(this); ServerManager.getServerManager().registerServer(this); WindowManager.addWindow(window); window.setTitle(server + ":" + port); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); window.getInputHandler().setTabCompleter(tabCompleter); updateIcon(); window.open(); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_GLOBAL)); this.autochannels = autochannels; this.parserFactory = factory; new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime", 60000)); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow", false)) { addRaw(); } connect(server, port, password, ssl, profile); } /** * Connects to a new server with the specified details. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use */ @Precondition({ "The IRC Parser is null or not connected", "The specified profile is not null" }) public void connect(final String server, final int port, final String password, final boolean ssl, final Identity profile) { assert profile != null; synchronized (this) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: addLine("serverConnectInProgress"); disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); return; case DISCONNECTING: addLine("serverDisconnectInProgress"); return; default: // Do nothing break; } if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } myState.transition(ServerState.CONNECTING); ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this); getConfigManager().migrate("", "", server); serverInfo = new ServerInfo(server, port, password); serverInfo.setSSL(ssl); if (getConfigManager().hasOption(DOMAIN_SERVER, "proxy.address")) { serverInfo.setUseSocks(true); serverInfo.setProxyHost(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.address")); serverInfo.setProxyUser(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.user", "")); serverInfo.setProxyPass(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.password", "")); serverInfo.setProxyPort(getConfigManager() .getOptionInt(DOMAIN_SERVER, "proxy.port", 1080)); } this.profile = profile; updateIcon(); addLine("serverConnecting", server, port); final MyInfo myInfo = getMyInfo(); CertificateManager certManager = new CertificateManager(server, getConfigManager()); parser = parserFactory.getParser(myInfo, serverInfo); parser.setTrustManager(new TrustManager[]{certManager}); parser.setKeyManagers(certManager.getKeyManager()); parser.setRemoveAfterCallback(true); parser.setCreateFake(true); parser.setIgnoreList(ignoreList); if (getConfigManager().hasOption(DOMAIN_GENERAL, "bindip")) { parser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } doCallbacks(); awayMessage = null; removeInvites(); window.setAwayIndicator(false); try { new Thread(parser, "IRC Parser thread").start(); } catch (IllegalThreadStateException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex); } } } /** * Reconnects to the IRC server with a specified reason. * * @param reason The quit reason to send */ public void reconnect(final String reason) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(serverInfo.getHost(), serverInfo.getPort(), serverInfo.getPassword(), serverInfo.getSSL(), profile); } } /** * Reconnects to the IRC server. */ public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** * Disconnects from the server with the default quit message. */ public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** * Disconnects from the server. * * @param reason disconnect reason */ public void disconnect(final String reason) { synchronized (this) { switch (myState.getState()) { case CLOSING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parser.disconnect(reason); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit", false)) { closeChannels(); } else { clearChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit", false)) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (this) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay", 5000)); handleNotification("connectRetry", getName(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (Server.this) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } /** * Determines whether the server knows of the specified channel. * * @param channel The channel to be checked * @return True iff the channel is known, false otherwise */ public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** * Retrieves the specified channel belonging to this server. * * @param channel The channel to be retrieved * @return The appropriate channel object */ public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** * Retrieves a list of channel names belonging to this server. * * @return list of channel names belonging to this server */ public List<String> getChannels() { final ArrayList<String> res = new ArrayList<String>(); for (String channel : channels.keySet()) { res.add(channel); } return res; } /** * Determines whether the server knows of the specified query. * * @param host The host of the query to look for * @return True iff the query is known, false otherwise */ public boolean hasQuery(final String host) { final String nick = ClientInfo.parseHost(host); for (Query query : queries) { if (converter.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) { return true; } } return false; } /** * Retrieves the specified query belonging to this server. * * @param host The host of the query to look for * @return The appropriate query object */ public Query getQuery(final String host) { final String nick = ClientInfo.parseHost(host); for (Query query : queries) { if (converter.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) { return query; } } throw new IllegalArgumentException("No such query: " + host); } /** * Retrieves a list of queries belonging to this server. * * @return list of queries belonging to this server */ public List<Query> getQueries() { return new ArrayList<Query>(queries); } /** * Adds a raw window to this server. */ public void addRaw() { if (raw == null) { raw = new Raw(this); if (parser != null) { raw.registerCallbacks(); } } else { raw.activateFrame(); } } /** * Retrieves the raw window associated with this server. * * @return The raw window associated with this server. */ public Raw getRaw() { return raw; } /** * Removes our reference to the raw object (presumably after it has been * closed). */ public void delRaw() { raw = null; //NOPMD } /** * Removes a specific channel and window from this server. * * @param chan channel to remove */ public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** * Adds a specific channel and window to this server. * * @param chan channel to add */ public void addChannel(final ChannelInfo chan) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return; } } if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); newChan.show(); } } /** * Adds a query to this server. * * @param host host of the remote client being queried */ public void addQuery(final String host) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return; } } if (!hasQuery(host)) { final Query newQuery = new Query(this, host); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, ClientInfo.parseHost(host)); queries.add(newQuery); } } /** * Deletes a query from this server. * * @param query The query that should be removed. */ public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(query); } /** {@inheritDoc} */ @Override public boolean ownsFrame(final Window target) { // Check if it's our server frame if (window != null && window.equals(target)) { return true; } // Check if it's the raw frame if (raw != null && raw.ownsFrame(target)) { return true; } // Check if it's a channel frame for (Channel channel : channels.values()) { if (channel.ownsFrame(target)) { return true; } } // Check if it's a query frame for (Query query : queries) { if (query.ownsFrame(target)) { return true; } } return false; } /** * Sets the specified frame as the most-recently activated. * * @param source The frame that was activated */ public void setActiveFrame(final FrameContainer source) { activeFrame = source; } /** * Retrieves a list of all children of this server instance. * * @return A list of this server's children */ public List<WritableFrameContainer> getChildren() { final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>(); if (raw != null) { res.add(raw); } res.addAll(channels.values()); res.addAll(queries); return res; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? serverInfo.getSSL() ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Retrieves the MyInfo object used for the IRC Parser. * * @return The MyInfo object for our profile */ @Precondition({ "The current profile is not null", "The current profile specifies at least one nickname" }) private MyInfo getMyInfo() { Logger.assertTrue(profile != null); Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty()); final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0)); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOption(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries) { query.reregister(); } } /** * Joins the specified channel, or adds it to the auto-join list if the * server is not connected. * * @param channel The channel to be joined */ public void join(final String channel) { synchronized (this) { if (myState.getState() == ServerState.CONNECTED) { removeInvites(channel); if (hasChannel(channel)) { getChannel(channel).join(); getChannel(channel).activateFrame(); } else { parser.joinChannel(channel); } } else { autochannels.add(channel); } } } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (this) { if (parser != null && myState.getState() == ServerState.CONNECTED) { parser.sendLine(window.getTranscoder().encode(line)); } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { return IRCParser.MAX_LINELENGTH; } /** * Retrieves the parser used for this connection. * * @return IRCParser this connection's parser */ public IRCParser getParser() { return parser; } /** * Retrieves the profile that's in use for this server. * * @return The profile in use by this server */ public Identity getProfile() { return profile; } /** * Retrieves the name of this server. * * @return The name of this server */ public String getName() { return serverInfo.getHost(); } /** * Retrieves the name of this server's network. The network name is * determined using the following rules: * * 1. If the server includes its network name in the 005 information, we * use that * 2. If the server's name ends in biz, com, info, net or org, we use the * second level domain (e.g., foo.com) * 3. If the server's name contains more than two dots, we drop everything * up to and including the first part, and use the remainder * 4. In all other cases, we use the full server name * * @return The name of this server's network */ public String getNetwork() { if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** * Retrieves the name of this server's IRCd. * * @return The name of this server's IRCd */ public String getIrcd() { return parser.getIRCD(true); } /** * Returns the current away status. * * @return True if the client is marked as away, false otherwise */ public boolean isAway() { return awayMessage != null; } /** * Gets the current away message. * * @return Null if the client isn't away, or a textual away message if it is */ public String getAwayMessage() { return awayMessage; } /** * Returns the tab completer for this connection. * * @return The tab completer for this server */ public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public InputWindow getFrame() { return window; } /** * Retrieves the current state for this server. * * @return This server's state */ public ServerState getState() { return myState.getState(); } /** * Retrieves the status object for this server. Effecting state transitions * on the object returned by this method will almost certainly cause * problems. * * @since 0.6.3 * @return This server's status object. */ public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (this) { // 1: Make the window non-visible window.setVisible(false); // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary if (parser != null && parser.isReady()) { disconnect(); } myState.transition(ServerState.CLOSING); closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); // 6: Remove the window from the window manager WindowManager.removeWindow(window); // 7: Remove any references to the window and parents window = null; //NOPMD parser = null; //NOPMD } } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries)) { query.close(); } } /** * Passes the arguments to the most recently activated frame for this * server. If the frame isn't know, or isn't visible, use this frame * instead. * * @param messageType The type of message to send * @param args The arguments for the message */ public void addLineToActive(final String messageType, final Object... args) { if (activeFrame == null || !activeFrame.getFrame().isVisible()) { activeFrame = this; } activeFrame.getFrame().addLine(messageType, args); } /** * Passes the arguments to all frames for this server. * * @param messageType The type of message to send * @param args The arguments of the message */ public void addLineToAll(final String messageType, final Object... args) { for (Channel channel : channels.values()) { channel.getFrame().addLine(messageType, args); } for (Query query : queries) { query.getFrame().addLine(messageType, args); } addLine(messageType, args); } /** * Replies to an incoming CTCP message. * * @param source The source of the message * @param type The CTCP type * @param args The CTCP arguments */ public void sendCTCPReply(final String source, final String type, final String args) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + Main.VERSION + " - http: } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } /** * Determines if the specified channel name is valid. A channel name is * valid if we already have an existing Channel with the same name, or * we have a valid parser instance and the parser says it's valid. * * @param channelName The name of the channel to test * @return True if the channel name is valid, false otherwise */ public boolean isValidChannelName(final String channelName) { return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } /** * Returns this server's name. * * @return A string representation of this server (i.e., its name) */ @Override public String toString() { return getName(); } /** * Returns the server instance associated with this frame. * * @return the associated server connection */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getIdent()); args.add(clientInfo.getHost()); return true; } else { return super.processNotificationArg(arg, args); } } /** * Retusnt the list of invites for this server. * * @return Invite list */ public List<Invite> getInvites() { return invites; } /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getMyNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + (int) (Math.random() * 10); final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames"); int offset = 0; // Loop so we can check case sensitivity for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } if (offset < alts.size() && !alts.get(offset).isEmpty()) { newNick = alts.get(offset); } parser.setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String withIrcd = "numeric_" + parser.getIRCD(true) + "_" + snumeric; final String sansIrcd = "numeric_" + snumeric; StringBuffer target = null; if (getConfigManager().hasOption("formatter", withIrcd)) { target = new StringBuffer(withIrcd); } else if (getConfigManager().hasOption("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOption("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); if (target != null) { handleNotification(target.toString(), (Object[]) tokens); } } /** * Called when the socket has been closed. */ public void onSocketClosed() { handleNotification("socketClosed", getName()); ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (this) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } parser = null; updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect", false)) { closeChannels(); } else { clearChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect", false)) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect", false) && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { // Do nothing return; } else if (myState.getState() == ServerState.DISCONNECTING) { // Pretend it closed nicely onSocketClosed(); return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\nState: " + myState); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); parser = null; updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketException || exception instanceof javax.net.ssl.SSLException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error", exception); description = "Unknown error: " + exception.getMessage(); } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getName(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure", false)) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { Main.getUI().getStatusBar().setMessage("No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime(false) / 1000.0))) + " seconds.", null, 10); ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime(false))); if (parser.getPingTime(false) >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout", 60000)) { handleNotification("stonedServer", getName()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (this) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\nState: " + myState); } myState.transition(ServerState.CONNECTED); updateIcon(); getConfigManager().migrate(parser.getIRCD(true), getNetwork(), getName()); updateIgnoreList(); converter = parser.getIRCStringConverter(); ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this); if (getConfigManager().hasOption(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { chan.join(); } } for (String channel : autochannels) { parser.joinChannel(channel); } checkModeAliases(); } } /** * Checks that we have the neccessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBoolChanModes() + parser.getListChanModes() + parser.getSetOnlyChanModes() + parser.getSetUnsetChanModes(); final String umodes = parser.getUserModeString(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOption(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOption(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + parser.getIRCD(true) + "]", new Exception(missing.toString() + "\n" // NOPMD + "Network: " + getNetwork() + "\n" + "IRCd: " + parser.getIRCD(false) + " (" + parser.getIRCD(true) + ")\n" + "Mode alias version: " + getConfigManager().getOption("identity", "modealiasversion", "none") + "\n\n")); } } /** * Retrieves this server's ignore list. * * @return This server's ignore list */ public IgnoreList getIgnoreList() { return ignoreList; } /** * Updates this server's ignore list to use the entries stored in the * config manager. */ public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** * Saves the contents of our ignore list to the network identity. */ public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } /** * Retrieves the identity for this server. * * @return This server's identity */ public Identity getServerIdentity() { return IdentityManager.getServerConfig(getName()); } /** * Retrieves the identity for this server's network. * * @return This server's network identity */ public Identity getNetworkIdentity() { return IdentityManager.getNetworkConfig(getNetwork()); } /** * Adds an invite listener to this server. * * @param listener The listener to be added */ public void addInviteListener(final InviteListener listener) { listeners.add(InviteListener.class, listener); } /** * Removes an invite listener from this server. * * @param listener The listener to be removed */ public void removeInviteListener(final InviteListener listener) { listeners.remove(InviteListener.class, listener); } /** * Adds an invite to this server, and fires the appropriate listeners. * * @param invite The invite to be added */ public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } /** * Removes all invites for the specified channel. * * @param channel The channel to remove invites for */ public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** * Removes all invites for all channels. */ private void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** * Removes an invite from this server, and fires the appropriate listeners. * * @param invite The invite to be removed */ public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } /** * Adds an away state lisener to this server. * * @param listener The listener to be added */ public void addAwayStateListener(final AwayStateListener listener) { listeners.add(AwayStateListener.class, listener); } /** * Removes an away state lisener from this server. * * @param listener The listener to be removed */ public void removeAwayStateListener(final AwayStateListener listener) { listeners.remove(AwayStateListener.class, listener); } /** * Updates our away state and fires the relevant listeners. * * @param message The away message to use, or null if we're not away. */ public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } }
package ca.sait.stars.domains; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the stars_record_data database table. * * @author william * */ @Entity @Table(name = "stars_record_data", uniqueConstraints = @UniqueConstraint(columnNames = { "owner", "title", "time" })) @NamedQuery(name = "RecordData.findAll", query = "SELECT r FROM RecordData r") public class RecordData implements Serializable { private static final long serialVersionUID = -2179632862300221506L; @EmbeddedId private RecordDataPK id; @Column(nullable = false) private double cacc; @Column(nullable = false) private double gpsfix; @Column(nullable = false) private double hacc; @Column(nullable = false) private double hmsl; @Column(nullable = false) private double heading; @Column(nullable = false) private double lat; @Column(nullable = false) private double lon; @Column(nullable = false) private double numsv; @Column(nullable = false) private double sacc; @Column(nullable = false) private double vacc; @Column(nullable = false) private double veld; @Column(nullable = false) private double vele; @Column(nullable = false) private double veln; // bi-directional many-to-one association to Record @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name = "owner", referencedColumnName = "owner", nullable = false, insertable = false, updatable = false), @JoinColumn(name = "title", referencedColumnName = "title", nullable = false, insertable = false, updatable = false) }) private Record record; public RecordDataPK getId() { return this.id; } public void setId(RecordDataPK id) { this.id = id; } public double getCacc() { return cacc; } public void setCacc(double cacc) { this.cacc = cacc; } public double getGpsfix() { return gpsfix; } public void setGpsfix(double gpsfix) { this.gpsfix = gpsfix; } public double getHacc() { return hacc; } public void setHacc(double hacc) { this.hacc = hacc; } public double getHmsl() { return hmsl; } public void setHmsl(double hmsl) { this.hmsl = hmsl; } public double getHeading() { return heading; } public void setHeading(double heading) { this.heading = heading; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public double getNumsv() { return numsv; } public void setNumsv(double numsv) { this.numsv = numsv; } public double getSacc() { return sacc; } public void setSacc(double sacc) { this.sacc = sacc; } public double getVacc() { return vacc; } public void setVacc(double vacc) { this.vacc = vacc; } public double getVeld() { return veld; } public void setVeld(double veld) { this.veld = veld; } public double getVele() { return vele; } public void setVele(double vele) { this.vele = vele; } public double getVeln() { return veln; } public void setVeln(double veln) { this.veln = veln; } public Record getRecord() { return this.record; } public void setRecord(Record record) { this.record = record; } @Override public String toString() { return id.toString(); } }
package org.postgresql.test.jdbc3; import junit.framework.TestCase; import org.postgresql.core.NativeQuery; import org.postgresql.core.Parser; import java.util.List; public class CompositeQueryParseTest extends TestCase { public void testEmptyQuery() { assertEquals("", reparse("", true, false, true)); } public void testWhitespaceQuery() { assertEquals("", reparse(" ", true, false, true)); } public void testOnlyEmptyQueries() { assertEquals("", reparse(";;;; ; \n;\n", true, false, true)); } public void testSimpleQuery() { assertEquals("select 1", reparse("select 1", true, false, true)); } public void testSimpleBind() { assertEquals("select $1", reparse("select ?", true, false, true)); } public void testQuotedQuestionmark() { assertEquals("select '?'", reparse("select '?'", true, false, true)); } public void testDoubleQuestionmark() { assertEquals("select '?', $1 ?=> $2", reparse("select '?', ? ??=> ?", true, false, true)); } public void testCompositeBasic() { assertEquals("select 1;/*cut*/\n select 2", reparse("select 1; select 2", true, false, true)); } public void testCompositeWithBinds() { assertEquals("select $1;/*cut*/\n select $1", reparse("select ?; select ?", true, false, true)); } public void testTrailingSemicolon() { assertEquals("select 1", reparse("select 1;", true, false, true)); } public void testTrailingSemicolonAndSpace() { assertEquals("select 1", reparse("select 1; ", true, false, true)); } public void testMultipleTrailingSemicolons() { assertEquals("select 1", reparse("select 1;;;", true, false, true)); } public void testMultipleEmptyQueries() { assertEquals("select 1;/*cut*/\n" + "select 2", reparse("select 1; ;\t;select 2", true, false, true)); } public void testCompositeWithComments() { assertEquals("select 1;/*cut*/\n" + "/* noop */;/*cut*/\n" + "select 2", reparse("select 1;/* noop */;select 2", true, false, true)); } private String reparse(String query, boolean standardConformingStrings, boolean withParameters, boolean splitStatements) { return toString(Parser.parseJdbcSql(query, standardConformingStrings, withParameters, splitStatements)); } private String toString(List<NativeQuery> queries) { StringBuilder sb = new StringBuilder(); for (NativeQuery query : queries) { if (sb.length() != 0) { sb.append(";/*cut*/\n"); } sb.append(query.nativeSql); } return sb.toString(); } }
package com.emailclue.api; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import java.util.Map; import static com.emailclue.api.EmailClue.configuration; import static com.emailclue.api.EmailClue.fromTemplate; import static com.emailclue.api.Util.fixture; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; public class EmailClueSendTest { private final EmailClue emailClueClient = EmailClue.emailClue( configuration() .apiKey("12873782347TOKEN") .host("http://localhost:8089") ); @Rule public WireMockRule wireMockRule = new WireMockRule(8089); @Before public void setUp() { } @Test @Ignore public void canSendEmail() { stubFor(post(urlEqualTo("/v1/email/message/send")) .willReturn(aResponse() .withHeader("MediaType", "application/json") .withBody("{ \"messageId\": \"msg101\"}"))); Map<String, Object> templateData = ImmutableMap.<String, Object>builder() .put("name", "Homer") .build(); emailClueClient.sendEmail( fromTemplate("TEMPLATE101") .to("recipient@example.com") .cc("cc@example.com") .subject("Test Email") .templateData(ImmutableMap.<String, Object>of( "toName", "Daniel", "contact", ImmutableMap.of( "name", "James", "url", "http://google.com" ) ))); verify(postRequestedFor(urlEqualTo("/v1/email/message/send")) .withHeader("Authorization", equalTo("Bearer 12873782347TOKEN")) .withRequestBody(equalToJson(fixture("response/send.json")))); } }
package com.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.parsers.ServerCommandParser; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.interfaces.Connection; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.common.ChannelJoinRequest; import com.dmdirc.parser.common.DefaultStringConverter; import com.dmdirc.parser.common.IgnoreList; import com.dmdirc.parser.common.MyInfo; import com.dmdirc.parser.common.ParserError; import com.dmdirc.parser.common.ThreadedParser; import com.dmdirc.parser.interfaces.ChannelInfo; import com.dmdirc.parser.interfaces.ClientInfo; import com.dmdirc.parser.interfaces.EncodingParser; import com.dmdirc.parser.interfaces.Parser; import com.dmdirc.parser.interfaces.ProtocolDescription; import com.dmdirc.parser.interfaces.SecureParser; import com.dmdirc.parser.interfaces.StringConverter; import com.dmdirc.tls.CertificateManager; import com.dmdirc.tls.CertificateProblemListener; import com.dmdirc.ui.StatusMessage; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.core.components.StatusBarManager; import com.dmdirc.ui.core.components.WindowComponent; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.messages.Formatter; import java.net.URI; import java.net.URISyntaxException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. */ public class Server extends WritableFrameContainer implements ConfigChangeListener, CertificateProblemListener, Connection { // <editor-fold defaultstate="collapsed" desc="Properties"> // <editor-fold defaultstate="collapsed" desc="Static"> /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Instance"> /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new ConcurrentSkipListMap<String, Channel>(); /** Open query windows on the server. */ private final Map<String, Query> queries = new ConcurrentSkipListMap<String, Query>(); /** The Parser instance handling this server. */ private Parser parser; /** The Parser instance that used to be handling this server. */ private Parser oldParser; /** The parser-supplied protocol description object. */ private ProtocolDescription protocolDescription; /** * Object used to synchronise access to parser. This object should be * locked by anything requiring that the parser reference remains the same * for a duration of time, or by anything which is updating the parser * reference. * * If used in conjunction with myStateLock, the parserLock must always be * locked INSIDE the myStateLock to prevent deadlocks. */ private final ReadWriteLock parserLock = new ReentrantReadWriteLock(); /** The raw frame used for this server instance. */ private Raw raw; /** The address of the server we're connecting to. */ private URI address; /** The profile we're using. */ private Identity profile; /** Object used to synchronise access to myState. */ private final Object myStateLock = new Object(); /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(this, myStateLock); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** A set of channels we want to join without focusing. */ private final Set<String> backgroundChannels = new HashSet<String>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private StringConverter converter = new DefaultStringConverter(); /** The certificate manager in use, if any. */ private CertificateManager certificateManager; // </editor-fold> // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructors"> /** * Creates a new server which will connect to the specified URL with * the specified profile. * * @since 0.6.3 * @param uri The address of the server to connect to * @param profile The profile to use */ public Server(final URI uri, final Identity profile) { super("server-disconnected", getHost(uri), getHost(uri), new ConfigManager(uri.getScheme(), "", "", uri.getHost()), new ServerCommandParser(), Arrays.asList(WindowComponent.TEXTAREA.getIdentifier(), WindowComponent.INPUTFIELD.getIdentifier(), WindowComponent.CERTIFICATE_VIEWER.getIdentifier())); setConnectionDetails(uri, profile); ServerManager.getServerManager().registerServer(this); WindowManager.getWindowManager().addWindow(this); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandManager().getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandManager().getCommandNames(CommandType.TYPE_GLOBAL)); updateIcon(); new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime")); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow")) { addRaw(); } getConfigManager().addChangeListener("formatter", "serverName", this); getConfigManager().addChangeListener("formatter", "serverTitle", this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Connection, disconnection & reconnection"> /** * Updates the connection details for this server. If the specified URI * does not define a port, the default port from the protocol description * will be used. * * @param uri The new URI that this server should connect to * @param profile The profile that this server should use */ private void setConnectionDetails(final URI uri, final Identity profile) { this.address = uri; this.protocolDescription = new ParserFactory().getDescription(uri); this.profile = profile; if (uri.getPort() == -1 && protocolDescription != null) { try { this.address = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), protocolDescription.getDefaultPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to construct URI", ex); } } } /** {@inheritDoc} */ @Override public void connect() { connect(address, profile); } /** {@inheritDoc} */ @Override @Precondition({ "The current parser is null or not connected", "The specified profile is not null" }) @SuppressWarnings("fallthrough") public void connect(final URI address, final Identity profile) { assert profile != null; synchronized (myStateLock) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); case DISCONNECTING: while (!myState.getState().isDisconnected()) { try { myStateLock.wait(); } catch (InterruptedException ex) { return; } } break; default: // Do nothing break; } final URI connectAddress; try { parserLock.writeLock().lock(); if (parser != null) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + getState()); } getConfigManager().migrate(address.getScheme(), "", "", address.getHost()); setConnectionDetails(address, profile); updateTitle(); updateIcon(); parser = buildParser(); if (parser == null) { addLine("serverUnknownProtocol", address.getScheme()); return; } connectAddress = parser.getURI(); } finally { parserLock.writeLock().unlock(); } addLine("serverConnecting", connectAddress.getHost(), connectAddress.getPort()); myState.transition(ServerState.CONNECTING); doCallbacks(); updateAwayState(null); removeInvites(); parser.connect(); if (parser instanceof ThreadedParser) { ((ThreadedParser)parser).getControlThread().setName("Parser - " + connectAddress.getHost()); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTING, null, this); } /** {@inheritDoc} */ @Override public void reconnect(final String reason) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(address, profile); } } /** {@inheritDoc} */ @Override public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** {@inheritDoc} */ @Override public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** {@inheritDoc} */ @Override public void disconnect(final String reason) { synchronized (myStateLock) { switch (myState.getState()) { case CLOSING: case DISCONNECTING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } clearChannels(); backgroundChannels.clear(); try { parserLock.readLock().lock(); if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parser.disconnect(reason); } } finally { parserLock.readLock().unlock(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit")) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (myStateLock) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay")); handleNotification("connectRetry", getAddress(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (myStateLock) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Child windows"> /** {@inheritDoc} */ @Override public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** {@inheritDoc} */ @Override public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** {@inheritDoc} */ @Override public List<String> getChannels() { return new ArrayList<String>(channels.keySet()); } /** {@inheritDoc} */ @Override public boolean hasQuery(final String host) { return queries.containsKey(converter.toLowerCase(parseHostmask(host)[0])); } /** {@inheritDoc} */ @Override public Query getQuery(final String host) { return getQuery(host, false); } /** {@inheritDoc} */ @Override public Query getQuery(final String host, final boolean focus) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return null; } } final String nick = parseHostmask(host)[0]; final String lnick = converter.toLowerCase(nick); if (!queries.containsKey(lnick)) { final Query newQuery = new Query(this, host, focus); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, nick); queries.put(lnick, newQuery); } return queries.get(lnick); } /** {@inheritDoc} */ @Override public void updateQuery(final Query query, final String oldNick, final String newNick) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, oldNick); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, newNick); queries.put(converter.toLowerCase(newNick), query); queries.remove(converter.toLowerCase(oldNick)); } /** {@inheritDoc} */ @Override public Collection<Query> getQueries() { return Collections.unmodifiableCollection(queries.values()); } /** {@inheritDoc} */ @Override public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(converter.toLowerCase(query.getNickname())); } /** {@inheritDoc} */ @Override public void addRaw() { if (raw == null) { raw = new Raw(this); try { parserLock.readLock().lock(); if (parser != null) { raw.registerCallbacks(); } } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public Raw getRaw() { return raw; } /** {@inheritDoc} */ @Override public void delRaw() { raw = null; //NOPMD } /** {@inheritDoc} */ @Override public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** {@inheritDoc} */ @Override public Channel addChannel(final ChannelInfo chan) { return addChannel(chan, !backgroundChannels.contains(chan.getName()) || getConfigManager().getOptionBool(DOMAIN_GENERAL, "hidechannels")); } /** {@inheritDoc} */ @Override public Channel addChannel(final ChannelInfo chan, final boolean focus) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return null; } } backgroundChannels.remove(chan.getName()); if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan, focus); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); } return getChannel(chan.getName()); } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries.values())) { query.close(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Miscellaneous methods"> private static String getHost(final URI uri) { if (uri.getHost() == null) { throw new IllegalArgumentException("URIs must have hosts"); } return uri.getHost(); } /** * Builds an appropriately configured {@link Parser} for this server. * * @return A configured parser. */ private Parser buildParser() { final MyInfo myInfo = buildMyInfo(); final Parser myParser = new ParserFactory().getParser(myInfo, address); if (myParser instanceof SecureParser) { certificateManager = new CertificateManager(address.getHost(), getConfigManager()); final SecureParser secureParser = (SecureParser) myParser; secureParser.setTrustManagers(new TrustManager[]{certificateManager}); secureParser.setKeyManagers(certificateManager.getKeyManager()); certificateManager.addCertificateProblemListener(this); } if (myParser instanceof EncodingParser) { final EncodingParser encodingParser = (EncodingParser) myParser; encodingParser.setEncoder(new MessageEncoder(this, myParser)); } if (myParser != null) { myParser.setIgnoreList(ignoreList); myParser.setPingTimerInterval(getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimer")); myParser.setPingTimerFraction((int) (getConfigManager().getOptionInt(DOMAIN_SERVER, "pingfrequency") / myParser.getPingTimerInterval())); if (getConfigManager().hasOptionString(DOMAIN_GENERAL, "bindip")) { myParser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } myParser.setProxy(buildProxyURI()); } return myParser; } /** * Constructs a URI for the configured proxy for this server, if any. * * @return An appropriate URI or null if no proxy is configured */ private URI buildProxyURI() { if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.address")) { final String type; if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.type")) { type = getConfigManager().getOption(DOMAIN_SERVER, "proxy.type"); } else { type = "socks"; } final int port; if (getConfigManager().hasOptionInt(DOMAIN_SERVER, "proxy.port")) { port = getConfigManager().getOptionInt(DOMAIN_SERVER, "proxy.port"); } else { port = 8080; } final String host = getConfigManager().getOptionString(DOMAIN_SERVER, "proxy.address"); final String userInfo; if (getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.username") && getConfigManager().hasOptionString(DOMAIN_SERVER, "proxy.password")) { userInfo = getConfigManager().getOption(DOMAIN_SERVER, "proxy.username") + getConfigManager().getOption(DOMAIN_SERVER, "proxy.password"); } else { userInfo = ""; } try { return new URI(type, userInfo, host, port, "", "", ""); } catch (URISyntaxException ex) { Logger.appError(ErrorLevel.MEDIUM, "Unable to create proxy URI", ex); } } return null; } /** {@inheritDoc} */ @Override public boolean compareURI(final URI uri) { if (parser != null) { return parser.compareURI(uri); } if (oldParser != null) { return oldParser.compareURI(uri); } return false; } /** {@inheritDoc} */ @Override public String[] parseHostmask(final String hostmask) { return protocolDescription.parseHostmask(hostmask); } /** * Retrieves the MyInfo object used for the Parser. * * @return The MyInfo object for our profile */ @Precondition({ "The current profile is not null", "The current profile specifies at least one nickname" }) private MyInfo buildMyInfo() { Logger.assertTrue(profile != null); Logger.assertTrue(!profile.getOptionList(DOMAIN_PROFILE, "nicknames").isEmpty()); final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOptionList(DOMAIN_PROFILE, "nicknames").get(0)); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOptionString(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? protocolDescription.isSecure(address) ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries.values()) { query.reregister(); } } /** {@inheritDoc} */ @Override public void join(final ChannelJoinRequest ... requests) { join(true, requests); } /** {@inheritDoc} */ @Override public void join(final boolean focus, final ChannelJoinRequest ... requests) { synchronized (myStateLock) { if (myState.getState() == ServerState.CONNECTED) { final List<ChannelJoinRequest> pending = new ArrayList<ChannelJoinRequest>(); for (ChannelJoinRequest request : requests) { removeInvites(request.getName()); final String name; if (parser.isValidChannelName(request.getName())) { name = request.getName(); } else { name = parser.getChannelPrefixes().substring(0, 1) + request.getName(); } if (!hasChannel(name) || !getChannel(name).isOnChannel()) { if (!focus) { backgroundChannels.add(name); } pending.add(request); } } parser.joinChannels(pending.toArray(new ChannelJoinRequest[pending.size()])); } // TODO: otherwise: address.getChannels().add(channel); } } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (myStateLock) { try { parserLock.readLock().lock(); if (parser != null && !line.isEmpty() && myState.getState() == ServerState.CONNECTED) { parser.sendRawMessage(line); } } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { try { parserLock.readLock().lock(); return parser == null ? -1 : parser.getMaxLength(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public Parser getParser() { return parser; } /** {@inheritDoc} */ @Override public Identity getProfile() { return profile; } /** {@inheritDoc} */ @Override public String getChannelPrefixes() { try { parserLock.readLock().lock(); return parser == null ? "#&" : parser.getChannelPrefixes(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public String getAddress() { try { parserLock.readLock().lock(); return parser == null ? address.getHost() : parser.getServerName(); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public String getNetwork() { try { parserLock.readLock().lock(); if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null (state: " + getState() + ")"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public boolean isNetwork(final String target) { synchronized (myStateLock) { try { parserLock.readLock().lock(); if (parser == null) { return false; } else { return getNetwork().equalsIgnoreCase(target); } } finally { parserLock.readLock().unlock(); } } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; break; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** {@inheritDoc} */ @Override public String getIrcd() { return parser.getServerSoftwareType(); } /** {@inheritDoc} */ @Override public String getProtocol() { return address.getScheme(); } /** {@inheritDoc} */ @Override public boolean isAway() { return awayMessage != null; } /** {@inheritDoc} */ @Override public String getAwayMessage() { return awayMessage; } /** {@inheritDoc} */ @Override public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public ServerState getState() { return myState.getState(); } /** {@inheritDoc} */ @Override public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (myStateLock) { // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary disconnect(); myState.transition(ServerState.CLOSING); } closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); } /** {@inheritDoc} */ @Override public void windowClosed() { // 7: Remove any references to the window and parents oldParser = null; //NOPMD parser = null; //NOPMD } /** {@inheritDoc} */ @Override public void addLineToAll(final String messageType, final Date date, final Object... args) { for (Channel channel : channels.values()) { channel.addLine(messageType, date, args); } for (Query query : queries.values()) { query.addLine(messageType, date, args); } addLine(messageType, date, args); } /** {@inheritDoc} */ @Override public void sendCTCPReply(final String source, final String type, final String args) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + getConfigManager().getOption("version", "version") + " - http: } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } /** {@inheritDoc} */ @Override public boolean isValidChannelName(final String channelName) { try { parserLock.readLock().lock(); return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } finally { parserLock.readLock().unlock(); } } /** {@inheritDoc} */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getUsername()); args.add(clientInfo.getHostname()); return true; } else { return super.processNotificationArg(arg, args); } } /** {@inheritDoc} */ @Override public void updateTitle() { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING) { return; } try { parserLock.readLock().lock(); final Object[] arguments = new Object[]{ address.getHost(), parser == null ? "Unknown" : parser.getServerName(), address.getPort(), parser == null ? "Unknown" : getNetwork(), parser == null ? "Unknown" : parser.getLocalClient().getNickname(), }; setName(Formatter.formatMessage(getConfigManager(), "serverName", arguments)); setTitle(Formatter.formatMessage(getConfigManager(), "serverTitle", arguments)); } finally { parserLock.readLock().unlock(); } } } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if ("formatter".equals(domain)) { updateTitle(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Parser callbacks"> /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getLocalClient().getNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + new Random().nextInt(10); final List<String> alts = profile.getOptionList(DOMAIN_PROFILE, "nicknames"); int offset = 0; // Loop so we can check case sensitivity for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } if (offset < alts.size() && !alts.get(offset).isEmpty()) { newNick = alts.get(offset); } parser.getLocalClient().setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String sansIrcd = "numeric_" + snumeric; StringBuffer target = new StringBuffer(""); if (getConfigManager().hasOptionString("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOptionString("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); handleNotification(target.toString(), (Object[]) tokens); } /** * Called when the socket has been closed. */ public void onSocketClosed() { if (Thread.holdsLock(myStateLock)) { new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { onSocketClosed(); } }, "Socket closed deferred thread").start(); return; } handleNotification("socketClosed", getAddress()); ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconnect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } clearChannels(); try { parserLock.writeLock().lock(); oldParser = parser; parser = null; } finally { parserLock.writeLock().unlock(); } updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect")) { closeChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect")) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect") && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (myStateLock) { if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTING) { // Do nothing return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\n" + getStatus().getTransitionHistory()); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); try { parserLock.writeLock().lock(); oldParser = parser; parser = null; } finally { parserLock.writeLock().unlock(); } updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketTimeoutException) { description = "Connection attempt timed out"; } else if (exception instanceof java.net.SocketException || exception instanceof javax.net.ssl.SSLException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error: " + exception.getClass().getCanonicalName(), new IllegalArgumentException(exception)); description = "Unknown error: " + exception.getMessage(); } } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getAddress(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure")) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { StatusBarManager.getStatusBarManager().setMessage(new StatusMessage( "No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime() / 1000.0))) + " seconds.", getConfigManager())); ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime())); if (parser.getPingTime() >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout")) { handleNotification("stonedServer", getAddress()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (myStateLock) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\n" + myState.getTransitionHistory()); } if (myState.getState() != ServerState.CONNECTING) { // We've transitioned while waiting for the lock. Just abort. return; } myState.transition(ServerState.CONNECTED); getConfigManager().migrate(address.getScheme(), parser.getServerSoftwareType(), getNetwork(), parser.getServerName()); updateIcon(); updateTitle(); updateIgnoreList(); converter = parser.getStringConverter(); final List<ChannelJoinRequest> requests = new ArrayList<ChannelJoinRequest>(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { requests.add(new ChannelJoinRequest(chan.getName())); } } join(requests.toArray(new ChannelJoinRequest[requests.size()])); checkModeAliases(); } ActionManager.getActionManager().triggerEvent( CoreActionType.SERVER_CONNECTED, null, this); } /** * Checks that we have the necessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBooleanChannelModes() + parser.getListChannelModes() + parser.getParameterChannelModes() + parser.getDoubleParameterChannelModes(); final String umodes = parser.getUserModes(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOptionString(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + parser.getServerSoftwareType() + "]", new MissingModeAliasException(getNetwork(), parser, getConfigManager().getOption("identity", "modealiasversion"), missing.toString())); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Ignore lists"> /** {@inheritDoc} */ @Override public IgnoreList getIgnoreList() { return ignoreList; } /** {@inheritDoc} */ @Override public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** {@inheritDoc} */ @Override public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Identity handling"> /** {@inheritDoc} */ @Override public Identity getServerIdentity() { return IdentityManager.getIdentityManager().createServerConfig(parser.getServerName()); } /** {@inheritDoc} */ @Override public Identity getNetworkIdentity() { return IdentityManager.getIdentityManager().createNetworkConfig(getNetwork()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Invite handling"> /** {@inheritDoc} */ @Override public void addInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.add(InviteListener.class, listener); } } /** {@inheritDoc} */ @Override public void removeInviteListener(final InviteListener listener) { synchronized (listeners) { listeners.remove(InviteListener.class, listener); } } /** {@inheritDoc} */ @Override public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } } /** {@inheritDoc} */ @Override public void acceptInvites(final Invite ... invites) { final ChannelJoinRequest[] requests = new ChannelJoinRequest[invites.length]; for (int i = 0; i < invites.length; i++) { requests[i] = new ChannelJoinRequest(invites[i].getChannel()); } join(requests); } /** {@inheritDoc} */ @Override public void acceptInvites() { synchronized (invites) { acceptInvites(invites.toArray(new Invite[invites.size()])); } } /** {@inheritDoc} */ @Override public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** {@inheritDoc} */ @Override public void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** {@inheritDoc} */ @Override public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); synchronized (listeners) { for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } } /** {@inheritDoc} */ @Override public List<Invite> getInvites() { return invites; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Away state handling"> /** {@inheritDoc} */ @Override public void addAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.add(AwayStateListener.class, listener); } } /** {@inheritDoc} */ @Override public void removeAwayStateListener(final AwayStateListener listener) { synchronized (listeners) { listeners.remove(AwayStateListener.class, listener); } } /** {@inheritDoc} */ @Override public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; new Thread(new Runnable() { /** {@inheritDoc} */ @Override public void run() { synchronized (listeners) { if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } } }, "Away state listener runner").start(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="TLS listener handling"> /** {@inheritDoc} */ @Override public void addCertificateProblemListener(final CertificateProblemListener listener) { listeners.add(CertificateProblemListener.class, listener); if (certificateManager != null && !certificateManager.getProblems().isEmpty()) { listener.certificateProblemEncountered(certificateManager.getChain(), certificateManager.getProblems(), certificateManager); } } /** {@inheritDoc} */ @Override public void removeCertificateProblemListener(final CertificateProblemListener listener) { listeners.remove(CertificateProblemListener.class, listener); } /** {@inheritDoc} */ @Override public void certificateProblemEncountered(final X509Certificate[] chain, final Collection<CertificateException> problems, final CertificateManager certificateManager) { for (CertificateProblemListener listener : listeners.get(CertificateProblemListener.class)) { listener.certificateProblemEncountered(chain, problems, certificateManager); } } /** {@inheritDoc} */ @Override public void certificateProblemResolved(final CertificateManager manager) { for (CertificateProblemListener listener : listeners.get(CertificateProblemListener.class)) { listener.certificateProblemResolved(manager); } } // </editor-fold> }
package com.dmdirc; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.wrappers.AliasWrapper; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.commandparser.CommandType; import com.dmdirc.config.ConfigManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.AwayStateListener; import com.dmdirc.interfaces.InviteListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.ChannelInfo; import com.dmdirc.parser.ClientInfo; import com.dmdirc.parser.IRCParser; import com.dmdirc.parser.IRCStringConverter; import com.dmdirc.parser.MyInfo; import com.dmdirc.parser.ParserError; import com.dmdirc.parser.ServerInfo; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.input.TabCompleter; import com.dmdirc.ui.input.TabCompletionType; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.ServerWindow; import com.dmdirc.ui.interfaces.Window; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.net.ssl.TrustManager; /** * The Server class represents the client's view of a server. It maintains * a list of all channels, queries, etc, and handles parser callbacks pertaining * to the server. * * @author chris */ public final class Server extends WritableFrameContainer implements Serializable { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** The name of the general domain. */ private static final String DOMAIN_GENERAL = "general".intern(); /** The name of the profile domain. */ private static final String DOMAIN_PROFILE = "profile".intern(); /** The name of the server domain. */ private static final String DOMAIN_SERVER = "server".intern(); /** Open channels that currently exist on the server. */ private final Map<String, Channel> channels = new Hashtable<String, Channel>(); /** Open query windows on the server. */ private final List<Query> queries = new ArrayList<Query>(); /** The IRC Parser instance handling this server. */ private transient IRCParser parser; /** The raw frame used for this server instance. */ private Raw raw; /** The ServerWindow corresponding to this server. */ private ServerWindow window; /** The details of the server we're connecting to. */ private ServerInfo serverInfo; /** The profile we're using. */ private transient Identity profile; /** The current state of this server. */ private final ServerStatus myState = new ServerStatus(); /** The timer we're using to delay reconnects. */ private Timer reconnectTimer; /** Channels we're meant to auto-join. */ private final List<String> autochannels; /** The tabcompleter used for this server. */ private final TabCompleter tabCompleter = new TabCompleter(); /** The last activated internal frame for this server. */ private FrameContainer activeFrame = this; /** Our reason for being away, if any. */ private String awayMessage; /** Our event handler. */ private final ServerEventHandler eventHandler = new ServerEventHandler(this); /** A list of outstanding invites. */ private final List<Invite> invites = new ArrayList<Invite>(); /** Our ignore list. */ private final IgnoreList ignoreList = new IgnoreList(); /** Our string convertor. */ private IRCStringConverter converter = new IRCStringConverter(); /** The parser factory to use. */ private final ParserFactory parserFactory; /** * Creates a new instance of Server. Does not auto-join any channels, and * uses a default {@link ParserFactory}. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile) { this(server, port, password, ssl, profile, new ArrayList<String>()); } /** * Creates a new instance of Server. Uses a default {@link ParserFactory}. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use * @param autochannels A list of channels to auto-join when we connect */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile, final List<String> autochannels) { this(server, port, password, ssl, profile, autochannels, new ParserFactory()); } /** * Creates a new instance of Server. * * @since 0.6 * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use * @param autochannels A list of channels to auto-join when we connect * @param factory The {@link ParserFactory} to use to create parsers */ public Server(final String server, final int port, final String password, final boolean ssl, final Identity profile, final List<String> autochannels, final ParserFactory factory) { super("server-disconnected", new ConfigManager("", "", server)); serverInfo = new ServerInfo(server, port, password); serverInfo.setSSL(ssl); window = Main.getUI().getServer(this); ServerManager.getServerManager().registerServer(this); WindowManager.addWindow(window); window.setTitle(server + ":" + port); tabCompleter.addEntries(TabCompletionType.COMMAND, AliasWrapper.getAliasWrapper().getAliases()); window.getInputHandler().setTabCompleter(tabCompleter); updateIcon(); window.open(); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_SERVER)); tabCompleter.addEntries(TabCompletionType.COMMAND, CommandManager.getCommandNames(CommandType.TYPE_GLOBAL)); this.autochannels = autochannels; this.parserFactory = factory; new Timer("Server Who Timer").schedule(new TimerTask() { @Override public void run() { for (Channel channel : channels.values()) { channel.checkWho(); } } }, 0, getConfigManager().getOptionInt(DOMAIN_GENERAL, "whotime", 60000)); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "showrawwindow", false)) { addRaw(); } connect(server, port, password, ssl, profile); } /** * Connects to a new server with the specified details. * * @param server The hostname/ip of the server to connect to * @param port The port to connect to * @param password The server password * @param ssl Whether to use SSL or not * @param profile The profile to use */ @Precondition({ "The IRC Parser is null or not connected", "The specified profile is not null" }) public void connect(final String server, final int port, final String password, final boolean ssl, final Identity profile) { assert profile != null; synchronized (this) { switch (myState.getState()) { case RECONNECT_WAIT: reconnectTimer.cancel(); break; case CLOSING: // Ignore the connection attempt return; case CONNECTED: case CONNECTING: disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); break; case DISCONNECTING: addLine("serverDisconnecting"); break; default: // Do nothing break; } if (parser != null && parser.getSocketState() == IRCParser.STATE_OPEN) { throw new IllegalArgumentException("Connection attempt while parser " + "is still connected.\n\nMy state:" + myState); } myState.transition(ServerState.CONNECTING); ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this); getConfigManager().migrate("", "", server); serverInfo = new ServerInfo(server, port, password); serverInfo.setSSL(ssl); if (getConfigManager().hasOption(DOMAIN_SERVER, "proxy.address")) { serverInfo.setUseSocks(true); serverInfo.setProxyHost(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.address")); serverInfo.setProxyUser(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.user", "")); serverInfo.setProxyPass(getConfigManager() .getOption(DOMAIN_SERVER, "proxy.password", "")); serverInfo.setProxyPort(getConfigManager() .getOptionInt(DOMAIN_SERVER, "proxy.port", 1080)); } this.profile = profile; updateIcon(); addLine("serverConnecting", server, port); final MyInfo myInfo = getMyInfo(); CertificateManager certManager = new CertificateManager(server, getConfigManager()); parser = parserFactory.getParser(myInfo, serverInfo); parser.setTrustManager(new TrustManager[]{certManager}); parser.setKeyManagers(certManager.getKeyManager()); parser.setRemoveAfterCallback(true); parser.setCreateFake(true); parser.setIgnoreList(ignoreList); if (getConfigManager().hasOption(DOMAIN_GENERAL, "bindip")) { parser.setBindIP(getConfigManager().getOption(DOMAIN_GENERAL, "bindip")); } doCallbacks(); awayMessage = null; removeInvites(); window.setAwayIndicator(false); try { new Thread(parser, "IRC Parser thread").start(); } catch (IllegalThreadStateException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex); } } } /** * Reconnects to the IRC server with a specified reason. * * @param reason The quit reason to send */ public void reconnect(final String reason) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { return; } disconnect(reason); connect(serverInfo.getHost(), serverInfo.getPort(), serverInfo.getPassword(), serverInfo.getSSL(), profile); } } /** * Reconnects to the IRC server. */ public void reconnect() { reconnect(getConfigManager().getOption(DOMAIN_GENERAL, "reconnectmessage")); } /** * Disconnects from the server with the default quit message. */ public void disconnect() { disconnect(getConfigManager().getOption(DOMAIN_GENERAL, "quitmessage")); } /** * Disconnects from the server. * * @param reason disconnect reason */ public void disconnect(final String reason) { synchronized (this) { switch (myState.getState()) { case CLOSING: case DISCONNECTED: case TRANSIENTLY_DISCONNECTED: return; case RECONNECT_WAIT: reconnectTimer.cancel(); break; default: break; } if (parser == null) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.DISCONNECTING); removeInvites(); updateIcon(); parser.disconnect(reason); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsonquit", false)) { closeChannels(); } else { clearChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesonquit", false)) { closeQueries(); } } } /** * Schedules a reconnect attempt to be performed after a user-defiend delay. */ @Precondition("The server state is transiently disconnected") private void doDelayedReconnect() { synchronized (this) { if (myState.getState() != ServerState.TRANSIENTLY_DISCONNECTED) { throw new IllegalStateException("doDelayedReconnect when not " + "transiently disconnected\n\nState: " + myState); } final int delay = Math.max(1000, getConfigManager().getOptionInt(DOMAIN_GENERAL, "reconnectdelay", 5000)); handleNotification("connectRetry", getName(), delay / 1000); reconnectTimer = new Timer("Server Reconnect Timer"); reconnectTimer.schedule(new TimerTask() { @Override public void run() { synchronized (Server.this) { if (myState.getState() == ServerState.RECONNECT_WAIT) { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); reconnect(); } } } }, delay); myState.transition(ServerState.RECONNECT_WAIT); updateIcon(); } } /** * Determines whether the server knows of the specified channel. * * @param channel The channel to be checked * @return True iff the channel is known, false otherwise */ public boolean hasChannel(final String channel) { return channels.containsKey(converter.toLowerCase(channel)); } /** * Retrieves the specified channel belonging to this server. * * @param channel The channel to be retrieved * @return The appropriate channel object */ public Channel getChannel(final String channel) { return channels.get(converter.toLowerCase(channel)); } /** * Retrieves a list of channel names belonging to this server. * * @return list of channel names belonging to this server */ public List<String> getChannels() { final ArrayList<String> res = new ArrayList<String>(); for (String channel : channels.keySet()) { res.add(channel); } return res; } /** * Determines whether the server knows of the specified query. * * @param host The host of the query to look for * @return True iff the query is known, false otherwise */ public boolean hasQuery(final String host) { final String nick = ClientInfo.parseHost(host); for (Query query : queries) { if (converter.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) { return true; } } return false; } /** * Retrieves the specified query belonging to this server. * * @param host The host of the query to look for * @return The appropriate query object */ public Query getQuery(final String host) { final String nick = ClientInfo.parseHost(host); for (Query query : queries) { if (converter.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) { return query; } } throw new IllegalArgumentException("No such query: " + host); } /** * Retrieves a list of queries belonging to this server. * * @return list of queries belonging to this server */ public List<Query> getQueries() { return new ArrayList<Query>(queries); } /** * Adds a raw window to this server. */ public void addRaw() { if (raw == null) { raw = new Raw(this); if (parser != null) { raw.registerCallbacks(); } } else { raw.activateFrame(); } } /** * Retrieves the raw window associated with this server. * * @return The raw window associated with this server. */ public Raw getRaw() { return raw; } /** * Removes our reference to the raw object (presumably after it has been * closed). */ public void delRaw() { raw = null; //NOPMD } /** * Removes a specific channel and window from this server. * * @param chan channel to remove */ public void delChannel(final String chan) { tabCompleter.removeEntry(TabCompletionType.CHANNEL, chan); channels.remove(converter.toLowerCase(chan)); } /** * Adds a specific channel and window to this server. * * @param chan channel to add */ public void addChannel(final ChannelInfo chan) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { // Can't join channels while the server is closing return; } } if (hasChannel(chan.getName())) { getChannel(chan.getName()).setChannelInfo(chan); getChannel(chan.getName()).selfJoin(); } else { final Channel newChan = new Channel(this, chan); tabCompleter.addEntry(TabCompletionType.CHANNEL, chan.getName()); channels.put(converter.toLowerCase(chan.getName()), newChan); newChan.show(); } } /** * Adds a query to this server. * * @param host host of the remote client being queried */ public void addQuery(final String host) { synchronized (this) { if (myState.getState() == ServerState.CLOSING) { // Can't open queries while the server is closing return; } } if (!hasQuery(host)) { final Query newQuery = new Query(this, host); tabCompleter.addEntry(TabCompletionType.QUERY_NICK, ClientInfo.parseHost(host)); queries.add(newQuery); } } /** * Deletes a query from this server. * * @param query The query that should be removed. */ public void delQuery(final Query query) { tabCompleter.removeEntry(TabCompletionType.QUERY_NICK, query.getNickname()); queries.remove(query); } /** {@inheritDoc} */ @Override public boolean ownsFrame(final Window target) { // Check if it's our server frame if (window != null && window.equals(target)) { return true; } // Check if it's the raw frame if (raw != null && raw.ownsFrame(target)) { return true; } // Check if it's a channel frame for (Channel channel : channels.values()) { if (channel.ownsFrame(target)) { return true; } } // Check if it's a query frame for (Query query : queries) { if (query.ownsFrame(target)) { return true; } } return false; } /** * Sets the specified frame as the most-recently activated. * * @param source The frame that was activated */ public void setActiveFrame(final FrameContainer source) { activeFrame = source; } /** * Retrieves a list of all children of this server instance. * * @return A list of this server's children */ public List<WritableFrameContainer> getChildren() { final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>(); if (raw != null) { res.add(raw); } res.addAll(channels.values()); res.addAll(queries); return res; } /** * Updates this server's icon. */ private void updateIcon() { final String icon = myState.getState() == ServerState.CONNECTED ? serverInfo.getSSL() ? "secure-server" : "server" : "server-disconnected"; setIcon(icon); } /** * Retrieves the MyInfo object used for the IRC Parser. * * @return The MyInfo object for our profile */ @Precondition("The current profile is not null") private MyInfo getMyInfo() { assert profile != null; final MyInfo myInfo = new MyInfo(); myInfo.setNickname(profile.getOption(DOMAIN_PROFILE, "nickname")); myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname")); if (profile.hasOption(DOMAIN_PROFILE, "ident")) { myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident")); } return myInfo; } /** * Registers callbacks. */ private void doCallbacks() { if (raw != null) { raw.registerCallbacks(); } eventHandler.registerCallbacks(); for (Query query : queries) { query.reregister(); } } /** * Joins the specified channel, or adds it to the auto-join list if the * server is not connected. * * @param channel The channel to be joined */ public void join(final String channel) { synchronized (this) { if (myState.getState() == ServerState.CONNECTED) { removeInvites(channel); if (hasChannel(channel)) { getChannel(channel).join(); getChannel(channel).activateFrame(); } else { parser.joinChannel(channel); } } else { autochannels.add(channel); } } } /** {@inheritDoc} */ @Override public void sendLine(final String line) { synchronized (this) { if (parser != null && myState.getState() == ServerState.CONNECTED) { parser.sendLine(window.getTranscoder().encode(line)); } } } /** {@inheritDoc} */ @Override public int getMaxLineLength() { return IRCParser.MAX_LINELENGTH; } /** * Retrieves the parser used for this connection. * * @return IRCParser this connection's parser */ public IRCParser getParser() { return parser; } /** * Retrieves the profile that's in use for this server. * * @return The profile in use by this server */ public Identity getProfile() { return profile; } /** * Retrieves the name of this server. * * @return The name of this server */ public String getName() { return serverInfo.getHost(); } /** * Retrieves the name of this server's network. The network name is * determined using the following rules: * * 1. If the server includes its network name in the 005 information, we * use that * 2. If the server's name ends in biz, com, info, net or org, we use the * second level domain (e.g., foo.com) * 3. If the server's name contains more than two dots, we drop everything * up to and including the first part, and use the remainder * 4. In all other cases, we use the full server name * * @return The name of this server's network */ public String getNetwork() { if (parser == null) { throw new IllegalStateException("getNetwork called when " + "parser is null"); } else if (parser.getNetworkName().isEmpty()) { return getNetworkFromServerName(parser.getServerName()); } else { return parser.getNetworkName(); } } /** * Calculates a network name from the specified server name. This method * implements parts 2-4 of the procedure documented at getNetwork(). * * @param serverName The server name to parse * @return A network name for the specified server */ protected static String getNetworkFromServerName(final String serverName) { final String[] parts = serverName.split("\\."); final String[] tlds = {"biz", "com", "info", "net", "org"}; boolean isTLD = false; for (String tld : tlds) { if (serverName.endsWith("." + tld)) { isTLD = true; } } if (isTLD && parts.length > 2) { return parts[parts.length - 2] + "." + parts[parts.length - 1]; } else if (parts.length > 2) { final StringBuilder network = new StringBuilder(); for (int i = 1; i < parts.length; i++) { if (network.length() > 0) { network.append('.'); } network.append(parts[i]); } return network.toString(); } else { return serverName; } } /** * Retrieves the name of this server's IRCd. * * @return The name of this server's IRCd */ public String getIrcd() { return parser.getIRCD(true); } /** * Returns the current away status. * * @return True if the client is marked as away, false otherwise */ public boolean isAway() { return awayMessage != null; } /** * Gets the current away message. * * @return Null if the client isn't away, or a textual away message if it is */ public String getAwayMessage() { return awayMessage; } /** * Returns the tab completer for this connection. * * @return The tab completer for this server */ public TabCompleter getTabCompleter() { return tabCompleter; } /** {@inheritDoc} */ @Override public InputWindow getFrame() { return window; } /** * Retrieves the current state for this server. * * @return This server's state */ public ServerState getState() { return myState.getState(); } /** * Retrieves the status object for this server. Effecting state transitions * on the object returned by this method will almost certainly cause * problems. * * @since 0.6.3 * @return This server's status object. */ public ServerStatus getStatus() { return myState; } /** {@inheritDoc} */ @Override public void windowClosing() { synchronized (this) { // 1: Make the window non-visible window.setVisible(false); // 2: Remove any callbacks or listeners eventHandler.unregisterCallbacks(); // 3: Trigger any actions neccessary if (parser != null && parser.isReady()) { disconnect(); } myState.transition(ServerState.CLOSING); closeChannels(); closeQueries(); removeInvites(); if (raw != null) { raw.close(); } // 4: Trigger action for the window closing // 5: Inform any parents that the window is closing ServerManager.getServerManager().unregisterServer(this); // 6: Remove the window from the window manager WindowManager.removeWindow(window); // 7: Remove any references to the window and parents window = null; //NOPMD parser = null; //NOPMD } } /** * Closes all open channel windows associated with this server. */ private void closeChannels() { for (Channel channel : new ArrayList<Channel>(channels.values())) { channel.close(); } } /** * Clears the nicklist of all open channels. */ private void clearChannels() { for (Channel channel : channels.values()) { channel.resetWindow(); } } /** * Closes all open query windows associated with this server. */ private void closeQueries() { for (Query query : new ArrayList<Query>(queries)) { query.close(); } } /** * Passes the arguments to the most recently activated frame for this * server. If the frame isn't know, or isn't visible, use this frame * instead. * * @param messageType The type of message to send * @param args The arguments for the message */ public void addLineToActive(final String messageType, final Object... args) { if (activeFrame == null || !activeFrame.getFrame().isVisible()) { activeFrame = this; } activeFrame.getFrame().addLine(messageType, args); } /** * Passes the arguments to all frames for this server. * * @param messageType The type of message to send * @param args The arguments of the message */ public void addLineToAll(final String messageType, final Object... args) { for (Channel channel : channels.values()) { channel.getFrame().addLine(messageType, args); } for (Query query : queries) { query.getFrame().addLine(messageType, args); } addLine(messageType, args); } /** * Replies to an incoming CTCP message. * * @param source The source of the message * @param type The CTCP type * @param args The CTCP arguments */ public void sendCTCPReply(final String source, final String type, final String args) { if (type.equalsIgnoreCase("VERSION")) { parser.sendCTCPReply(source, "VERSION", "DMDirc " + Main.VERSION + " - http: } else if (type.equalsIgnoreCase("PING")) { parser.sendCTCPReply(source, "PING", args); } else if (type.equalsIgnoreCase("CLIENTINFO")) { parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO"); } } /** * Determines if the specified channel name is valid. A channel name is * valid if we already have an existing Channel with the same name, or * we have a valid parser instance and the parser says it's valid. * * @param channelName The name of the channel to test * @return True if the channel name is valid, false otherwise */ public boolean isValidChannelName(final String channelName) { return hasChannel(channelName) || (parser != null && parser.isValidChannelName(channelName)); } /** * Returns this server's name. * * @return A string representation of this server (i.e., its name) */ @Override public String toString() { return getName(); } /** * Returns the server instance associated with this frame. * * @return the associated server connection */ @Override public Server getServer() { return this; } /** {@inheritDoc} */ @Override protected boolean processNotificationArg(final Object arg, final List<Object> args) { if (arg instanceof ClientInfo) { final ClientInfo clientInfo = (ClientInfo) arg; args.add(clientInfo.getNickname()); args.add(clientInfo.getIdent()); args.add(clientInfo.getHost()); return true; } else { return super.processNotificationArg(arg, args); } } /** * Retusnt the list of invites for this server. * * @return Invite list */ public List<Invite> getInvites() { return invites; } /** * Called when the server says that the nickname we're trying to use is * already in use. * * @param nickname The nickname that we were trying to use */ public void onNickInUse(final String nickname) { final String lastNick = parser.getMyNickname(); // If our last nick is still valid, ignore the in use message if (!converter.equalsIgnoreCase(lastNick, nickname)) { return; } String newNick = lastNick + (int) (Math.random() * 10); if (profile.hasOption(DOMAIN_PROFILE, "altnicks")) { final String[] alts = profile.getOption(DOMAIN_PROFILE, "altnicks").split("\n"); int offset = 0; if (!converter.equalsIgnoreCase(lastNick, profile.getOption(DOMAIN_PROFILE, "nickname"))) { for (String alt : alts) { offset++; if (converter.equalsIgnoreCase(alt, lastNick)) { break; } } } if (offset < alts.length && !alts[offset].isEmpty()) { newNick = alts[offset]; } } parser.setNickname(newNick); } /** * Called when the server sends a numeric event. * * @param numeric The numeric code for the event * @param tokens The (tokenised) arguments of the event */ public void onNumeric(final int numeric, final String[] tokens) { String snumeric = String.valueOf(numeric); if (numeric < 10) { snumeric = "00" + snumeric; } else if (numeric < 100) { snumeric = "0" + snumeric; } final String withIrcd = "numeric_" + parser.getIRCD(true) + "_" + snumeric; final String sansIrcd = "numeric_" + snumeric; StringBuffer target = null; if (getConfigManager().hasOption("formatter", withIrcd)) { target = new StringBuffer(withIrcd); } else if (getConfigManager().hasOption("formatter", sansIrcd)) { target = new StringBuffer(sansIrcd); } else if (getConfigManager().hasOption("formatter", "numeric_unknown")) { target = new StringBuffer("numeric_unknown"); } ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, target, this, Integer.valueOf(numeric), tokens); if (target != null) { handleNotification(target.toString(), (Object[]) tokens); } } /** * Called when the socket has been closed. */ public void onSocketClosed() { handleNotification("socketClosed", getName()); ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this); eventHandler.unregisterCallbacks(); synchronized (this) { parser = null; if (myState.getState() == ServerState.CLOSING || myState.getState() == ServerState.DISCONNECTED) { // This has been triggered via .disconect() return; } if (myState.getState() == ServerState.DISCONNECTING) { myState.transition(ServerState.DISCONNECTED); } else { myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); } updateIcon(); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect", false)) { closeChannels(); } else { clearChannels(); } if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect", false)) { closeQueries(); } removeInvites(); updateAwayState(null); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect", false) && myState.getState() == ServerState.TRANSIENTLY_DISCONNECTED) { doDelayedReconnect(); } } } /** * Called when an error was encountered while connecting. * * @param errorInfo The parser's error information */ @Precondition("The current server state is CONNECTING") public void onConnectError(final ParserError errorInfo) { synchronized (this) { parser = null; if (myState.getState() == ServerState.CLOSING) { // Do nothing return; } else if (myState.getState() == ServerState.DISCONNECTING) { // Pretend it closed nicely onSocketClosed(); return; } else if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Connect error when not " + "connecting\n\nState: " + myState); } myState.transition(ServerState.TRANSIENTLY_DISCONNECTED); updateIcon(); String description; if (errorInfo.getException() == null) { description = errorInfo.getData(); } else { final Exception exception = errorInfo.getException(); if (exception instanceof java.net.UnknownHostException) { description = "Unknown host (unable to resolve)"; } else if (exception instanceof java.net.NoRouteToHostException) { description = "No route to host"; } else if (exception instanceof java.net.SocketException) { description = exception.getMessage(); } else { Logger.appError(ErrorLevel.LOW, "Unknown socket error", exception); description = "Unknown error: " + exception.getMessage(); } } ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null, this, description); handleNotification("connectError", getName(), description); if (getConfigManager().getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure", false)) { doDelayedReconnect(); } } } /** * Called when we fail to receive a ping reply within a set period of time. */ public void onPingFailed() { Main.getUI().getStatusBar().setMessage("No ping reply from " + getName() + " for over " + ((int) (Math.floor(parser.getPingTime(false) / 1000.0))) + " seconds.", null, 10); ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this, Long.valueOf(parser.getPingTime(false))); if (parser.getPingTime(false) >= getConfigManager().getOptionInt(DOMAIN_SERVER, "pingtimeout", 60000)) { handleNotification("stonedServer", getName()); reconnect(); } } /** * Called after the parser receives the 005 headers from the server. */ @Precondition("State is CONNECTING") public void onPost005() { synchronized (this) { if (myState.getState() != ServerState.CONNECTING) { // Shouldn't happen throw new IllegalStateException("Received onPost005 while not " + "connecting\n\nState: " + myState); } myState.transition(ServerState.CONNECTED); updateIcon(); getConfigManager().migrate(parser.getIRCD(true), getNetwork(), getName()); updateIgnoreList(); converter = parser.getIRCStringConverter(); ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this); if (getConfigManager().hasOption(DOMAIN_GENERAL, "rejoinchannels")) { for (Channel chan : channels.values()) { chan.join(); } } for (String channel : autochannels) { parser.joinChannel(channel); } checkModeAliases(); } } /** * Checks that we have the neccessary mode aliases for this server. */ private void checkModeAliases() { // Check we have mode aliases final String modes = parser.getBoolChanModes() + parser.getListChanModes() + parser.getSetOnlyChanModes() + parser.getSetUnsetChanModes(); final String umodes = parser.getUserModeString(); final StringBuffer missingModes = new StringBuffer(); final StringBuffer missingUmodes = new StringBuffer(); for (char mode : modes.toCharArray()) { if (!getConfigManager().hasOption(DOMAIN_SERVER, "mode" + mode)) { missingModes.append(mode); } } for (char mode : umodes.toCharArray()) { if (!getConfigManager().hasOption(DOMAIN_SERVER, "umode" + mode)) { missingUmodes.append(mode); } } if (missingModes.length() + missingUmodes.length() > 0) { final StringBuffer missing = new StringBuffer("Missing mode aliases: "); if (missingModes.length() > 0) { missing.append("channel: +"); missing.append(missingModes); } if (missingUmodes.length() > 0) { if (missingModes.length() > 0) { missing.append(' '); } missing.append("user: +"); missing.append(missingUmodes); } Logger.appError(ErrorLevel.LOW, missing.toString() + " [" + getNetwork() + "]", new Exception(missing.toString() + "\n" // NOPMD + "Network: " + getNetwork() + "\n" + "IRCd: " + parser.getIRCD(false) + " (" + parser.getIRCD(true) + ")\n" + "Mode alias version: " + getConfigManager().getOption("identity", "modealiasversion", "none") + "\n\n")); } } /** * Retrieves this server's ignore list. * * @return This server's ignore list */ public IgnoreList getIgnoreList() { return ignoreList; } /** * Updates this server's ignore list to use the entries stored in the * config manager. */ public void updateIgnoreList() { ignoreList.clear(); ignoreList.addAll(getConfigManager().getOptionList("network", "ignorelist")); } /** * Saves the contents of our ignore list to the network identity. */ public void saveIgnoreList() { getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList()); } /** * Retrieves the identity for this server. * * @return This server's identity */ public Identity getServerIdentity() { return IdentityManager.getServerConfig(getName()); } /** * Retrieves the identity for this server's network. * * @return This server's network identity */ public Identity getNetworkIdentity() { return IdentityManager.getNetworkConfig(getNetwork()); } /** * Adds an invite listener to this server. * * @param listener The listener to be added */ public void addInviteListener(final InviteListener listener) { listeners.add(InviteListener.class, listener); } /** * Removes an invite listener from this server. * * @param listener The listener to be removed */ public void removeInviteListener(final InviteListener listener) { listeners.remove(InviteListener.class, listener); } /** * Adds an invite to this server, and fires the appropriate listeners. * * @param invite The invite to be added */ public void addInvite(final Invite invite) { synchronized (invites) { for (Invite oldInvite : new ArrayList<Invite>(invites)) { if (oldInvite.getChannel().equals(invite.getChannel())) { removeInvite(oldInvite); } } invites.add(invite); for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteReceived(this, invite); } } } /** * Removes all invites for the specified channel. * * @param channel The channel to remove invites for */ public void removeInvites(final String channel) { for (Invite invite : new ArrayList<Invite>(invites)) { if (invite.getChannel().equals(channel)) { removeInvite(invite); } } } /** * Removes all invites for all channels. */ private void removeInvites() { for (Invite invite : new ArrayList<Invite>(invites)) { removeInvite(invite); } } /** * Removes an invite from this server, and fires the appropriate listeners. * * @param invite The invite to be removed */ public void removeInvite(final Invite invite) { synchronized (invites) { invites.remove(invite); for (InviteListener listener : listeners.get(InviteListener.class)) { listener.inviteExpired(this, invite); } } } /** * Adds an away state lisener to this server. * * @param listener The listener to be added */ public void addAwayStateListener(final AwayStateListener listener) { listeners.add(AwayStateListener.class, listener); } /** * Removes an away state lisener from this server. * * @param listener The listener to be removed */ public void removeAwayStateListener(final AwayStateListener listener) { listeners.remove(AwayStateListener.class, listener); } /** * Updates our away state and fires the relevant listeners. * * @param message The away message to use, or null if we're not away. */ public void updateAwayState(final String message) { if ((awayMessage != null && awayMessage.equals(message)) || (awayMessage == null && message == null)) { return; } awayMessage = message; if (message == null) { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onBack(); } } else { for (AwayStateListener listener : listeners.get(AwayStateListener.class)) { listener.onAway(message); } } } }
package com.arangodb.entity; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import java.util.Map; public class BaseDocument extends BaseEntity implements DocumentHolder { public static final String REV = "_rev"; public static final String KEY = "_key"; /** * the documents revision number */ @SerializedName("_rev") long documentRevision; /** * the document handle */ @SerializedName("_id") String documentHandle; /** * the document key */ @SerializedName("_key") String documentKey; /** * the map containing the key value pairs */ Map<String, Object> properties = new HashMap<String, Object>(); /** * create an empty BaseDocument */ public BaseDocument() { this.init(); } /** * create an empty BaseDocument with a given key * * @param documentKey the unique key of the document */ public BaseDocument(String documentKey) { this.init(); this.documentKey = documentKey; } // /** // * @param keyValues a set of key/value pairs containing the attributes for the document. // * The length has to be even and each even entry has to be of type String. // * If not an empty document will be created // */ // public BaseDocument(Object ...keyValues) { // this(null, keyValues); // /** // * create a BaseDocument with a given key and attributes defined in keyValues // * // * @param documentKey the unique key of the document // * @param keyValues a set of key/value pairs containing the attributes for the document. // * The length has to be even and each even entry has to be of type String. // * If not an empty document will be created // */ // public BaseDocument(String documentKey, Object ...keyValues) { // this.init(); // if (documentKey != null) { // this.documentKey = documentKey; // if (checkKeyValues(keyValues)) { // for (int i = 0; i < keyValues.length; i = i+2) { // if (keyValues[i] == REV) { // this.documentRevision = (Long) keyValues[i+1]; // } else if (keyValues[i] == KEY && documentKey == null) { // this.documentKey = (String) keyValues[i+1]; // } else { // this.addAttribute((String) keyValues[i], keyValues[i + 1]); /** * create an BaseDocument with given attributes * * @param properties the attributes (key/value) of the document to be created */ public BaseDocument(Map<String, Object> properties) { this(null, properties); } /** * create an BaseDocument with given key and attributes * * @param documentKey the unique key of the document * @param properties the attributes (key/value) of the document to be created */ public BaseDocument(String documentKey, Map<String, Object> properties) { this.init(); if (documentKey != null) { this.documentKey = documentKey; } if (properties.containsKey(REV)) { this.documentRevision = (Long) properties.get(REV); properties.remove(REV); } if (properties.containsKey(KEY)) { if (documentKey == null) { this.documentKey = (String) properties.get(KEY); } properties.remove(KEY); } this.properties = properties; } private void init () { //this.properties = new HashMap<String, Object>(); } @Override public long getDocumentRevision() { return this.documentRevision; } @Override public String getDocumentHandle() { return this.documentHandle; } @Override public String getDocumentKey() { return this.documentKey; } @Override public void setDocumentRevision(long documentRevision) { this.documentRevision = documentRevision; } @Override public void setDocumentHandle(String documentHandle) { this.documentHandle = documentHandle; } @Override public void setDocumentKey(String documentKey) { this.documentKey = documentKey; } public Map<String, Object> getProperties() { return properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } /** * add an attribute to the document. If the key already exists, the value of the attribute will be replaced, * * @param key the key of the attribute * @param value the value of the attribute */ public void addAttribute(String key, Object value) { this.properties.put(key, value); } /** * update the value of the attribute with the given key * * @param key the key of the attribute * @param value the value of the attribute ti replace the old value */ public void updateAttribute (String key, Object value) { if (this.properties.containsKey(key)) { this.properties.put(key, value); } } // /** // * check the list if it is suitable // * // * @param keyValues // * @return true, if the list has an even number and is an alternating sequence of instances of String and Object. // */ // private boolean checkKeyValues(Object... keyValues) { // if (keyValues.length %2 != 0) { // return false; // for (int i = 0; i < keyValues.length; i = i+2) { // if (! (keyValues[i] instanceof String)) { // return false; // return true; }
package com.rcv; import java.util.*; public class Tabulator { private List<CastVoteRecord> castVoteRecords; private int contestId; private List<String> contestOptions; private boolean batchElimination = false; static class TieBreak { List<String> contestOptionIds; String selection; TieBreak(List<String> contestOptionIds) { this.contestOptionIds = contestOptionIds; } String getSelection() { if (selection == null) { selection = breakTie(); } return selection; } String nonSelectedString() { ArrayList<String> options = new ArrayList<String>(); for (String contestOptionId : contestOptionIds) { if (!contestOptionId.equals(selection)) { options.add(contestOptionId); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < options.size(); i++) { sb.append(options.get(i)); if (i <= options.size() - 2 && options.size() > 2) { sb.append(", "); } if (i == options.size() - 2) { sb.append(" and "); } } return sb.toString(); } private String breakTie() { // TODO: use java.security.SecureRandom double r = Math.random(); int index = (int)Math.floor(r * (double)contestOptionIds.size()); return contestOptionIds.get(index); } } private Map<Integer, TieBreak> tieBreaks = new HashMap<Integer, TieBreak>(); public Tabulator( List<CastVoteRecord> castVoteRecords, int contestId, List<String> contestOptions, Boolean batchElimination ) { this.castVoteRecords = castVoteRecords; this.contestId = contestId; this.contestOptions = contestOptions; this.batchElimination = batchElimination; } public void tabulate() { RCVLogger.log("Beginning tabulation for contest:%d", this.contestId); RCVLogger.log("there are %d candidates for this contest:", this.contestOptions.size()); for (String option : this.contestOptions) { RCVLogger.log("%s", option); } RCVLogger.log("there are %d cast vote records for this contest", this.castVoteRecords.size()); // roundTallies is a map of round # --> a map of candidate ID -> vote totals for that round Map<Integer, Map<String, Integer>> roundTallies = new HashMap<Integer, Map<String, Integer>>(); // eliminatedRound object is a map of candidate IDs to the round in which they were eliminated Map<String, Integer> eliminatedRound = new HashMap<String, Integer>(); int round = 1; String winner; List<SortedMap<Integer, Set<String>>> sortedRankings = sortCastVoteRecords(castVoteRecords); // loop until we achieve a majority winner: // at each iteration we will eliminate the lowest-total candidate OR multiple losing candidates if using batch // elimination logic (Maine rules) while (true) { RCVLogger.log("Round: %d", round); // roundTally is map of candidate ID to vote tallies // generated based on previously eliminated candidates contained in eliminatedRound object // at each iteration of this loop, the eliminatedRound object will get more entries as candidates are eliminated // conversely the roundTally object returned here will contain fewer entries each of which will have more votes // eventually a winner will be chosen Map<String, Integer> roundTally = getRoundTally(sortedRankings, eliminatedRound); roundTallies.put(round, roundTally); // We fully sort the list in case we want to run batch elimination. int totalVotes = 0; // map of vote tally to candidate(s). A list is used to handle ties. SortedMap<Integer, LinkedList<String>> countToCandidates = new TreeMap<Integer, LinkedList<String>>(); // for each candidate record their vote total into the countTOCandidates object for (String contestOptionId : roundTally.keySet()) { int votes = roundTally.get(contestOptionId); RCVLogger.log("candidate %s got %d votes", contestOptionId, votes); // count the total votes cast in this round totalVotes += votes; LinkedList<String> candidates = countToCandidates.get(votes); if (candidates == null) { candidates = new LinkedList<String>(); countToCandidates.put(votes, candidates); } candidates.add(contestOptionId); } RCVLogger.log("Total votes in round %d:%d", round , totalVotes); int maxVotes = countToCandidates.lastKey(); // Does the leader have a majority of non-exhausted ballots? if (maxVotes > (float)totalVotes / 2.0) { winner = countToCandidates.get(maxVotes).getFirst(); RCVLogger.log( winner + " won in round %d with %d votes",round , maxVotes); break; } // container for eliminated candidate(s) List<String> eliminated = new LinkedList<String>(); if (batchElimination) { eliminated.addAll(runBatchElimination(round, countToCandidates)); } // If batch elimination caught anyone, don't apply regular elimination logic on this iteration. // Otherwise, eliminate last place, breaking tie if necessary. if (eliminated.isEmpty()) { String loser; int minVotes = countToCandidates.firstKey(); LinkedList<String> lastPlace = countToCandidates.get(minVotes); if (lastPlace.size() > 1) { TieBreak tieBreak = new TieBreak(lastPlace); loser = tieBreak.getSelection(); tieBreaks.put(round, tieBreak); RCVLogger.log( loser + " lost a tie-breaker in round " + round + " against " + tieBreak.nonSelectedString() + ". Each candidate had " + minVotes + " vote(s)." ); } else { loser = lastPlace.getFirst(); RCVLogger.log(loser + " was eliminated in round " + round + " with " + minVotes + " vote(s)."); } eliminated.add(loser); } for (String loser : eliminated) { eliminatedRound.put(loser, round); } round++; } } private void log(String s) { RCVLogger.log(s); } private List<String> runBatchElimination(int round, SortedMap<Integer, LinkedList<String>> countToCandidates) { int runningTotal = 0; List<String> candidatesSeen = new LinkedList<String>(); List<String> eliminated = new LinkedList<String>(); for (int currentVoteCount : countToCandidates.keySet()) { if (runningTotal < currentVoteCount) { eliminated.addAll(candidatesSeen); for (String candidate : candidatesSeen) { log( "Batch-eliminated " + candidate + " in round " + round + ". The running total was " + runningTotal + " vote(s) and the next-highest count was " + currentVoteCount + " vote(s)." ); } } List<String> currentCandidates = countToCandidates.get(currentVoteCount); runningTotal += currentVoteCount * currentCandidates.size(); candidatesSeen.addAll(currentCandidates); } return eliminated; } // roundTally returns a map of candidate ID to vote tallies // generated based on previously eliminated candidates contained in eliminatedRound object // at each iteration of this loop, the eliminatedRound object will get more entries as candidates are eliminated // conversely the roundTally object returned here will contain fewer entries each of which will have more votes // eventually a winner will be chosen private Map<String, Integer> getRoundTally( List<SortedMap<Integer, Set<String>>> allSortedRankings, Map<String, Integer> eliminatedRound ) { Map<String, Integer> roundTally = new HashMap<String, Integer>(); // if a candidate has already been eliminated they get 0 votes for (String contestOptionId : contestOptions) { if (eliminatedRound.get(contestOptionId) == null) { roundTally.put(contestOptionId, 0); } } // count first-place votes, considering only non-eliminated options for (SortedMap<Integer, Set<String>> rankings : allSortedRankings) { for (int rank : rankings.keySet()) { Set<String> contestOptionIds = rankings.get(rank); if (contestOptionIds.size() > 1) { System.out.println("Overvote!"); continue; } String contestOptionId = contestOptionIds.iterator().next(); if (eliminatedRound.get(contestOptionId) == null) { // found a continuing candidate so increase their tally by 1 roundTally.put(contestOptionId, roundTally.get(contestOptionId) + 1); break; } } } return roundTally; } // input is a list of CastVoteRecords private List<SortedMap<Integer, Set<String>>> sortCastVoteRecords(List<CastVoteRecord> castVoteRecords) { // returns a list of "sortedCVRs" List<SortedMap<Integer, Set<String>>> allSortedRankings = new LinkedList<SortedMap<Integer, Set<String>>>(); // for each input CVR see what rankings were given for the contest of interest for (CastVoteRecord cvr : castVoteRecords) { // sortedCVR will contain the rankings for the contest of interest in order from low to high // note: we use a set<Integer> here because there may be overvotes with different candidates getting // the same ranking, for example ranking 3 could map to candidates 1 and 2 SortedMap<Integer, Set<String>> sortedCVR = new TreeMap<Integer, Set<String>>(); for (ContestRanking ranking : cvr.getRankingsForContest(contestId)) { // set of candidates given this rank Set<String> optionsAtRank = sortedCVR.get(ranking.getRank()); if (optionsAtRank == null) { // create the new optionsAtRank and add to the sorted cvr optionsAtRank = new HashSet<String>(); sortedCVR.put(ranking.getRank(), optionsAtRank); } // add this option into the map optionsAtRank.add(ranking.getOptionId()); } allSortedRankings.add(sortedCVR); } return allSortedRankings; } }
package mho.qbar.objects; import mho.qbar.iterableProviders.QBarIterableProvider; import mho.qbar.testing.QBarTestProperties; import mho.wheels.io.Readers; import mho.wheels.math.BinaryFraction; import mho.wheels.math.MathUtils; import mho.wheels.numberUtils.BigDecimalUtils; import mho.wheels.numberUtils.IntegerUtils; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import static mho.qbar.objects.Rational.*; import static mho.qbar.objects.Rational.sum; import static mho.qbar.testing.QBarTesting.*; import static mho.qbar.testing.QBarTesting.propertiesCompareToHelper; import static mho.qbar.testing.QBarTesting.propertiesEqualsHelper; import static mho.qbar.testing.QBarTesting.propertiesHashCodeHelper; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.numberUtils.FloatingPointUtils.*; import static mho.wheels.ordering.Ordering.*; import static mho.wheels.testing.Testing.*; public class RationalProperties extends QBarTestProperties { private static final @NotNull String RATIONAL_CHARS = "-/0123456789"; private static final BigInteger ASCII_ALPHANUMERIC_COUNT = BigInteger.valueOf(36); public RationalProperties() { super("Rational"); } @Override protected void testConstant() { propertiesConstants(); } @Override protected void testBothModes() { propertiesGetNumerator(); propertiesGetDenominator(); propertiesOf_BigInteger_BigInteger(); propertiesOf_long_long(); propertiesOf_int_int(); propertiesOf_BigInteger(); propertiesOf_long(); propertiesOf_int(); propertiesOf_BinaryFraction(); propertiesOf_float(); propertiesOf_double(); propertiesOfExact_float(); propertiesOfExact_double(); propertiesOf_BigDecimal(); propertiesIsInteger(); propertiesBigIntegerValue_RoundingMode(); propertiesBigIntegerValue(); propertiesFloor(); propertiesCeiling(); propertiesBigIntegerValueExact(); propertiesByteValueExact(); propertiesShortValueExact(); propertiesIntValueExact(); propertiesLongValueExact(); propertiesIsPowerOfTwo(); propertiesIsBinaryFraction(); propertiesBinaryFractionValueExact(); propertiesBinaryExponent(); compareImplementationsBinaryExponent(); propertiesIsEqualToFloat(); compareImplementationsIsEqualToFloat(); propertiesIsEqualToDouble(); compareImplementationsIsEqualToDouble(); propertiesIsEqualToDouble(); propertiesFloatValue_RoundingMode(); propertiesFloatValue(); propertiesFloatValueExact(); propertiesDoubleValue_RoundingMode(); propertiesDoubleValue(); propertiesDoubleValueExact(); propertiesHasTerminatingBaseExpansion(); propertiesBigDecimalValueByPrecision_int_RoundingMode(); propertiesBigDecimalValueByScale_int_RoundingMode(); propertiesBigDecimalValueByPrecision_int(); propertiesBigDecimalValueByScale_int(); propertiesBigDecimalValueExact(); propertiesBitLength(); propertiesAdd(); compareImplementationsAdd(); propertiesNegate(); propertiesAbs(); propertiesSignum(); propertiesSubtract(); compareImplementationsSubtract(); propertiesMultiply_Rational(); compareImplementationsMultiply_Rational(); propertiesMultiply_BigInteger(); compareImplementationsMultiply_BigInteger(); propertiesMultiply_int(); compareImplementationsMultiply_int(); propertiesInvert(); compareImplementationsInvert(); propertiesDivide_Rational(); compareImplementationsDivide_Rational(); propertiesDivide_BigInteger(); compareImplementationsDivide_BigInteger(); propertiesDivide_int(); compareImplementationsDivide_int(); propertiesShiftLeft(); compareImplementationsShiftLeft(); propertiesShiftRight(); compareImplementationsShiftRight(); propertiesSum(); compareImplementationsSum(); propertiesProduct(); compareImplementationsProduct(); propertiesDelta(); propertiesHarmonicNumber(); propertiesPow(); compareImplementationsPow(); propertiesFractionalPart(); propertiesRoundToDenominator(); propertiesContinuedFraction(); propertiesFromContinuedFraction(); propertiesConvergents(); propertiesPositionalNotation(); propertiesFromPositionalNotation(); propertiesDigits(); compareImplementationsDigits(); propertiesToStringBase_BigInteger(); propertiesToStringBase_BigInteger_int(); propertiesFromStringBase(); propertiesCancelDenominators(); propertiesEquals(); propertiesHashCode(); propertiesCompareTo(); compareImplementationsCompareTo(); propertiesRead(); propertiesFindIn(); propertiesToString(); } private void propertiesConstants() { initializeConstant("constants"); List<Rational> sample = toList(take(MEDIUM_LIMIT, HARMONIC_NUMBERS)); sample.forEach(Rational::validate); assertTrue("HARMONIC_NUMBERS", unique(sample)); assertTrue("HARMONIC_NUMBERS", increasing(sample)); assertTrue("HARMONIC_NUMBERS", all(r -> !r.isInteger(), tail(sample))); try { HARMONIC_NUMBERS.iterator().remove(); fail("HARMONIC_NUMBERS"); } catch (UnsupportedOperationException ignored) {} } private void propertiesGetNumerator() { initialize("getNumerator()"); for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, of(r.getNumerator(), r.getDenominator()), r); } } private void propertiesGetDenominator() { initialize("getDenominator()"); for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, r.getDenominator().signum(), 1); } } private void propertiesOf_BigInteger_BigInteger() { initialize("of(BigInteger, BigInteger)"); for (Pair<BigInteger, BigInteger> p : take(LIMIT, P.pairs(P.bigIntegers(), P.nonzeroBigIntegers()))) { Rational r = of(p.a, p.b); r.validate(); assertEquals(p, of(p.a).divide(p.b), r); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { try { of(i, BigInteger.ZERO); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesOf_long_long() { initialize("of(long, long)"); BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE); BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE); for (Pair<Long, Long> p : take(LIMIT, P.pairs(P.longs(), P.nonzeroLongs()))) { Rational r = of(p.a, p.b); r.validate(); assertEquals(p, of(p.a).divide(BigInteger.valueOf(p.b)), r); assertTrue(p, ge(r.getNumerator(), minLong)); assertTrue(p, le(r.getNumerator(), maxLong)); assertTrue(p, ge(r.getDenominator(), minLong)); assertTrue(p, le(r.getDenominator(), maxLong)); } for (long l : take(LIMIT, P.longs())) { try { of(l, 0L); fail(l); } catch (ArithmeticException ignored) {} } } private void propertiesOf_int_int() { initialize("of(int, int)"); BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE); BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE); for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.integers(), P.nonzeroIntegers()))) { Rational r = of(p.a, p.b); r.validate(); assertEquals(p, of(p.a).divide(p.b), r); assertTrue(p, ge(r.getNumerator(), minInt)); assertTrue(p, le(r.getNumerator(), maxInt)); assertTrue(p, ge(r.getDenominator(), minInt)); assertTrue(p, le(r.getDenominator(), maxInt)); } for (int i : take(LIMIT, P.integers())) { try { of(i, 0); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesOf_BigInteger() { initialize("of(BigInteger)"); for (BigInteger i : take(LIMIT, P.bigIntegers())) { Rational r = of(i); r.validate(); assertEquals(i, r.getDenominator(), BigInteger.ONE); inverses(Rational::of, Rational::bigIntegerValueExact, i); } } private void propertiesOf_long() { initialize("of(long)"); for (long l : take(LIMIT, P.longs())) { Rational r = of(l); r.validate(); assertEquals(l, r.getDenominator(), BigInteger.ONE); assertTrue(l, ge(r.getNumerator(), BigInteger.valueOf(Long.MIN_VALUE))); assertTrue(l, le(r.getNumerator(), BigInteger.valueOf(Long.MAX_VALUE))); inverses(Rational::of, Rational::longValueExact, l); } } private void propertiesOf_int() { initialize("of(int)"); for (int i : take(LIMIT, P.integers())) { Rational r = of(i); r.validate(); assertEquals(i, r.getDenominator(), BigInteger.ONE); assertTrue(i, ge(r.getNumerator(), BigInteger.valueOf(Integer.MIN_VALUE))); assertTrue(i, le(r.getNumerator(), BigInteger.valueOf(Integer.MAX_VALUE))); inverses(Rational::of, Rational::intValueExact, i); } } private void propertiesOf_BinaryFraction() { initialize("of(BinaryFraction)"); for (BinaryFraction bf : take(LIMIT, P.binaryFractions())) { Rational r = of(bf); r.validate(); assertEquals(bf, of(bf.getMantissa()).multiply(ONE.shiftLeft(bf.getExponent())), r); assertTrue(bf, IntegerUtils.isPowerOfTwo(r.getDenominator())); inverses(Rational::of, Rational::binaryFractionValueExact, bf); } } private void propertiesOf_float() { initialize("of(float)"); for (float f : take(LIMIT, filter(Float::isFinite, P.floats()))) { Rational r = of(f).get(); r.validate(); assertTrue(f, r.hasTerminatingBaseExpansion(BigInteger.TEN)); } for (float f : take(LIMIT, filter(g -> Float.isFinite(g) && !isNegativeZero(g), P.floats()))) { Rational r = of(f).get(); aeqf(f, f, r.floatValue()); assertTrue(f, eq(new BigDecimal(Float.toString(f)), r.bigDecimalValueExact())); } } private void propertiesOf_double() { initialize("of(double)"); for (double d : take(LIMIT, filter(Double::isFinite, P.doubles()))) { Rational r = of(d).get(); r.validate(); assertTrue(d, r.hasTerminatingBaseExpansion(BigInteger.TEN)); } for (double d : take(LIMIT, filter(e -> Double.isFinite(e) && !isNegativeZero(e), P.doubles()))) { Rational r = of(d).get(); aeqd(d, d, r.doubleValue()); assertTrue(d, eq(new BigDecimal(Double.toString(d)), r.bigDecimalValueExact())); } } private void propertiesOfExact_float() { initialize("ofExact(float)"); for (float f : take(LIMIT, P.floats())) { Optional<Rational> or = ofExact(f); assertEquals(f, Float.isFinite(f), or.isPresent()); } for (float f : take(LIMIT, filter(g -> Float.isFinite(g) && !isNegativeZero(g), P.floats()))) { inverses(g -> ofExact(g).get(), Rational::floatValueExact, f); } int x = 1 << (FLOAT_EXPONENT_WIDTH - 1); BigInteger y = BigInteger.ONE.shiftLeft(-MIN_SUBNORMAL_FLOAT_EXPONENT); BigInteger z = BigInteger.ONE.shiftLeft(x).subtract(BigInteger.ONE.shiftLeft(x - FLOAT_FRACTION_WIDTH - 1)); for (float f : take(LIMIT, filter(Float::isFinite, P.floats()))) { Rational r = ofExact(f).get(); r.validate(); assertTrue(f, IntegerUtils.isPowerOfTwo(r.getDenominator())); assertTrue(f, le(r.getDenominator(), y)); assertTrue(f, le(r.getNumerator(), z)); } for (float f : take(LIMIT, filter(g -> Float.isFinite(g) && !isNegativeZero(g), P.floats()))) { Rational r = ofExact(f).get(); aeqf(f, f, r.floatValue()); } } private void propertiesOfExact_double() { initialize("ofExact(double)"); for (double d : take(LIMIT, P.doubles())) { Optional<Rational> or = ofExact(d); assertEquals(d, Double.isFinite(d), or.isPresent()); } for (double d : take(LIMIT, filter(e -> Double.isFinite(e) && !isNegativeZero(e), P.doubles()))) { inverses(e -> ofExact(e).get(), Rational::doubleValueExact, d); } int x = 1 << (DOUBLE_EXPONENT_WIDTH - 1); BigInteger y = BigInteger.ONE.shiftLeft(-MIN_SUBNORMAL_DOUBLE_EXPONENT); BigInteger z = BigInteger.ONE.shiftLeft(x).subtract(BigInteger.ONE.shiftLeft(x - DOUBLE_FRACTION_WIDTH - 1)); for (double d : take(LIMIT, filter(Double::isFinite, P.doubles()))) { Rational r = ofExact(d).get(); r.validate(); assertTrue(d, IntegerUtils.isPowerOfTwo(r.getDenominator())); assertTrue(d, le(r.getDenominator(), y)); assertTrue(d, le(r.getNumerator(), z)); } for (double d : take(LIMIT, filter(e -> Double.isFinite(e) && !isNegativeZero(e), P.doubles()))) { Rational r = ofExact(d).get(); aeqd(d, d, r.doubleValue()); } } private void propertiesOf_BigDecimal() { initialize("of(BigDecimal)"); for (BigDecimal bd : take(LIMIT, P.bigDecimals())) { Rational r = of(bd); r.validate(); assertTrue(bd, eq(bd, r.bigDecimalValueExact())); assertTrue(bd, r.hasTerminatingBaseExpansion(BigInteger.TEN)); } for (BigDecimal bd : take(LIMIT, P.canonicalBigDecimals())) { inverses(Rational::of, Rational::bigDecimalValueExact, bd); } } private void propertiesIsInteger() { initialize("isInteger()"); for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, r.isInteger(), of(r.floor()).equals(r)); homomorphic(Rational::negate, Function.identity(), Rational::isInteger, Rational::isInteger, r); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertTrue(i, of(i).isInteger()); } } private void propertiesBigIntegerValue_RoundingMode() { initialize("bigIntegerValue(RoundingMode)"); Iterable<Pair<Rational, RoundingMode>> ps = filterInfinite( p -> p.b != RoundingMode.UNNECESSARY || p.a.isInteger(), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { BigInteger rounded = p.a.bigIntegerValue(p.b); assertTrue(p, rounded.equals(BigInteger.ZERO) || rounded.signum() == p.a.signum()); assertTrue(p, lt(p.a.subtract(of(rounded)).abs(), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i, of(i).bigIntegerValue(RoundingMode.UNNECESSARY), i); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, r.bigIntegerValue(RoundingMode.FLOOR), r.floor()); assertEquals(r, r.bigIntegerValue(RoundingMode.CEILING), r.ceiling()); assertTrue(r, le(of(r.bigIntegerValue(RoundingMode.DOWN)).abs(), r.abs())); assertTrue(r, ge(of(r.bigIntegerValue(RoundingMode.UP)).abs(), r.abs())); assertTrue(r, le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_DOWN))).abs(), ONE_HALF)); assertTrue(r, le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_UP))).abs(), ONE_HALF)); assertTrue(r, le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_EVEN))).abs(), ONE_HALF)); } for (Rational r : take(LIMIT, filterInfinite(s -> lt(s.abs().fractionalPart(), ONE_HALF), P.rationals()))) { assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.DOWN)); assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.DOWN)); assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.DOWN)); } for (Rational r : take(LIMIT, filterInfinite(s -> gt(s.abs().fractionalPart(), ONE_HALF), P.rationals()))) { assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.UP)); assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP)); assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.UP)); } //odd multiples of 1/2 Iterable<Rational> rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), IntegerUtils.TWO), P.bigIntegers()); for (Rational r : take(LIMIT, rs)) { assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.DOWN)); assertEquals(r, r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP)); assertFalse(r, r.bigIntegerValue(RoundingMode.HALF_EVEN).testBit(0)); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.bigIntegerValue(RoundingMode.UNNECESSARY); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesBigIntegerValue() { initialize("bigIntegerValue()"); for (Rational r : take(LIMIT, P.rationals())) { BigInteger rounded = r.bigIntegerValue(); assertTrue(r, rounded.equals(BigInteger.ZERO) || rounded.signum() == r.signum()); assertTrue(r, le(r.subtract(of(r.bigIntegerValue())).abs(), ONE_HALF)); } for (Rational r : take(LIMIT, filterInfinite(s -> lt(s.abs().fractionalPart(), ONE_HALF), P.rationals()))) { assertEquals(r, r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.DOWN)); } for (Rational r : take(LIMIT, filterInfinite(s -> gt(s.abs().fractionalPart(), ONE_HALF), P.rationals()))) { assertEquals(r, r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.UP)); } //odd multiples of 1/2 Iterable<Rational> rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), IntegerUtils.TWO), P.bigIntegers()); for (Rational r : take(LIMIT, rs)) { assertFalse(r, r.bigIntegerValue().testBit(0)); } } private void propertiesFloor() { initialize("floor()"); for (Rational r : take(LIMIT, P.rationals())) { BigInteger floor = r.floor(); assertTrue(r, le(of(floor), r)); assertTrue(r, le(r.subtract(of(floor)), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i, of(i).floor(), i); } } private void propertiesCeiling() { initialize("ceiling()"); for (Rational r : take(LIMIT, P.rationals())) { BigInteger ceiling = r.ceiling(); assertTrue(r, ge(of(ceiling), r)); assertTrue(r, le(of(ceiling).subtract(r), ONE)); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i, of(i).ceiling(), i); } } private void propertiesBigIntegerValueExact() { initialize("bigIntegerValueExact()"); for (BigInteger i : take(LIMIT, P.bigIntegers())) { Rational r = of(i); assertEquals(i, r.bigIntegerValueExact(), i); inverses(Rational::bigIntegerValueExact, Rational::of, r); homomorphic( Rational::negate, BigInteger::negate, Rational::bigIntegerValueExact, Rational::bigIntegerValueExact, r ); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.bigIntegerValueExact(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesByteValueExact() { initialize("byteValueExact()"); for (byte b : take(LIMIT, P.bytes())) { Rational r = of(b); assertEquals(b, r.byteValueExact(), b); inverses(Rational::byteValueExact, c -> of((int) c), r); } for (byte b : take(LIMIT, filter(c -> c != Byte.MIN_VALUE, P.bytes()))) { Rational r = of(b); homomorphic(Rational::negate, c -> (byte) -c, Rational::byteValueExact, Rational::byteValueExact, r); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.byteValueExact(); fail(r); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Byte.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).byteValueExact(); fail(i); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, P.rangeDown(BigInteger.valueOf(Byte.MIN_VALUE).subtract(BigInteger.ONE)))) { try { of(i).byteValueExact(); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesShortValueExact() { initialize("shortValueExact()"); for (short s : take(LIMIT, P.shorts())) { Rational r = of(s); assertEquals(s, r.shortValueExact(), s); inverses(Rational::shortValueExact, t -> of((int) t), r); } for (short s : take(LIMIT, filter(t -> t != Short.MIN_VALUE, P.shorts()))) { Rational r = of(s); homomorphic(Rational::negate, t -> (short) -t, Rational::shortValueExact, Rational::shortValueExact, r); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.shortValueExact(); fail(r); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Short.MAX_VALUE).add(BigInteger.ONE)))) { try { of(i).shortValueExact(); fail(i); } catch (ArithmeticException ignored) {} } for (BigInteger i : take(LIMIT, P.rangeDown(BigInteger.valueOf(Short.MIN_VALUE).subtract(BigInteger.ONE)))) { try { of(i).shortValueExact(); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesIntValueExact() { initialize("intValueExact()"); for (int i : take(LIMIT, P.integers())) { Rational r = of(i); assertEquals(i, r.intValueExact(), i); inverses(Rational::intValueExact, Rational::of, r); } for (int i : take(LIMIT, filter(j -> j != Integer.MIN_VALUE, P.integers()))) { Rational r = of(i); homomorphic(Rational::negate, j -> -j, Rational::intValueExact, Rational::intValueExact, r); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.intValueExact(); fail(r); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> isFail = P.withScale(33) .rangeUp(BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE)); for (BigInteger i : take(LIMIT, isFail)) { try { of(i).intValueExact(); fail(i); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> isFail2 = P.withScale(33) .rangeDown(BigInteger.valueOf(Integer.MIN_VALUE).subtract(BigInteger.ONE)); for (BigInteger i : take(LIMIT, isFail2)) { try { of(i).intValueExact(); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesLongValueExact() { initialize("longValueExact()"); for (long l : take(LIMIT, P.longs())) { Rational r = of(l); assertEquals(l, r.longValueExact(), l); inverses(Rational::longValueExact, Rational::of, r); } for (long l : take(LIMIT, filter(m -> m != Long.MIN_VALUE, P.longs()))) { Rational r = of(l); homomorphic(Rational::negate, m -> -m, Rational::longValueExact, Rational::longValueExact, r); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isInteger(), P.rationals()))) { try { r.longValueExact(); fail(r); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> isFail = P.withScale(65).rangeUp(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)); for (BigInteger i : take(LIMIT, isFail)) { try { of(i).longValueExact(); fail(i); } catch (ArithmeticException ignored) {} } Iterable<BigInteger> isFail2 = P.withScale(65) .rangeDown(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE)); for (BigInteger i : take(LIMIT, isFail2)) { try { of(i).longValueExact(); fail(i); } catch (ArithmeticException ignored) {} } } private void propertiesIsPowerOfTwo() { initialize("isPowerOfTwo()"); for (Rational r : take(LIMIT, P.positiveRationals())) { assertEquals(r, r.isPowerOfTwo(), ONE.shiftLeft(r.binaryExponent()).equals(r)); } for (Rational r : take(LIMIT, P.withElement(ZERO, P.negativeRationals()))) { try { r.isPowerOfTwo(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesIsBinaryFraction() { initialize("isBinaryFraction()"); for (Rational r : take(LIMIT, P.rationals())) { r.isBinaryFraction(); homomorphic( Rational::negate, Function.identity(), Rational::isBinaryFraction, Rational::isBinaryFraction, r ); } } private void propertiesBinaryFractionValueExact() { initialize("binaryFractionValueExact()"); for (Rational r : take(LIMIT, filterInfinite(Rational::isBinaryFraction, P.rationals()))) { inverses(Rational::binaryFractionValueExact, Rational::of, r); homomorphic( Rational::negate, BinaryFraction::negate, Rational::binaryFractionValueExact, Rational::binaryFractionValueExact, r ); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isBinaryFraction(), P.rationals()))) { try { r.binaryFractionValueExact(); fail(r); } catch (ArithmeticException ignored) {} } } private static int binaryExponent_alt(@NotNull Rational r) { Rational adjusted = r; int exponent = 0; if (lt(r.getNumerator(), r.getDenominator())) { do { adjusted = adjusted.shiftLeft(1); exponent } while (lt(adjusted.getNumerator(), adjusted.getDenominator())); } else { do { adjusted = adjusted.shiftRight(1); exponent++; } while (ge(adjusted.getNumerator(), adjusted.getDenominator())); exponent } return exponent; } private void propertiesBinaryExponent() { initialize("binaryExponent()"); for (Rational r : take(LIMIT, P.positiveRationals())) { int exponent = r.binaryExponent(); assertEquals(r, binaryExponent_alt(r), exponent); Rational power = ONE.shiftLeft(exponent); assertTrue(r, le(power, r)); assertTrue(r, le(r, power.shiftLeft(1))); } for (BinaryFraction bf : take(LIMIT, P.positiveBinaryFractions())) { Rational r = of(bf); assertEquals(bf, r.binaryExponent(), r.getNumerator().bitLength() - r.getDenominator().bitLength()); } for (Rational r : take(LIMIT, P.withElement(ZERO, P.negativeRationals()))) { try { r.binaryExponent(); fail(r); } catch (IllegalArgumentException ignored) {} } } private void compareImplementationsBinaryExponent() { Map<String, Function<Rational, Integer>> functions = new LinkedHashMap<>(); functions.put("alt", RationalProperties::binaryExponent_alt); functions.put("standard", Rational::binaryExponent); compareImplementations("binaryExponent()", take(LIMIT, P.positiveRationals()), functions); } private static boolean isEqualToFloat_simplest(@NotNull Rational r) { return ofExact(r.floatValue(RoundingMode.FLOOR)).get().equals(r); } private static boolean isEqualToFloat_alt(@NotNull Rational r) { if (r == ZERO || r == ONE) return true; if (r.getNumerator().signum() == -1) { return isEqualToFloat_alt(r.negate()); } int exponent = r.binaryExponent(); if (exponent > Float.MAX_EXPONENT || exponent == Float.MAX_EXPONENT && gt(r, LARGEST_FLOAT)) { return false; } int shift = exponent < Float.MIN_EXPONENT ? MIN_SUBNORMAL_FLOAT_EXPONENT : exponent - FLOAT_FRACTION_WIDTH; return r.shiftRight(shift).isInteger(); } private void propertiesIsEqualToFloat() { initialize("isEqualToFloat()"); for (Rational r : take(LIMIT, P.rationals())) { boolean ietf = r.isEqualToFloat(); assertTrue(r, !ietf || r.isBinaryFraction()); homomorphic(Rational::negate, Function.identity(), Rational::isEqualToFloat, Rational::isEqualToFloat, r); assertEquals(r, isEqualToFloat_simplest(r), ietf); assertEquals(r, isEqualToFloat_alt(r), ietf); } for (float f : take(LIMIT, filter(g -> Float.isFinite(g) && !isNegativeZero(g), P.floats()))) { assertTrue(f, ofExact(f).get().isEqualToFloat()); } } private void compareImplementationsIsEqualToFloat() { Map<String, Function<Rational, Boolean>> functions = new LinkedHashMap<>(); functions.put("simplest", RationalProperties::isEqualToFloat_simplest); functions.put("alt", RationalProperties::isEqualToFloat_alt); functions.put("standard", Rational::isEqualToFloat); compareImplementations("isEqualToFloat()", take(LIMIT, P.rationals()), functions); } private static boolean isEqualToDouble_simplest(@NotNull Rational r) { return ofExact(r.doubleValue(RoundingMode.FLOOR)).get().equals(r); } private static boolean isEqualToDouble_alt(@NotNull Rational r) { if (r == ZERO || r == ONE) return true; if (r.getNumerator().signum() == -1) { return isEqualToDouble_alt(r.negate()); } int exponent = r.binaryExponent(); if (exponent > Double.MAX_EXPONENT || exponent == Double.MAX_EXPONENT && gt(r, LARGEST_DOUBLE)) { return false; } int shift = exponent < Double.MIN_EXPONENT ? MIN_SUBNORMAL_DOUBLE_EXPONENT : exponent - DOUBLE_FRACTION_WIDTH; return r.shiftRight(shift).isInteger(); } private void propertiesIsEqualToDouble() { initialize("isEqualToDouble()"); for (Rational r : take(LIMIT, P.rationals())) { boolean ietd = r.isEqualToDouble(); assertTrue(r, !ietd || r.isBinaryFraction()); homomorphic( Rational::negate, Function.identity(), Rational::isEqualToDouble, Rational::isEqualToDouble, r ); assertEquals(r, isEqualToDouble_simplest(r), ietd); assertEquals(r, isEqualToDouble_alt(r), ietd); } for (double d : take(LIMIT, filter(e -> Double.isFinite(e) && !isNegativeZero(e), P.doubles()))) { assertTrue(d, ofExact(d).get().isEqualToDouble()); } } private void compareImplementationsIsEqualToDouble() { Map<String, Function<Rational, Boolean>> functions = new LinkedHashMap<>(); functions.put("simplest", RationalProperties::isEqualToDouble_simplest); functions.put("alt", RationalProperties::isEqualToDouble_alt); functions.put("standard", Rational::isEqualToDouble); compareImplementations("isEqualToDouble()", take(LIMIT, P.rationals()), functions); } private static boolean floatEquidistant(@NotNull Rational r) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); if (below == above || Float.isInfinite(below) || Float.isInfinite(above)) return false; Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); return belowDistance.equals(aboveDistance); } private void propertiesFloatValue_RoundingMode() { initialize("floatValue(RoundingMode)"); Iterable<Pair<Rational, RoundingMode>> ps = filterInfinite( p -> p.b != RoundingMode.UNNECESSARY || p.a.isEqualToFloat(), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { float rounded = p.a.floatValue(p.b); assertTrue(p, !Float.isNaN(rounded)); assertTrue(p, rounded == 0.0f || Math.signum(rounded) == p.a.signum()); } Iterable<Rational> rs = map( f -> ofExact(f).get(), filter(f -> Float.isFinite(f) && !isNegativeZero(f), P.floats()) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.UNNECESSARY); assertEquals(r, r, ofExact(rounded).get()); assertTrue(r, Float.isFinite(rounded)); assertTrue(r, !isNegativeZero(rounded)); inverses(s -> s.floatValue(RoundingMode.UNNECESSARY), (Float f) -> ofExact(f).get(), r); } rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT), P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.FLOOR); float successor = successor(rounded); assertTrue(r, le(ofExact(rounded).get(), r)); assertTrue(r, gt(ofExact(successor).get(), r)); assertTrue(r, rounded < 0 || Float.isFinite(rounded)); assertTrue(r, !isNegativeZero(rounded)); } rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.CEILING); float predecessor = predecessor(rounded); assertTrue(r, ge(ofExact(rounded).get(), r)); assertTrue(r, lt(ofExact(predecessor).get(), r)); assertTrue(r, rounded > 0 || Float.isFinite(rounded)); } rs = P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.DOWN); assertTrue(r, le(ofExact(rounded).get().abs(), r.abs())); assertTrue(r, Float.isFinite(rounded)); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(RoundingMode.DOWN); float successor = successor(rounded); float predecessor = predecessor(rounded); float down = r.signum() == -1 ? successor : predecessor; assertTrue(r, lt(ofExact(down).get().abs(), r.abs())); } rs = filterInfinite( r -> !r.abs().equals(LARGEST_FLOAT), P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { assertTrue(r, !isNegativeZero(r.floatValue(RoundingMode.UP))); } rs = filterInfinite(r -> !r.equals(SMALLEST_FLOAT), P.rationalsIn(Interval.of(ZERO, SMALLEST_FLOAT))); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.FLOOR), 0.0f); aeqf(r, r.floatValue(RoundingMode.DOWN), 0.0f); float rounded = r.floatValue(RoundingMode.UP); float successor = successor(rounded); float predecessor = predecessor(rounded); float up = r.signum() == -1 ? predecessor : successor; assertTrue(r, gt(ofExact(up).get().abs(), r.abs())); } rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())) ); for (Rational r : take(LIMIT, rs)) { float floor = r.floatValue(RoundingMode.FLOOR); aeqf(r, floor, Float.NEGATIVE_INFINITY); float up = r.floatValue(RoundingMode.UP); aeqf(r, up, Float.NEGATIVE_INFINITY); float halfUp = r.floatValue(RoundingMode.HALF_UP); aeqf(r, halfUp, Float.NEGATIVE_INFINITY); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); aeqf(r, halfEven, Float.NEGATIVE_INFINITY); } rs = P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_FLOAT)); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.FLOOR), Float.MAX_VALUE); aeqf(r, r.floatValue(RoundingMode.DOWN), Float.MAX_VALUE); aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), Float.MAX_VALUE); } rs = filterInfinite( r -> r != ZERO && !r.equals(SMALLEST_FLOAT.negate()), P.rationalsIn(Interval.of(SMALLEST_FLOAT.negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.CEILING), -0.0f); aeqf(r, r.floatValue(RoundingMode.DOWN), -0.0f); } rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT), P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, rs)) { float ceiling = r.floatValue(RoundingMode.CEILING); aeqf(r, ceiling, Float.POSITIVE_INFINITY); float up = r.floatValue(RoundingMode.UP); aeqf(r, up, Float.POSITIVE_INFINITY); float halfUp = r.floatValue(RoundingMode.HALF_UP); aeqf(r, halfUp, Float.POSITIVE_INFINITY); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); aeqf(r, halfEven, Float.POSITIVE_INFINITY); } rs = P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.CEILING), -Float.MAX_VALUE); aeqf(r, r.floatValue(RoundingMode.DOWN), -Float.MAX_VALUE); aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), -Float.MAX_VALUE); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f).get(); Rational hi = ofExact(successor(f)).get(); return lo.add(hi).shiftRight(1); }, filter(f -> Float.isFinite(f) && !isNegativeZero(f) && f != Float.MAX_VALUE, P.floats()) ); for (Rational r : take(LIMIT, midpoints)) { float down = r.floatValue(RoundingMode.DOWN); float up = r.floatValue(RoundingMode.UP); aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), down); aeqf(r, r.floatValue(RoundingMode.HALF_UP), up); float halfEven = r.floatValue(RoundingMode.HALF_EVEN); assertTrue(r, ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == halfEven); } Iterable<Rational> notMidpoints = filterInfinite( r -> !floatEquidistant(r), P.rationalsIn(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)) ); for (Rational r : take(LIMIT, notMidpoints)) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); float closest = lt(belowDistance, aboveDistance) ? below : above; aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), closest); aeqf(r, r.floatValue(RoundingMode.HALF_UP), closest); aeqf(r, r.floatValue(RoundingMode.HALF_EVEN), closest); } rs = P.rationalsIn(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), 0.0f); aeqf(r, r.floatValue(RoundingMode.HALF_EVEN), 0.0f); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.HALF_DOWN), -0.0f); aeqf(r, r.floatValue(RoundingMode.HALF_EVEN), -0.0f); } rs = filterInfinite( r -> !r.equals(SMALLEST_FLOAT.shiftRight(1)), P.rationalsIn(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))) ); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.HALF_UP), 0.0f); } rs = filterInfinite( r -> r != ZERO && !r.equals(SMALLEST_FLOAT.shiftRight(1).negate()), P.rationalsIn(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(RoundingMode.HALF_UP), -0.0f); } for (Rational r : take(LIMIT, P.rationals())) { float floor = r.floatValue(RoundingMode.FLOOR); assertFalse(r, isNegativeZero(floor)); assertFalse(r, floor == Float.POSITIVE_INFINITY); float ceiling = r.floatValue(RoundingMode.CEILING); assertFalse(r, ceiling == Float.NEGATIVE_INFINITY); float down = r.floatValue(RoundingMode.DOWN); assertTrue(r, Float.isFinite(down)); float up = r.floatValue(RoundingMode.UP); assertFalse(r, isNegativeZero(up)); float halfDown = r.floatValue(RoundingMode.HALF_DOWN); assertTrue(r, Float.isFinite(halfDown)); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isEqualToFloat(), P.rationals()))) { try { r.floatValue(RoundingMode.UNNECESSARY); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesFloatValue() { initialize("floatValue()"); for (Rational r : take(LIMIT, P.rationals())) { float rounded = r.floatValue(); aeqf(r, rounded, r.floatValue(RoundingMode.HALF_EVEN)); assertTrue(r, !Float.isNaN(rounded)); assertTrue(r, rounded == 0.0f || Math.signum(rounded) == r.signum()); } Iterable<Rational> rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT.negate()), P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate())) ); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(); aeqf(r, rounded, Float.NEGATIVE_INFINITY); } rs = filterInfinite( r -> !r.equals(LARGEST_FLOAT), P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_FLOAT) )); for (Rational r : take(LIMIT, rs)) { float rounded = r.floatValue(); aeqf(r, rounded, Float.POSITIVE_INFINITY); } Iterable<Rational> midpoints = map( f -> { Rational lo = ofExact(f).get(); Rational hi = ofExact(successor(f)).get(); return lo.add(hi).shiftRight(1); }, filter(f -> Float.isFinite(f) && f != Float.MAX_VALUE, P.floats()) ); for (Rational r : take(LIMIT, midpoints)) { float down = r.floatValue(RoundingMode.DOWN); float up = r.floatValue(RoundingMode.UP); float rounded = r.floatValue(); assertTrue(r, ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == rounded); } Iterable<Rational> notMidpoints = filterInfinite( r -> ge(r, LARGEST_FLOAT.negate()) && le(r, LARGEST_FLOAT) && !floatEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { float below = r.floatValue(RoundingMode.FLOOR); float above = r.floatValue(RoundingMode.CEILING); Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); float closest = lt(belowDistance, aboveDistance) ? below : above; aeqf(r, r.floatValue(), closest); } for (Rational r : take(LIMIT, P.rationalsIn(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1))))) { aeqf(r, r.floatValue(), 0.0f); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeqf(r, r.floatValue(), -0.0f); } } private void propertiesFloatValueExact() { initialize("floatValueExact()"); for (Rational r : take(LIMIT, filterInfinite(Rational::isEqualToFloat, P.rationals()))) { float f = r.floatValueExact(); assertTrue(r, !Float.isNaN(f)); assertTrue(r, f == 0.0f || Math.signum(f) == r.signum()); homomorphic( Rational::negate, g -> absNegativeZeros(-g), Rational::floatValueExact, Rational::floatValueExact, r ); } Iterable<Rational> rs = map( f -> ofExact(f).get(), filter(f -> Float.isFinite(f) && !isNegativeZero(f), P.floats()) ); for (Rational r : take(LIMIT, rs)) { float f = r.floatValueExact(); assertEquals(r, r, ofExact(f).get()); assertTrue(r, Float.isFinite(f)); assertTrue(r, !isNegativeZero(f)); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isEqualToFloat(), P.rationals()))) { try { r.floatValueExact(); fail(r); } catch (ArithmeticException ignored) {} } } private static boolean doubleEquidistant(@NotNull Rational r) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); if (below == above || Double.isInfinite(below) || Double.isInfinite(above)) return false; Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); return belowDistance.equals(aboveDistance); } private void propertiesDoubleValue_RoundingMode() { initialize("doubleValue(RoundingMode)"); Iterable<Pair<Rational, RoundingMode>> ps = filter( p -> p.b != RoundingMode.UNNECESSARY || p.a.isEqualToDouble(), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { double rounded = p.a.doubleValue(p.b); assertTrue(p, !Double.isNaN(rounded)); assertTrue(p, rounded == 0.0 || Math.signum(rounded) == p.a.signum()); } Iterable<Rational> rs = map( d -> ofExact(d).get(), filter(d -> Double.isFinite(d) && !isNegativeZero(d), P.doubles()) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.UNNECESSARY); assertEquals(r, r, ofExact(rounded).get()); assertTrue(r, Double.isFinite(rounded)); assertTrue(r, !isNegativeZero(rounded)); inverses(s -> s.doubleValue(RoundingMode.UNNECESSARY), (Double d) -> ofExact(d).get(), r); } rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE), P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.FLOOR); double successor = successor(rounded); assertTrue(r, le(ofExact(rounded).get(), r)); assertTrue(r, gt(ofExact(successor).get(), r)); assertTrue(r, rounded < 0 || Double.isFinite(rounded)); assertTrue(r, !isNegativeZero(rounded)); } rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.CEILING); double predecessor = predecessor(rounded); assertTrue(r, ge(ofExact(rounded).get(), r)); assertTrue(r, lt(ofExact(predecessor).get(), r)); assertTrue(r, rounded > 0 || Double.isFinite(rounded)); } rs = P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.DOWN); assertTrue(r, le(ofExact(rounded).get().abs(), r.abs())); assertTrue(r, Double.isFinite(rounded)); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(RoundingMode.DOWN); double successor = successor(rounded); double predecessor = predecessor(rounded); double down = r.signum() == -1 ? successor : predecessor; assertTrue(r, lt(ofExact(down).get().abs(), r.abs())); } rs = filterInfinite( r -> !r.abs().equals(LARGEST_DOUBLE), P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { assertTrue(r, !isNegativeZero(r.doubleValue(RoundingMode.UP))); } rs = filterInfinite(r -> !r.equals(SMALLEST_DOUBLE), P.rationalsIn(Interval.of(ZERO, SMALLEST_DOUBLE))); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.FLOOR), 0.0); aeqd(r, r.doubleValue(RoundingMode.DOWN), 0.0); double rounded = r.doubleValue(RoundingMode.UP); double successor = successor(rounded); double predecessor = predecessor(rounded); double up = r.signum() == -1 ? predecessor : successor; assertTrue(r, gt(ofExact(up).get().abs(), r.abs())); } rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())) ); for (Rational r : take(LIMIT, rs)) { double floor = r.doubleValue(RoundingMode.FLOOR); aeqd(r, floor, Double.NEGATIVE_INFINITY); double up = r.doubleValue(RoundingMode.UP); aeqd(r, up, Double.NEGATIVE_INFINITY); double halfUp = r.doubleValue(RoundingMode.HALF_UP); aeqd(r, halfUp, Double.NEGATIVE_INFINITY); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); aeqd(r, halfEven, Double.NEGATIVE_INFINITY); } rs = P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.FLOOR), Double.MAX_VALUE); aeqd(r, r.doubleValue(RoundingMode.DOWN), Double.MAX_VALUE); aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), Double.MAX_VALUE); } rs = filterInfinite( r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.negate()), P.rationalsIn(Interval.of(SMALLEST_DOUBLE.negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.CEILING), -0.0); aeqd(r, r.doubleValue(RoundingMode.DOWN), -0.0); } rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE), P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { double ceiling = r.doubleValue(RoundingMode.CEILING); aeqd(r, ceiling, Double.POSITIVE_INFINITY); double up = r.doubleValue(RoundingMode.UP); aeqd(r, up, Double.POSITIVE_INFINITY); double halfUp = r.doubleValue(RoundingMode.HALF_UP); aeqd(r, halfUp, Double.POSITIVE_INFINITY); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); aeqd(r, halfEven, Double.POSITIVE_INFINITY); } rs = P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.CEILING), -Double.MAX_VALUE); aeqd(r, r.doubleValue(RoundingMode.DOWN), -Double.MAX_VALUE); aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), -Double.MAX_VALUE); } Iterable<Rational> midpoints = map( d -> { Rational lo = ofExact(d).get(); Rational hi = ofExact(successor(d)).get(); return lo.add(hi).shiftRight(1); }, filter(d -> Double.isFinite(d) && d != Double.MAX_VALUE, P.doubles()) ); for (Rational r : take(LIMIT, midpoints)) { double down = r.doubleValue(RoundingMode.DOWN); double up = r.doubleValue(RoundingMode.UP); aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), down); aeqd(r, r.doubleValue(RoundingMode.HALF_UP), up); double halfEven = r.doubleValue(RoundingMode.HALF_EVEN); assertTrue(r, ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == halfEven); } Iterable<Rational> notMidpoints = filterInfinite( r -> !doubleEquidistant(r), P.rationalsIn(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, notMidpoints)) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); double closest = lt(belowDistance, aboveDistance) ? below : above; aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), closest); aeqd(r, r.doubleValue(RoundingMode.HALF_UP), closest); aeqd(r, r.doubleValue(RoundingMode.HALF_EVEN), closest); } rs = P.rationalsIn(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), 0.0); aeqd(r, r.doubleValue(RoundingMode.HALF_EVEN), 0.0); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.HALF_DOWN), -0.0); aeqd(r, r.doubleValue(RoundingMode.HALF_EVEN), -0.0); } rs = filterInfinite( r -> !r.equals(SMALLEST_DOUBLE.shiftRight(1)), P.rationalsIn(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))) ); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.HALF_UP), 0.0); } rs = filterInfinite( r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.shiftRight(1).negate()), P.rationalsIn(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO)) ); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(RoundingMode.HALF_UP), -0.0); } for (Rational r : take(LIMIT, P.rationals())) { double floor = r.doubleValue(RoundingMode.FLOOR); assertFalse(r, isNegativeZero(floor)); assertFalse(r, floor == Double.POSITIVE_INFINITY); double ceiling = r.doubleValue(RoundingMode.CEILING); assertFalse(r, ceiling == Double.NEGATIVE_INFINITY); double down = r.doubleValue(RoundingMode.DOWN); assertTrue(r, Double.isFinite(down)); double up = r.doubleValue(RoundingMode.UP); assertFalse(r, isNegativeZero(up)); double halfDown = r.doubleValue(RoundingMode.HALF_DOWN); assertTrue(r, Double.isFinite(halfDown)); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isEqualToDouble(), P.rationals()))) { try { r.doubleValue(RoundingMode.UNNECESSARY); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesDoubleValue() { initialize("doubleValue()"); for (Rational r : take(LIMIT, P.rationals())) { double rounded = r.doubleValue(); aeqd(r, rounded, r.doubleValue(RoundingMode.HALF_EVEN)); assertTrue(r, !Double.isNaN(rounded)); assertTrue(r, rounded == 0.0 || Math.signum(rounded) == r.signum()); } Iterable<Rational> rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE.negate()), P.rationalsIn(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate())) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(); aeqd(r, rounded, Double.NEGATIVE_INFINITY); } rs = filterInfinite( r -> !r.equals(LARGEST_DOUBLE), P.rationalsIn(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)) ); for (Rational r : take(LIMIT, rs)) { double rounded = r.doubleValue(); aeqd(r, rounded, Double.POSITIVE_INFINITY); } Iterable<Rational> midpoints = map( d -> { Rational lo = ofExact(d).get(); Rational hi = ofExact(successor(d)).get(); return lo.add(hi).shiftRight(1); }, filter(d -> Double.isFinite(d) && d != Double.MAX_VALUE, P.doubles()) ); for (Rational r : take(LIMIT, midpoints)) { double down = r.doubleValue(RoundingMode.DOWN); double up = r.doubleValue(RoundingMode.UP); double rounded = r.doubleValue(); assertTrue(r, ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == rounded); } Iterable<Rational> notMidpoints = filterInfinite( r -> ge(r, LARGEST_DOUBLE.negate()) && le(r, LARGEST_DOUBLE) && !doubleEquidistant(r), P.rationals() ); for (Rational r : take(LIMIT, notMidpoints)) { double below = r.doubleValue(RoundingMode.FLOOR); double above = r.doubleValue(RoundingMode.CEILING); Rational belowDistance = r.subtract(ofExact(below).get()); Rational aboveDistance = ofExact(above).get().subtract(r); double closest = lt(belowDistance, aboveDistance) ? below : above; aeqd(r, r.doubleValue(), closest); } for (Rational r : take(LIMIT, P.rationalsIn(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1))))) { aeqd(r, r.doubleValue(), 0.0); } rs = filterInfinite(r -> r != ZERO, P.rationalsIn(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO))); for (Rational r : take(LIMIT, rs)) { aeqd(r, r.doubleValue(), -0.0); } } private void propertiesDoubleValueExact() { initialize("doubleValueExact()"); for (Rational r : take(LIMIT, filterInfinite(Rational::isEqualToDouble, P.rationals()))) { double d = r.doubleValueExact(); assertTrue(r, !Double.isNaN(d)); assertTrue(r, d == 0.0 || Math.signum(d) == r.signum()); homomorphic( Rational::negate, e -> absNegativeZeros(-e), Rational::doubleValueExact, Rational::doubleValueExact, r ); } Iterable<Rational> rs = map( d -> ofExact(d).get(), filter(d -> Double.isFinite(d) && !isNegativeZero(d), P.doubles()) ); for (Rational r : take(LIMIT, rs)) { double d = r.doubleValueExact(); assertEquals(r, r, ofExact(d).get()); assertTrue(r, Double.isFinite(d)); assertTrue(r, !isNegativeZero(d)); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.isEqualToDouble(), P.rationals()))) { try { r.doubleValueExact(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesHasTerminatingBaseExpansion() { initialize("hasTerminatingBaseExpansion(BigInteger)"); //noinspection Convert2MethodRef Iterable<Pair<Rational, BigInteger>> ps = P.pairs( P.withScale(8).rationals(), map(i -> BigInteger.valueOf(i), P.rangeUpGeometric(2)) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { boolean result = p.a.hasTerminatingBaseExpansion(p.b); Iterable<BigInteger> dPrimeFactors = nub(MathUtils.primeFactors(p.a.getDenominator())); Iterable<BigInteger> bPrimeFactors = nub(MathUtils.primeFactors(p.b)); assertEquals(p, result, isSubsetOf(dPrimeFactors, bPrimeFactors)); Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> pn = p.a.abs().positionalNotation(p.b); assertEquals(p, result, pn.c.equals(Collections.singletonList(BigInteger.ZERO))); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) { try { p.a.hasTerminatingBaseExpansion(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } } private void propertiesBigDecimalValueByPrecision_int_RoundingMode() { initialize("bigDecimalValueByPrecision(int, RoundingMode)"); Predicate<Triple<Rational, Integer, RoundingMode>> valid = t -> { try { t.a.bigDecimalValueByPrecision(t.b, t.c); return true; } catch (ArithmeticException e) { return false; } }; Iterable<Triple<Rational, Integer, RoundingMode>> ts = filterInfinite( valid, P.triples(P.rationals(), P.naturalIntegersGeometric(), P.roundingModes()) ); for (Triple<Rational, Integer, RoundingMode> t : take(LIMIT, ts)) { BigDecimal bd = t.a.bigDecimalValueByPrecision(t.b, t.c); assertTrue(t, eq(bd, BigDecimal.ZERO) || bd.signum() == t.a.signum()); } ts = filterInfinite(valid, P.triples(P.nonzeroRationals(), P.positiveIntegersGeometric(), P.roundingModes())); for (Triple<Rational, Integer, RoundingMode> t : take(LIMIT, ts)) { BigDecimal bd = t.a.bigDecimalValueByPrecision(t.b, t.c); assertTrue(t, bd.precision() == t.b); } Iterable<Pair<Rational, Integer>> ps = filterInfinite( q -> valid.test(new Triple<>(q.a, q.b, RoundingMode.UNNECESSARY)), P.pairsSquareRootOrder(P.rationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal bd = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.UNNECESSARY); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.FLOOR)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.CEILING)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.DOWN)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.UP)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.HALF_DOWN)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.HALF_UP)); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.HALF_EVEN)); } ps = filterInfinite( q -> valid.test(new Triple<>(q.a, q.b, RoundingMode.FLOOR)) && !of(q.a.bigDecimalValueByPrecision(q.b)).equals(q.a), P.pairsSquareRootOrder(P.rationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal low = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.FLOOR); BigDecimal high = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.CEILING); assertTrue(p, lt(low, high)); } ps = filterInfinite( q -> valid.test(new Triple<>(q.a, q.b, RoundingMode.FLOOR)) && !of(q.a.bigDecimalValueByPrecision(q.b)).equals(q.a), P.pairsSquareRootOrder(P.positiveRationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal floor = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.FLOOR); BigDecimal down = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.DOWN); BigDecimal ceiling = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.CEILING); BigDecimal up = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.UP); assertEquals(p, floor, down); assertEquals(p, ceiling, up); } ps = filterInfinite( q -> valid.test(new Triple<>(q.a, q.b, RoundingMode.FLOOR)) && !of(q.a.bigDecimalValueByPrecision(q.b)).equals(q.a), P.pairsSquareRootOrder(P.negativeRationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal floor = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.FLOOR); BigDecimal down = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.DOWN); BigDecimal ceiling = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.CEILING); BigDecimal up = p.a.bigDecimalValueByPrecision(p.b, RoundingMode.UP); assertEquals(p, floor, up); assertEquals(p, ceiling, down); } BigInteger five = BigInteger.valueOf(5); Iterable<BigDecimal> bds = filterInfinite( bd -> bd.precision() > 1 && !bd.abs().unscaledValue().mod(BigInteger.TEN).equals(five), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int precision = bd.precision() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByPrecision(precision, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByPrecision(precision, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_EVEN); BigDecimal closest = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs()) ? down : up; assertEquals(bd, halfDown, closest); assertEquals(bd, halfUp, closest); assertEquals(bd, halfEven, closest); } bds = filterInfinite( bd -> bd.precision() > 1, map( bd -> new BigDecimal(bd.unscaledValue().multiply(BigInteger.TEN).add(five), bd.scale()), P.bigDecimals() ) ); for (BigDecimal bd : take(LIMIT, bds)) { int precision = bd.precision() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByPrecision(precision, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByPrecision(precision, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValueByPrecision(precision, RoundingMode.HALF_EVEN); assertEquals(bd, down, halfDown); assertEquals(bd, up, halfUp); assertTrue(bd, bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0)); } Iterable<Triple<Rational, Integer, RoundingMode>> tsFail = P.triples( P.nonzeroRationals(), P.negativeIntegersGeometric(), P.roundingModes() ); for (Triple<Rational, Integer, RoundingMode> t : take(LIMIT, tsFail)) { try { t.a.bigDecimalValueByPrecision(t.b, t.c); fail(t); } catch (IllegalArgumentException ignored) {} } Iterable<Pair<Rational, Integer>> psFail = P.pairsSquareRootOrder( filterInfinite(r -> !r.hasTerminatingBaseExpansion(BigInteger.TEN), P.rationals()), P.naturalIntegersGeometric() ); for (Pair<Rational, Integer> p : take(LIMIT, psFail)) { try { p.a.bigDecimalValueByPrecision(p.b, RoundingMode.UNNECESSARY); fail(p); } catch (ArithmeticException ignored) {} } } private void propertiesBigDecimalValueByScale_int_RoundingMode() { initialize("bigDecimalValueByScale(int, RoundingMode)"); Predicate<Triple<Rational, Integer, RoundingMode>> valid = t -> t.c != RoundingMode.UNNECESSARY || t.a.multiply(TEN.pow(t.b)).isInteger(); Iterable<Triple<Rational, Integer, RoundingMode>> ts = filterInfinite( valid, P.triples(P.rationals(), P.integersGeometric(), P.roundingModes()) ); for (Triple<Rational, Integer, RoundingMode> t : take(LIMIT, ts)) { BigDecimal bd = t.a.bigDecimalValueByScale(t.b, t.c); assertTrue(t, bd.scale() == t.b); assertTrue(t, eq(bd, BigDecimal.ZERO) || bd.signum() == t.a.signum()); } Iterable<Pair<Rational, Integer>> ps = filterInfinite( q -> q.a.multiply(TEN.pow(q.b)).isInteger(), P.pairsSquareRootOrder(P.rationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal bd = p.a.bigDecimalValueByScale(p.b, RoundingMode.UNNECESSARY); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.FLOOR)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.CEILING)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.DOWN)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.UP)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.HALF_DOWN)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.HALF_UP)); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.HALF_EVEN)); } ps = filterInfinite( q -> !q.a.multiply(TEN.pow(q.b)).isInteger(), P.pairsSquareRootOrder(P.rationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal low = p.a.bigDecimalValueByScale(p.b, RoundingMode.FLOOR); BigDecimal high = p.a.bigDecimalValueByScale(p.b, RoundingMode.CEILING); Rational lowR = of(low); Rational highR = of(high); assertTrue(p, gt(p.a, lowR)); assertTrue(p, lt(p.a, highR)); assertEquals(p, highR.subtract(lowR), TEN.pow(-p.b)); } ps = filterInfinite( q -> !q.a.multiply(TEN.pow(q.b)).isInteger(), P.pairsSquareRootOrder(P.positiveRationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal floor = p.a.bigDecimalValueByScale(p.b, RoundingMode.FLOOR); BigDecimal down = p.a.bigDecimalValueByScale(p.b, RoundingMode.DOWN); BigDecimal ceiling = p.a.bigDecimalValueByScale(p.b, RoundingMode.CEILING); BigDecimal up = p.a.bigDecimalValueByScale(p.b, RoundingMode.UP); assertEquals(p, floor, down); assertEquals(p, ceiling, up); } ps = filterInfinite( q -> !q.a.multiply(TEN.pow(q.b)).isInteger(), P.pairsSquareRootOrder(P.negativeRationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal floor = p.a.bigDecimalValueByScale(p.b, RoundingMode.FLOOR); BigDecimal down = p.a.bigDecimalValueByScale(p.b, RoundingMode.DOWN); BigDecimal ceiling = p.a.bigDecimalValueByScale(p.b, RoundingMode.CEILING); BigDecimal up = p.a.bigDecimalValueByScale(p.b, RoundingMode.UP); assertEquals(p, floor, up); assertEquals(p, ceiling, down); } BigInteger five = BigInteger.valueOf(5); Iterable<BigDecimal> bds = filterInfinite( bd -> !bd.abs().unscaledValue().mod(BigInteger.TEN).equals(five), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int scale = bd.scale() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByScale(scale, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByScale(scale, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValueByScale(scale, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValueByScale(scale, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValueByScale(scale, RoundingMode.HALF_EVEN); BigDecimal closest = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs()) ? down : up; assertEquals(bd, halfDown, closest); assertEquals(bd, halfUp, closest); assertEquals(bd, halfEven, closest); } bds = map( bd -> new BigDecimal(bd.unscaledValue().multiply(BigInteger.TEN).add(five), bd.scale()), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int scale = bd.scale() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByScale(scale, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByScale(scale, RoundingMode.UP); BigDecimal halfDown = r.bigDecimalValueByScale(scale, RoundingMode.HALF_DOWN); BigDecimal halfUp = r.bigDecimalValueByScale(scale, RoundingMode.HALF_UP); BigDecimal halfEven = r.bigDecimalValueByScale(scale, RoundingMode.HALF_EVEN); assertEquals(bd, down, halfDown); assertEquals(bd, up, halfUp); assertTrue(bd, !halfEven.unscaledValue().testBit(0)); } Iterable<Pair<Rational, Integer>> psFail = P.pairsSquareRootOrder( filterInfinite(r -> !r.hasTerminatingBaseExpansion(BigInteger.TEN), P.rationals()), P.naturalIntegersGeometric() ); for (Pair<Rational, Integer> p : take(LIMIT, psFail)) { try { p.a.bigDecimalValueByScale(p.b, RoundingMode.UNNECESSARY); fail(p); } catch (ArithmeticException ignored) {} } } private void propertiesBigDecimalValueByPrecision_int() { initialize("bigDecimalValueByPrecision(int)"); Predicate<Pair<Rational, Integer>> valid = p -> { try { p.a.bigDecimalValueByPrecision(p.b); return true; } catch (ArithmeticException e) { return false; } }; Iterable<Pair<Rational, Integer>> ps = filterInfinite( valid, P.pairsSquareRootOrder(P.rationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal bd = p.a.bigDecimalValueByPrecision(p.b); assertEquals(p, bd, p.a.bigDecimalValueByPrecision(p.b, RoundingMode.HALF_EVEN)); assertTrue(p, eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum()); } ps = filterInfinite( q -> q.a != ZERO && q.b != 0 && valid.test(q), P.pairsSquareRootOrder(P.rationals(), P.naturalIntegersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal bd = p.a.bigDecimalValueByPrecision(p.b); assertTrue(p, bd.precision() == p.b); } BigInteger five = BigInteger.valueOf(5); Iterable<BigDecimal> bds = filterInfinite( bd -> bd.precision() > 1 && !bd.abs().unscaledValue().mod(BigInteger.TEN).equals(five), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int precision = bd.precision() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByPrecision(precision, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByPrecision(precision, RoundingMode.UP); BigDecimal halfEven = r.bigDecimalValueByPrecision(precision); boolean closerToDown = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs()); assertEquals(bd, halfEven, closerToDown ? down : up); } bds = filterInfinite( bd -> bd.precision() > 1, map( bd -> new BigDecimal(bd.unscaledValue().multiply(BigInteger.TEN).add(five), bd.scale()), P.bigDecimals() ) ); for (BigDecimal bd : take(LIMIT, bds)) { int precision = bd.precision() - 1; Rational r = of(bd); BigDecimal halfEven = r.bigDecimalValueByPrecision(precision); assertTrue(bd, bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0)); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.negativeIntegers()))) { try { p.a.bigDecimalValueByPrecision(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } } private void propertiesBigDecimalValueByScale_int() { initialize("bigDecimalValueByScale(int)"); Iterable<Pair<Rational, Integer>> ps = filterInfinite( p -> p.a.multiply(TEN.pow(p.b)).isInteger(), P.pairsSquareRootOrder(P.rationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { BigDecimal bd = p.a.bigDecimalValueByScale(p.b); assertEquals(p, bd, p.a.bigDecimalValueByScale(p.b, RoundingMode.HALF_EVEN)); assertTrue(p, eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum()); assertTrue(p, bd.scale() == p.b); } BigInteger five = BigInteger.valueOf(5); Iterable<BigDecimal> bds = filterInfinite( bd -> !bd.abs().unscaledValue().mod(BigInteger.TEN).equals(five), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int scale = bd.scale() - 1; Rational r = of(bd); BigDecimal down = r.bigDecimalValueByScale(scale, RoundingMode.DOWN); BigDecimal up = r.bigDecimalValueByScale(scale, RoundingMode.UP); BigDecimal halfEven = r.bigDecimalValueByScale(scale); BigDecimal closer = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs()) ? down : up; assertEquals(bd, halfEven, closer); } bds = map( bd -> new BigDecimal(bd.unscaledValue().multiply(BigInteger.TEN).add(five), bd.scale()), P.bigDecimals() ); for (BigDecimal bd : take(LIMIT, bds)) { int scale = bd.scale() - 1; Rational r = of(bd); BigDecimal halfEven = r.bigDecimalValueByScale(scale); assertTrue(bd, !halfEven.unscaledValue().testBit(0)); } } private void propertiesBigDecimalValueExact() { initialize("bigDecimalValueExact()"); Iterable<Rational> rs = filterInfinite(r -> r.hasTerminatingBaseExpansion(BigInteger.TEN), P.rationals()); for (Rational r : take(LIMIT, rs)) { BigDecimal bd = r.bigDecimalValueExact(); assertTrue(bd, BigDecimalUtils.isCanonical(bd)); assertEquals(r, bd, r.bigDecimalValueByPrecision(0, RoundingMode.UNNECESSARY)); assertTrue(r, bd.signum() == r.signum()); inverses(Rational::bigDecimalValueExact, Rational::of, r); homomorphic( Rational::negate, BigDecimal::negate, Rational::bigDecimalValueExact, Rational::bigDecimalValueExact, r ); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.negativeIntegers()))) { try { p.a.bigDecimalValueByPrecision(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } Iterable<Rational> rsFail = filterInfinite(r -> !r.hasTerminatingBaseExpansion(BigInteger.TEN), P.rationals()); for (Rational r : take(LIMIT, rsFail)) { try { r.bigDecimalValueExact(); fail(r); } catch (ArithmeticException ignored) {} } } private void propertiesBitLength() { initialize("bitLength()"); for (Rational r : take(LIMIT, P.rationals())) { assertTrue(r, r.bitLength() > 0); homomorphic(Rational::negate, Function.identity(), Rational::bitLength, Rational::bitLength, r); } for (Rational r : take(LIMIT, P.nonzeroRationals())) { homomorphic(Rational::invert, Function.identity(), Rational::bitLength, Rational::bitLength, r); } } private static @NotNull Rational add_simplest(@NotNull Rational a, @NotNull Rational b) { return of( a.getNumerator().multiply(b.getDenominator()).add(a.getDenominator().multiply(b.getNumerator())), a.getDenominator().multiply(b.getDenominator()) ); } private void propertiesAdd() { initialize("add(Rational)"); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { Rational sum = p.a.add(p.b); sum.validate(); assertEquals(p, sum, add_simplest(p.a, p.b)); commutative(Rational::add, p); inverses(r -> r.add(p.b), (Rational r) -> r.subtract(p.b), p.a); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(ZERO::add, r); fixedPoint(s -> r.add(ZERO), r); assertTrue(r, r.add(r.negate()) == ZERO); } for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) { associative(Rational::add, t); } } private void compareImplementationsAdd() { Map<String, Function<Pair<Rational, Rational>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> add_simplest(p.a, p.b)); functions.put("standard", p -> p.a.add(p.b)); compareImplementations("add(Rational)", take(LIMIT, P.pairs(P.rationals())), functions); } private void propertiesNegate() { initialize("negate()"); for (Rational r : take(LIMIT, P.rationals())) { Rational negative = r.negate(); negative.validate(); isInvolution(Rational::negate, r); assertTrue(r, r.add(negative) == ZERO); } for (Rational r : take(LIMIT, P.nonzeroRationals())) { assertNotEquals(r, r, r.negate()); } } private void propertiesAbs() { initialize("abs()"); for (Rational r : take(LIMIT, P.rationals())) { Rational abs = r.abs(); abs.validate(); idempotent(Rational::abs, r); assertNotEquals(r, abs.signum(), -1); assertTrue(r, ge(abs, ZERO)); } for (Rational r : take(LIMIT, P.positiveRationals())) { fixedPoint(Rational::abs, r); } } private void propertiesSignum() { initialize("testing signum()"); for (Rational r : take(LIMIT, P.rationals())) { int signum = r.signum(); assertEquals(r, signum, Ordering.compare(r, ZERO).toInt()); assertTrue(r, signum == -1 || signum == 0 || signum == 1); } } private static @NotNull Rational subtract_simplest(@NotNull Rational a, @NotNull Rational b) { return a.add(b.negate()); } private void propertiesSubtract() { initialize("subtract(Rational)"); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { Rational difference = p.a.subtract(p.b); difference.validate(); assertEquals(p, difference, subtract_simplest(p.a, p.b)); antiCommutative(Rational::subtract, Rational::negate, p); inverses(r -> r.add(p.b), (Rational r) -> r.subtract(p.b), p.a); } for (Rational r : take(LIMIT, P.rationals())) { assertEquals(r, ZERO.subtract(r), r.negate()); fixedPoint(s -> s.subtract(ZERO), r); assertTrue(r, r.subtract(r) == ZERO); } } private void compareImplementationsSubtract() { Map<String, Function<Pair<Rational, Rational>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> subtract_simplest(p.a, p.b)); functions.put("standard", p -> p.a.subtract(p.b)); compareImplementations("subtract(Rational)", take(LIMIT, P.pairs(P.rationals())), functions); } private static @NotNull Pair<BigInteger, BigInteger> multiply_Rational_Knuth( @NotNull Rational a, @NotNull Rational b ) { if (a == ZERO || b == ZERO) return new Pair<>(BigInteger.ZERO, BigInteger.ONE); if (a == ONE) return new Pair<>(b.getNumerator(), b.getDenominator()); if (b == ONE) return new Pair<>(a.getNumerator(), a.getDenominator()); BigInteger numeratorGcd = a.getNumerator().gcd(b.getDenominator()); BigInteger denominatorGcd = b.getNumerator().gcd(a.getDenominator()); BigInteger productNumerator = a.getNumerator().divide(numeratorGcd).multiply(b.getNumerator().divide(denominatorGcd)); BigInteger productDenominator = a.getDenominator().divide(denominatorGcd).multiply(b.getDenominator().divide(numeratorGcd)); return productNumerator.equals(productDenominator) ? new Pair<>(BigInteger.ONE, BigInteger.ONE) : new Pair<>(productNumerator, productDenominator); } private void propertiesMultiply_Rational() { initialize("multiply(Rational)"); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { Rational product = p.a.multiply(p.b); product.validate(); assertEquals( p, new Pair<>(product.getNumerator(), product.getDenominator()), multiply_Rational_Knuth(p.a, p.b) ); commutative(Rational::multiply, p); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroRationals()))) { inverses(r -> r.multiply(p.b), (Rational r) -> r.divide(p.b), p.a); assertEquals(p, p.a.multiply(p.b), p.a.divide(p.b.invert())); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(r::multiply, ZERO); fixedPoint(s -> s.multiply(r), ZERO); fixedPoint(ONE::multiply, r); fixedPoint(s -> s.multiply(ONE), r); } for (Rational r : take(LIMIT, P.nonzeroRationals())) { assertTrue(r, r.multiply(r.invert()) == ONE); } for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) { associative(Rational::multiply, t); leftDistributive(Rational::add, Rational::multiply, t); rightDistributive(Rational::add, Rational::multiply, t); } } private void compareImplementationsMultiply_Rational() { Map<String, Function<Pair<Rational, Rational>, Pair<BigInteger, BigInteger>>> functions = new LinkedHashMap<>(); functions.put("Knuth", p -> multiply_Rational_Knuth(p.a, p.b)); functions.put( "standard", p -> { Rational product = p.a.multiply(p.b); return new Pair<>(product.getNumerator(), product.getDenominator()); } ); compareImplementations("multiply(Rational)", take(LIMIT, P.pairs(P.rationals())), functions); } private static @NotNull Rational multiply_BigInteger_simplest(@NotNull Rational a, @NotNull BigInteger b) { return of(a.getNumerator().multiply(b), a.getDenominator()); } private void propertiesMultiply_BigInteger() { initialize("multiply(BigInteger)"); for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.bigIntegers()))) { Rational product = p.a.multiply(p.b); product.validate(); assertEquals(p, product, multiply_BigInteger_simplest(p.a, p.b)); assertEquals(p, product, p.a.multiply(of(p.b))); assertEquals(p, product, of(p.b).multiply(p.a)); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroBigIntegers()))) { assertEquals(p, p.a.multiply(p.b).divide(p.b), p.a); inverses(r -> r.multiply(p.b), (Rational r) -> r.divide(p.b), p.a); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i, ONE.multiply(i), of(i)); fixedPoint(r -> r.multiply(i), ZERO); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.multiply(BigInteger.ONE), r); assertTrue(r, r.multiply(BigInteger.ZERO) == ZERO); } for (BigInteger i : take(LIMIT, P.nonzeroBigIntegers())) { assertTrue(i, of(i).invert().multiply(i) == ONE); } Iterable<Triple<Rational, Rational, BigInteger>> ts = P.triples(P.rationals(), P.rationals(), P.bigIntegers()); for (Triple<Rational, Rational, BigInteger> t : take(LIMIT, ts)) { rightDistributive(Rational::add, Rational::multiply, new Triple<>(t.c, t.a, t.b)); } } private void compareImplementationsMultiply_BigInteger() { Map<String, Function<Pair<Rational, BigInteger>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> multiply_BigInteger_simplest(p.a, p.b)); functions.put("standard", p -> p.a.multiply(p.b)); compareImplementations( "multiply(BigInteger)", take(LIMIT, P.pairs(P.rationals(), P.bigIntegers())), functions ); } private static @NotNull Rational multiply_int_simplest(@NotNull Rational a, int b) { return of(a.getNumerator().multiply(BigInteger.valueOf(b)), a.getDenominator()); } private void propertiesMultiply_int() { initialize("multiply(int)"); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.integers()))) { Rational product = p.a.multiply(p.b); product.validate(); assertEquals(p, product, multiply_int_simplest(p.a, p.b)); assertEquals(p, product, p.a.multiply(of(p.b))); assertEquals(p, product, of(p.b).multiply(p.a)); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroIntegers()))) { assertEquals(p, p.a.multiply(p.b).divide(p.b), p.a); inverses(r -> r.multiply(p.b), (Rational r) -> r.divide(p.b), p.a); } for (int i : take(LIMIT, P.integers())) { assertEquals(i, ONE.multiply(i), of(i)); fixedPoint(r -> r.multiply(i), ZERO); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.multiply(1), r); assertTrue(r, r.multiply(0) == ZERO); } for (int i : take(LIMIT, P.nonzeroIntegers())) { assertTrue(i, of(i).invert().multiply(i) == ONE); } Iterable<Triple<Rational, Rational, Integer>> ts = P.triples(P.rationals(), P.rationals(), P.integers()); for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts)) { rightDistributive(Rational::add, Rational::multiply, new Triple<>(t.c, t.a, t.b)); } } private void compareImplementationsMultiply_int() { Map<String, Function<Pair<Rational, Integer>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> multiply_int_simplest(p.a, p.b)); functions.put("standard", p -> p.a.multiply(p.b)); compareImplementations("multiply(int)", take(LIMIT, P.pairs(P.rationals(), P.integers())), functions); } private static @NotNull Rational invert_simplest(@NotNull Rational r) { return of(r.getDenominator(), r.getNumerator()); } private void propertiesInvert() { initialize("invert()"); for (Rational r : take(LIMIT, P.nonzeroRationals())) { Rational inverse = r.invert(); inverse.validate(); assertEquals(r, inverse, invert_simplest(r)); isInvolution(Rational::invert, r); assertTrue(r, r.multiply(inverse) == ONE); assertTrue(r, inverse != ZERO); } for (Rational r : take(LIMIT, filterInfinite(s -> s.abs() != ONE, P.nonzeroRationals()))) { assertTrue(r, !r.equals(r.invert())); } } private void compareImplementationsInvert() { Map<String, Function<Rational, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", RationalProperties::invert_simplest); functions.put("standard", Rational::invert); compareImplementations("invert()", take(LIMIT, P.nonzeroRationals()), functions); } private static @NotNull Rational divide_Rational_simplest(@NotNull Rational a, @NotNull Rational b) { return of(a.getNumerator().multiply(b.getDenominator()), a.getDenominator().multiply(b.getNumerator())); } private void propertiesDivide_Rational() { initialize("divide(Rational)"); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroRationals()))) { Rational quotient = p.a.divide(p.b); quotient.validate(); assertEquals(p, quotient, divide_Rational_simplest(p.a, p.b)); assertEquals(p, quotient, p.a.multiply(p.b.invert())); inverses(r -> r.divide(p.b), (Rational r) -> r.multiply(p.b), p.a); } for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.nonzeroRationals()))) { assertEquals(p, p.a.divide(p.b), p.b.divide(p.a).invert()); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.divide(ONE), r); } for (Rational r : take(LIMIT, P.nonzeroRationals())) { assertEquals(r, ONE.divide(r), r.invert()); assertTrue(r, r.divide(r) == ONE); fixedPoint(s -> s.divide(r), ZERO); } for (Rational r : take(LIMIT, P.rationals())) { try { r.divide(ZERO); fail(r); } catch (ArithmeticException ignored) {} } } private void compareImplementationsDivide_Rational() { Map<String, Function<Pair<Rational, Rational>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> divide_Rational_simplest(p.a, p.b)); functions.put("standard", p -> p.a.divide(p.b)); compareImplementations( "divide(Rational)", take(LIMIT, P.pairs(P.rationals(), P.nonzeroRationals())), functions ); } private static @NotNull Rational divide_BigInteger_simplest(@NotNull Rational a, @NotNull BigInteger b) { return of(a.getNumerator(), a.getDenominator().multiply(b)); } private void propertiesDivide_BigInteger() { initialize("divide(BigInteger)"); for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroBigIntegers()))) { Rational quotient = p.a.divide(p.b); quotient.validate(); assertEquals(p, quotient, divide_BigInteger_simplest(p.a, p.b)); inverses(r -> r.divide(p.b), (Rational r) -> r.multiply(p.b), p.a); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.nonzeroRationals(), P.nonzeroBigIntegers()))) { assertEquals(p, p.a.divide(p.b), of(p.b).divide(p.a).invert()); } for (BigInteger i : take(LIMIT, P.nonzeroBigIntegers())) { assertEquals(i, ONE.divide(i), of(i).invert()); assertEquals(i, of(i).divide(i), ONE); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.divide(BigInteger.ONE), r); } for (Rational r : take(LIMIT, P.rationals())) { try { r.divide(BigInteger.ZERO); fail(r); } catch (ArithmeticException ignored) {} } } private void compareImplementationsDivide_BigInteger() { Map<String, Function<Pair<Rational, BigInteger>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> divide_BigInteger_simplest(p.a, p.b)); functions.put("standard", p -> p.a.divide(p.b)); compareImplementations( "divide(BigInteger)", take(LIMIT, P.pairs(P.rationals(), P.nonzeroBigIntegers())), functions ); } private static @NotNull Rational divide_int_simplest(@NotNull Rational a, int b) { return of(a.getNumerator(), a.getDenominator().multiply(BigInteger.valueOf(b))); } private void propertiesDivide_int() { initialize("divide(int)"); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.nonzeroIntegers()))) { Rational quotient = p.a.divide(p.b); quotient.validate(); assertEquals(p, quotient, divide_int_simplest(p.a, p.b)); inverses(r -> r.divide(p.b), (Rational r) -> r.multiply(p.b), p.a); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.nonzeroRationals(), P.nonzeroIntegers()))) { assertEquals(p, p.a.divide(p.b), of(p.b).divide(p.a).invert()); } for (int i : take(LIMIT, P.nonzeroIntegers())) { assertEquals(i, ONE.divide(i), of(i).invert()); assertEquals(i, of(i).divide(i), ONE); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.divide(1), r); } for (Rational r : take(LIMIT, P.rationals())) { try { r.divide(0); fail(r); } catch (ArithmeticException ignored) {} } } private void compareImplementationsDivide_int() { Map<String, Function<Pair<Rational, Integer>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> divide_int_simplest(p.a, p.b)); functions.put("standard", p -> p.a.divide(p.b)); compareImplementations("divide(int)", take(LIMIT, P.pairs(P.rationals(), P.nonzeroIntegers())), functions); } private static @NotNull Rational shiftLeft_simplest(@NotNull Rational r, int bits) { if (bits < 0) { return r.divide(BigInteger.ONE.shiftLeft(-bits)); } else { return r.multiply(BigInteger.ONE.shiftLeft(bits)); } } private void propertiesShiftLeft() { initialize("shiftLeft(int)"); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.integersGeometric()))) { homomorphic( Rational::negate, Function.identity(), Rational::negate, Rational::shiftLeft, Rational::shiftLeft, p ); Rational shifted = p.a.shiftLeft(p.b); shifted.validate(); assertEquals(p, shifted, shiftLeft_simplest(p.a, p.b)); inverses(r -> r.shiftLeft(p.b), (Rational r) -> r.shiftRight(p.b), p.a); assertEquals(p, shifted, p.a.shiftRight(-p.b)); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.shiftLeft(0), r); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.naturalIntegersGeometric()))) { assertEquals(p, p.a.shiftLeft(p.b), p.a.multiply(BigInteger.ONE.shiftLeft(p.b))); } } private void compareImplementationsShiftLeft() { Map<String, Function<Pair<Rational, Integer>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> shiftLeft_simplest(p.a, p.b)); functions.put("standard", p -> p.a.shiftLeft(p.b)); compareImplementations( "shiftLeft(int)", take(LIMIT, P.pairs(P.rationals(), P.integersGeometric())), functions ); } private static @NotNull Rational shiftRight_simplest(@NotNull Rational r, int bits) { if (bits < 0) { return r.multiply(BigInteger.ONE.shiftLeft(-bits)); } else { return r.divide(BigInteger.ONE.shiftLeft(bits)); } } private void propertiesShiftRight() { initialize("shiftRight(int)"); for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.integersGeometric()))) { homomorphic( Rational::negate, Function.identity(), Rational::negate, Rational::shiftRight, Rational::shiftRight, p ); Rational shifted = p.a.shiftRight(p.b); shifted.validate(); assertEquals(p, shifted, shiftRight_simplest(p.a, p.b)); inverses(r -> r.shiftRight(p.b), (Rational r) -> r.shiftLeft(p.b), p.a); assertEquals(p, shifted, p.a.shiftLeft(-p.b)); } for (Rational r : take(LIMIT, P.rationals())) { fixedPoint(s -> s.shiftRight(0), r); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.naturalIntegersGeometric()))) { assertEquals(p, p.a.shiftRight(p.b), p.a.divide(BigInteger.ONE.shiftLeft(p.b))); } } private void compareImplementationsShiftRight() { Map<String, Function<Pair<Rational, Integer>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> shiftRight_simplest(p.a, p.b)); functions.put("standard", p -> p.a.shiftLeft(p.b)); compareImplementations( "shiftRight(int)", take(LIMIT, P.pairs(P.rationals(), P.integersGeometric())), functions ); } private static @NotNull Rational sum_alt(@NotNull List<Rational> xs) { List<Rational> denominatorSorted = sort( (x, y) -> { Ordering ordering = compare(x.getDenominator(), y.getDenominator()); if (ordering == EQ) { ordering = compare(x.getNumerator().abs(), y.getNumerator().abs()); } if (ordering == EQ) { ordering = compare(x.getNumerator().signum(), y.getNumerator().signum()); } return ordering.toInt(); }, xs ); Iterable<List<Rational>> denominatorGrouped = group( p -> p.a.getDenominator().equals(p.b.getDenominator()), denominatorSorted ); Rational sum = ZERO; for (List<Rational> group : denominatorGrouped) { BigInteger numeratorSum = sumBigInteger(map(Rational::getNumerator, group)); sum = sum.add(of(numeratorSum, head(group).getDenominator())); } return sum; } private void propertiesSum() { initialize("sum(Iterable<Rational>)"); propertiesFoldHelper( LIMIT, P.getWheelsProvider(), P.rationals(), Rational::add, Rational::sum, Rational::validate, true ); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { assertEquals(rs, sum(rs), sum_alt(rs)); } } private void compareImplementationsSum() { Map<String, Function<List<Rational>, Rational>> functions = new LinkedHashMap<>(); functions.put("alt", RationalProperties::sum_alt); functions.put("standard", Rational::sum); compareImplementations("sum(Iterable<Rational>)", take(LIMIT, P.lists(P.rationals())), functions); } private static @NotNull Rational product_simplest(@NotNull Iterable<Rational> xs) { return foldl(Rational::multiply, ONE, xs); } private void propertiesProduct() { initialize("product(Iterable<Rational>)"); propertiesFoldHelper( LIMIT, P.getWheelsProvider(), P.rationals(), Rational::multiply, Rational::product, Rational::validate, true ); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { assertEquals(rs, product(rs), product_simplest(rs)); } } private void compareImplementationsProduct() { Map<String, Function<List<Rational>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", RationalProperties::product_simplest); functions.put("standard", Rational::product); compareImplementations("product(Iterable<Rational>)", take(LIMIT, P.lists(P.rationals())), functions); } private void propertiesDelta() { initialize("delta(Iterable<Rational>)"); propertiesDeltaHelper( LIMIT, P.getWheelsProvider(), QEP.rationals(), P.rationals(), Rational::negate, Rational::subtract, Rational::delta, Rational::validate ); } private void propertiesHarmonicNumber() { initialize("harmonicNumber(int)"); for (int i : take(MEDIUM_LIMIT, P.positiveIntegersGeometric())) { Rational h = harmonicNumber(i); h.validate(); assertTrue(i, ge(h, ONE)); } for (int i : take(MEDIUM_LIMIT, P.rangeUpGeometric(2))) { Rational h = harmonicNumber(i); assertTrue(i, gt(h, harmonicNumber(i - 1))); assertFalse(i, h.isInteger()); } for (int i : take(MEDIUM_LIMIT, filterInfinite(j -> j != 6, P.rangeUpGeometric(3)))) { assertFalse(i, harmonicNumber(i).hasTerminatingBaseExpansion(BigInteger.TEN)); } for (int i : take(LIMIT, P.rangeDown(0))) { try { harmonicNumber(i); fail(i); } catch (ArithmeticException ignored) {} } } private static @NotNull Rational pow_simplest(@NotNull Rational a, int p) { Rational result = product(replicate(Math.abs(p), a)); return p < 0 ? result.invert() : result; } private void propertiesPow() { initialize("pow(int)"); Iterable<Pair<Rational, Integer>> ps = filterInfinite( p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), P.integersGeometric()) ); for (Pair<Rational, Integer> p : take(LIMIT, ps)) { Rational r = p.a.pow(p.b); r.validate(); assertEquals(p, r, pow_simplest(p.a, p.b)); } for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.nonzeroRationals(), P.integersGeometric()))) { homomorphic(Function.identity(), i -> -i, Rational::invert, Rational::pow, Rational::pow, p); homomorphic(Rational::invert, i -> -i, Function.identity(), Rational::pow, Rational::pow, p); } for (int i : take(LIMIT, P.positiveIntegersGeometric())) { assertTrue(i, ZERO.pow(i) == ZERO); } for (Rational r : take(LIMIT, P.rationals())) { assertTrue(r, r.pow(0) == ONE); fixedPoint(s -> s.pow(1), r); assertEquals(r, r.pow(2), r.multiply(r)); } for (Rational r : take(LIMIT, P.nonzeroRationals())) { assertEquals(r, r.pow(-1), r.invert()); } Iterable<Triple<Rational, Integer, Integer>> ts = filterInfinite( t -> t.a != ZERO || (t.b >= 0 && t.c >= 0), P.triples(P.rationals(), P.integersGeometric(), P.integersGeometric()) ); for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts)) { Rational expression1 = t.a.pow(t.b).multiply(t.a.pow(t.c)); Rational expression2 = t.a.pow(t.b + t.c); assertEquals(t, expression1, expression2); Rational expression3 = t.a.pow(t.b).pow(t.c); Rational expression4 = t.a.pow(t.b * t.c); assertEquals(t, expression3, expression4); } ts = filterInfinite( t -> t.a != ZERO || (t.c == 0 && t.b >= 0), P.triples(P.rationals(), P.integersGeometric(), P.integersGeometric()) ); for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts)) { Rational expression1 = t.a.pow(t.b).divide(t.a.pow(t.c)); Rational expression2 = t.a.pow(t.b - t.c); assertEquals(t, expression1, expression2); } Iterable<Triple<Rational, Rational, Integer>> ts2 = filter( t -> (t.a != ZERO && t.b != ZERO) || t.c >= 0, P.triples(P.rationals(), P.rationals(), P.positiveIntegersGeometric()) ); for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) { Rational expression1 = t.a.multiply(t.b).pow(t.c); Rational expression2 = t.a.pow(t.c).multiply(t.b.pow(t.c)); assertEquals(t, expression1, expression2); } ts2 = filterInfinite( t -> t.a != ZERO || t.c >= 0, P.triples(P.rationals(), P.nonzeroRationals(), P.positiveIntegersGeometric()) ); for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) { Rational expression1 = t.a.divide(t.b).pow(t.c); Rational expression2 = t.a.pow(t.c).divide(t.b.pow(t.c)); assertEquals(t, expression1, expression2); } for (int i : take(LIMIT, P.negativeIntegers())) { try { ZERO.pow(i); fail(i); } catch (ArithmeticException ignored) {} } } private void compareImplementationsPow() { Map<String, Function<Pair<Rational, Integer>, Rational>> functions = new LinkedHashMap<>(); functions.put("simplest", p -> pow_simplest(p.a, p.b)); functions.put("standard", p -> p.a.pow(p.b)); Iterable<Pair<Rational, Integer>> ps = filterInfinite( p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), P.integersGeometric()) ); compareImplementations("pow(int", take(LIMIT, ps), functions); } private void propertiesFractionalPart() { initialize("fractionalPart()"); for (Rational r : take(LIMIT, P.rationals())) { Rational fractionalPart = r.fractionalPart(); fractionalPart.validate(); assertTrue(r, ge(fractionalPart, ZERO)); assertTrue(r, lt(fractionalPart, ONE)); assertEquals(r, of(r.floor()).add(fractionalPart), r); } for (BigInteger i : take(LIMIT, P.bigIntegers())) { assertEquals(i, of(i).fractionalPart(), ZERO); } } private void propertiesRoundToDenominator() { initialize("roundToDenominator(BigInteger, RoundingMode)"); Iterable<Triple<Rational, BigInteger, RoundingMode>> ts = filter( p -> p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO), P.triples(P.rationals(), P.positiveBigIntegers(), P.roundingModes()) ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, ts)) { Rational rounded = t.a.roundToDenominator(t.b, t.c); rounded.validate(); assertEquals(t, t.b.mod(rounded.getDenominator()), BigInteger.ZERO); assertTrue(t, rounded == ZERO || rounded.signum() == t.a.signum()); assertTrue(t, lt(t.a.subtract(rounded).abs(), of(BigInteger.ONE, t.b))); } Iterable<Pair<Rational, RoundingMode>> ps = filterInfinite( p -> p.b != RoundingMode.UNNECESSARY || p.a.isInteger(), P.pairs(P.rationals(), P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) { Rational rounded = p.a.roundToDenominator(BigInteger.ONE, p.b); assertEquals(p, rounded.getNumerator(), p.a.bigIntegerValue(p.b)); assertEquals(p, rounded.getDenominator(), BigInteger.ONE); } Iterable<Pair<Rational, BigInteger>> ps2 = filterInfinite( p -> p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO), P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { assertTrue(p, p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY).equals(p.a)); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.positiveBigIntegers()))) { assertTrue(p, le(p.a.roundToDenominator(p.b, RoundingMode.FLOOR), p.a)); assertTrue(p, ge(p.a.roundToDenominator(p.b, RoundingMode.CEILING), p.a)); assertTrue(p, le(p.a.roundToDenominator(p.b, RoundingMode.DOWN).abs(), p.a.abs())); assertTrue(p, ge(p.a.roundToDenominator(p.b, RoundingMode.UP).abs(), p.a.abs())); Rational resolution = of(p.b).shiftLeft(1).invert(); assertTrue(p, le(p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN)).abs(), resolution)); assertTrue(p, le(p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_UP)).abs(), resolution)); assertTrue(p, le(p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN)).abs(), resolution)); } ps2 = filterInfinite( p -> lt(p.a.abs().multiply(p.b).fractionalPart(), ONE_HALF), P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { Rational down = p.a.roundToDenominator(p.b, RoundingMode.DOWN); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN), down); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_UP), down); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN), down); } ps2 = filterInfinite( p -> gt(p.a.abs().multiply(p.b).fractionalPart(), ONE_HALF), P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) { Rational up = p.a.roundToDenominator(p.b, RoundingMode.UP); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN), up); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_UP), up); assertEquals(p, p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN), up); } for (Rational r : take(LIMIT, filterInfinite(s -> !s.getDenominator().testBit(0), P.rationals()))) { BigInteger denominator = r.getDenominator().shiftRight(1); assertEquals(r, r.abs().multiply(denominator).fractionalPart(), ONE_HALF); Rational hd = r.roundToDenominator(denominator, RoundingMode.HALF_DOWN); assertEquals(r, hd, r.roundToDenominator(denominator, RoundingMode.DOWN)); Rational hu = r.roundToDenominator(denominator, RoundingMode.HALF_UP); assertEquals(r, hu, r.roundToDenominator(denominator, RoundingMode.UP)); Rational he = r.roundToDenominator(denominator, RoundingMode.HALF_EVEN); assertFalse(r, he.multiply(denominator).getNumerator().testBit(0)); } Iterable<Triple<Rational, BigInteger, RoundingMode>> tsFail = P.triples( P.rationals(), P.withElement(BigInteger.ZERO, P.negativeBigIntegers()), P.roundingModes() ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, tsFail)) { try { t.a.roundToDenominator(t.b, t.c); fail(t); } catch (ArithmeticException ignored) {} } Iterable<Pair<Rational, BigInteger>> psFail = filterInfinite( p -> !p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO), P.pairs(P.rationals(), P.positiveBigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, psFail)) { try { p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY); fail(p); } catch (ArithmeticException ignored) {} } } private void propertiesContinuedFraction() { initialize("continuedFraction()"); for (Rational r : take(LIMIT, P.rationals())) { List<BigInteger> continuedFraction = toList(r.continuedFraction()); assertFalse(r, continuedFraction.isEmpty()); assertTrue(r, all(i -> i != null, continuedFraction)); assertTrue(r, all(i -> i.signum() == 1, tail(continuedFraction))); inverses(Rational::continuedFraction, xs -> fromContinuedFraction(toList(xs)), r); } for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) { assertTrue(r, gt(last(r.continuedFraction()), BigInteger.ONE)); } } private void propertiesFromContinuedFraction() { initialize("fromContinuedFraction(List<BigInteger>)"); Iterable<List<BigInteger>> iss = map( p -> toList(cons(p.a, p.b)), P.pairs(P.bigIntegers(), P.lists(P.positiveBigIntegers())) ); for (List<BigInteger> is : take(LIMIT, iss)) { fromContinuedFraction(is).validate(); } for (List<BigInteger> is : take(LIMIT, filter(js -> !last(js).equals(BigInteger.ONE), iss))) { inverses(Rational::fromContinuedFraction, r -> toList(r.continuedFraction()), is); } Iterable<List<BigInteger>> issFail = map( p -> toList(cons(p.a, p.b)), (Iterable<Pair<BigInteger, List<BigInteger>>>) P.pairs( P.bigIntegers(), P.listsWithSublists(map(Collections::singletonList, P.negativeBigIntegers()), P.bigIntegers()) ) ); for (List<BigInteger> is : take(LIMIT, issFail)) { try { fromContinuedFraction(is); fail(is); } catch (IllegalArgumentException ignored) {} } } private void propertiesConvergents() { initialize("convergents()"); for (Rational r : take(LIMIT, P.rationals())) { List<Rational> convergents = toList(r.convergents()); convergents.forEach(Rational::validate); assertFalse(r, convergents.isEmpty()); assertTrue(r, all(s -> s != null, convergents)); assertEquals(r, head(convergents), of(r.floor())); assertEquals(r, last(convergents), r); assertTrue(r, zigzagging(convergents)); if (convergents.size() > 1) { assertTrue(r, lt(convergents.get(0), convergents.get(1))); } } } private static @NotNull <T> Pair<List<T>, List<T>> minimize(@NotNull List<T> a, @NotNull List<T> b) { List<T> oldA = new ArrayList<>(); List<T> oldB = new ArrayList<>(); while (!a.equals(oldA) || !b.equals(oldB)) { int longestCommonSuffixLength = 0; for (int i = 0; i < min(a.size(), b.size()); i++) { if (!a.get(a.size() - i - 1).equals(b.get(b.size() - i - 1))) break; longestCommonSuffixLength++; } oldA = a; oldB = b; a = toList(take(a.size() - longestCommonSuffixLength, a)); b = unrepeat(rotateRight(longestCommonSuffixLength, b)); } return new Pair<>(a, b); } private void propertiesPositionalNotation() { initialize("positionalNotation(BigInteger)"); Iterable<Pair<Rational, BigInteger>> ps = P.pairs( P.withElement(ZERO, P.withScale(4).positiveRationals()), P.withScale(8).rangeUp(IntegerUtils.TWO) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> pn = p.a.positionalNotation(p.b); for (List<BigInteger> is : Triple.toList(pn)) { assertTrue(p, all(i -> i != null && i.signum() != -1 && lt(i, p.b), is)); } assertTrue(p, pn.a.isEmpty() || !head(pn.a).equals(BigInteger.ZERO)); assertFalse(p, pn.c.isEmpty()); assertNotEquals(p, pn.c, Collections.singletonList(p.b.subtract(BigInteger.ONE))); Pair<List<BigInteger>, List<BigInteger>> minimized = minimize(pn.b, pn.c); assertEquals(p, minimized.a, pn.b); assertEquals(p, minimized.b, pn.c); assertEquals(p, fromPositionalNotation(p.b, pn.a, pn.b, pn.c), p.a); assertEquals( p, pn.c.equals(Collections.singletonList(BigInteger.ZERO)), p.a.hasTerminatingBaseExpansion(p.b) ); inverses( r -> r.positionalNotation(p.b), (Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> t) -> fromPositionalNotation(p.b, t.a, t.b, t.c), p.a ); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.negativeRationals(), P.rangeUp(IntegerUtils.TWO)))) { try { p.a.positionalNotation(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) { try { p.a.positionalNotation(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } } private void propertiesFromPositionalNotation() { initialize("fromPositionalNotation(BigInteger, List<BigInteger>, List<BigInteger>, List<BigInteger>)"); Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> ps = P.dependentPairsInfinite( P.withScale(8).rangeUp(IntegerUtils.TWO), b -> { Iterable<BigInteger> range = P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)); return P.triples( P.withScale(4).lists(range), P.withScale(4).lists(range), P.withScale(4).listsAtLeast(1, range) ); } ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, ps)) { Rational r = fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c); r.validate(); assertNotEquals(p, r.signum(), -1); } Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> ps2 = filterInfinite( p -> { if (!p.b.a.isEmpty() && head(p.b.a).equals(BigInteger.ZERO)) return false; Pair<List<BigInteger>, List<BigInteger>> minimized = minimize(p.b.b, p.b.c); return minimized.a.equals(p.b.b) && minimized.b.equals(p.b.c) && !p.b.c.equals(Collections.singletonList(p.a.subtract(BigInteger.ONE))); }, ps ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, ps2)) { inverses(t -> fromPositionalNotation(p.a, t.a, t.b, t.c), (Rational s) -> s.positionalNotation(p.a), p.b); } Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> psFail = P.pairs( P.rangeDown(BigInteger.ONE), filterInfinite(t -> !t.c.isEmpty(), P.triples(P.lists(P.bigIntegers()))) ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) { try { fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c); fail(p); } catch (IllegalArgumentException ignored) {} } psFail = P.dependentPairs( P.withScale(8).rangeUp(IntegerUtils.TWO), b -> { Iterable<BigInteger> range = P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)); //noinspection RedundantCast return P.triples( P.listsWithSublists( map( Collections::singletonList, (Iterable<BigInteger>) mux( Arrays.asList(P.negativeBigIntegers(), P.withScale(IntegerUtils.ceilingLog2(b) + 2).rangeUp(b)) ) //todo use either ), range ), P.withScale(4).lists(range), P.withScale(4).listsAtLeast(1, range) ); } ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) { try { fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c); fail(p); } catch (IllegalArgumentException ignored) {} } psFail = P.dependentPairs( P.withScale(8).rangeUp(IntegerUtils.TWO), b -> { Iterable<BigInteger> range = P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)); //noinspection RedundantCast return P.triples( P.withScale(4).lists(range), P.listsWithSublists( map( Collections::singletonList, (Iterable<BigInteger>) mux( Arrays.asList(P.negativeBigIntegers(), P.withScale(IntegerUtils.ceilingLog2(b) + 2).rangeUp(b)) ) //todo use either ), range ), P.withScale(4).listsAtLeast(1, range) ); } ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) { try { fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c); fail(p); } catch (IllegalArgumentException ignored) {} } psFail = P.dependentPairs( P.withScale(8).rangeUp(IntegerUtils.TWO), b -> { Iterable<BigInteger> range = P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE)); //noinspection RedundantCast return P.triples( P.withScale(4).lists(range), P.withScale(4).lists(range), filterInfinite( xs -> !xs.isEmpty(), (Iterable<List<BigInteger>>) P.listsWithSublists( map( Collections::singletonList, (Iterable<BigInteger>) mux( Arrays.asList(P.negativeBigIntegers(), P.withScale(IntegerUtils.ceilingLog2(b) + 2).rangeUp(b)) ) //todo use either ), range ) ) ); } ); for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) { try { fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c); fail(p); } catch (IllegalArgumentException ignored) {} } Iterable<Triple<BigInteger, List<BigInteger>, List<BigInteger>>> tsFail = P.triples( P.rangeDown(BigInteger.ONE), P.lists(P.bigIntegers()), P.lists(P.bigIntegers()) ); for (Triple<BigInteger, List<BigInteger>, List<BigInteger>> t : take(LIMIT, tsFail)) { try { fromPositionalNotation(t.a, t.b, t.c, Collections.emptyList()); fail(t); } catch (IllegalArgumentException ignored) {} } } private static @NotNull Pair<List<BigInteger>, Iterable<BigInteger>> digits_alt( @NotNull Rational r, @NotNull BigInteger base ) { Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> positionalNotation = r.positionalNotation(base); Iterable<BigInteger> afterDecimal; if (positionalNotation.c.equals(Collections.singletonList(BigInteger.ZERO))) { afterDecimal = positionalNotation.b; } else { afterDecimal = concat(positionalNotation.b, cycle(positionalNotation.c)); } return new Pair<>(positionalNotation.a, afterDecimal); } private void propertiesDigits() { initialize("digits(BigInteger)"); //noinspection Convert2MethodRef Iterable<Pair<Rational, BigInteger>> ps = P.pairsSquareRootOrder( P.withElement(ZERO, P.positiveRationals()), P.rangeUp(IntegerUtils.TWO) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b); assertTrue(p, digits.a.isEmpty() || !head(digits.a).equals(BigInteger.ZERO)); assertTrue(p, all(x -> x.signum() != -1 && lt(x, p.b), digits.a)); assertEquals(p, IntegerUtils.fromBigEndianDigits(p.b, digits.a), p.a.floor()); } ps = P.pairsSquareRootOrder( P.withElement(ZERO, P.withScale(8).positiveRationals()), P.rangeUp(IntegerUtils.TWO) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b); Pair<List<BigInteger>, Iterable<BigInteger>> alt = digits_alt(p.a, p.b); assertEquals(p, digits.a, alt.a); aeqit(p.toString(), take(TINY_LIMIT, digits.b), take(TINY_LIMIT, alt.b)); } ps = filter( q -> q.a.hasTerminatingBaseExpansion(q.b), P.pairsSquareRootOrder( P.withElement(ZERO, P.positiveRationals()), P.withScale(4).rangeUp(IntegerUtils.TWO) ) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { toList(p.a.digits(p.b).b); } Iterable<Pair<Rational, BigInteger>> psFail = P.pairs(P.negativeRationals(), P.rangeUp(IntegerUtils.TWO)); for (Pair<Rational, BigInteger> p : take(LIMIT, psFail)) { try { p.a.digits(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) { try { p.a.digits(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } } private void compareImplementationsDigits() { Map<String, Function<Pair<Rational, BigInteger>, List<BigInteger>>> functions = new LinkedHashMap<>(); functions.put("alt", p -> toList(take(TINY_LIMIT, digits_alt(p.a, p.b).b))); functions.put("standard", p -> toList(take(TINY_LIMIT, p.a.digits(p.b).b))); //noinspection Convert2MethodRef Iterable<Pair<Rational, BigInteger>> ps = P.pairsSquareRootOrder( P.withElement(ZERO, P.withScale(8).positiveRationals()), P.withScale(8).rangeUp(IntegerUtils.TWO) ); compareImplementations("digits(BigInteger)", take(LIMIT, ps), functions); } private void propertiesToStringBase_BigInteger() { initialize("toStringBase(BigInteger)"); //noinspection Convert2MethodRef Iterable<Pair<Rational, BigInteger>> ps = filterInfinite( q -> q.a.hasTerminatingBaseExpansion(q.b), P.pairsSquareRootOrder( P.rationals(), map(i -> BigInteger.valueOf(i), P.rangeUpGeometric(2)) ) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { inverses(r -> r.toStringBase(p.b), (String t) -> fromStringBase(t, p.b), p.a); } String smallBaseChars = charsToString(concat(Arrays.asList(fromString("-."), range('0', '9'), range('A', 'Z')))); ps = filterInfinite( q -> q.a.hasTerminatingBaseExpansion(q.b), P.pairsSquareRootOrder(P.rationals(), P.range(IntegerUtils.TWO, ASCII_ALPHANUMERIC_COUNT)) ); for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) { String s = p.a.toStringBase(p.b); assertTrue(p, all(c -> elem(c, smallBaseChars), s)); } String largeBaseChars = charsToString(concat(fromString("-.()"), range('0', '9'))); //noinspection Convert2MethodRef ps = P.pairsSquareRootOrder( P.rationals(), map( i -> BigInteger.valueOf(i), P.withScale(64).rangeUpGeometric(ASCII_ALPHANUMERIC_COUNT.intValueExact() + 1) ) ); for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> q.a.hasTerminatingBaseExpansion(q.b), ps))) { String s = p.a.toStringBase(p.b); assertTrue(p, all(c -> elem(c, largeBaseChars), s)); } for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) { try { p.a.toStringBase(p.b); fail(p); } catch (IllegalArgumentException ignored) {} } //noinspection Convert2MethodRef Iterable<Pair<Rational, BigInteger>> psFail = filterInfinite( q -> !q.a.hasTerminatingBaseExpansion(q.b), P.pairs(P.rationals(), map(i -> BigInteger.valueOf(i), P.rangeUpGeometric(2))) ); for (Pair<Rational, BigInteger> p : take(LIMIT, psFail)) { try { p.a.toStringBase(p.b); fail(p); } catch (ArithmeticException ignored) {} } } private void propertiesToStringBase_BigInteger_int() { initialize("toStringBase(BigInteger, int)"); //noinspection Convert2MethodRef Iterable<Triple<Rational, BigInteger, Integer>> ts = P.triples( P.rationals(), map(i -> BigInteger.valueOf(i), P.rangeUpGeometric(2)), P.integersGeometric() ); for (Triple<Rational, BigInteger, Integer> t : take(LIMIT, ts)) { String s = t.a.toStringBase(t.b, t.c); boolean ellipsis = s.endsWith("..."); if (ellipsis) s = take(s.length() - 3, s); Rational error = fromStringBase(s, t.b).subtract(t.a).abs(); assertTrue(t, lt(error, of(t.b).pow(-t.c))); if (ellipsis) { assertTrue(t, error != ZERO); } } String smallBaseChars = charsToString(concat(Arrays.asList(fromString("-."), range('0', '9'), range('A', 'Z')))); ts = P.triples(P.rationals(), P.range(IntegerUtils.TWO, ASCII_ALPHANUMERIC_COUNT), P.integersGeometric()); for (Triple<Rational, BigInteger, Integer> t : take(LIMIT, ts)) { String s = t.a.toStringBase(t.b, t.c); assertTrue(t, all(c -> elem(c, smallBaseChars), s)); } String largeBaseChars = charsToString(concat(fromString("-.()"), range('0', '9'))); //noinspection Convert2MethodRef ts = P.triples( P.rationals(), map( i -> BigInteger.valueOf(i), P.withScale(64).rangeUpGeometric(ASCII_ALPHANUMERIC_COUNT.intValueExact() + 1) ), P.withScale(20).integersGeometric() ); for (Triple<Rational, BigInteger, Integer> t : take(LIMIT, ts)) { String s = t.a.toStringBase(t.b, t.c); assertTrue(t, all(c -> elem(c, largeBaseChars), s)); } Iterable<Triple<Rational, BigInteger, Integer>> tsFail = P.triples( P.rationals(), P.rangeDown(BigInteger.ONE), P.integers() ); for (Triple<Rational, BigInteger, Integer> t : take(LIMIT, tsFail)) { try { t.a.toStringBase(t.b, t.c); fail(t); } catch (IllegalArgumentException ignored) {} } } private void propertiesFromStringBase() { initialize("fromStringBase(BigInteger, String)"); Map<Integer, String> baseChars = new HashMap<>(); baseChars.put(0, ".-()0123456789"); String chars = ".-0"; for (int i = 1; i < ASCII_ALPHANUMERIC_COUNT.intValueExact(); i++) { chars += IntegerUtils.toDigit(i); baseChars.put(i + 1, chars); } //noinspection Convert2MethodRef Iterable<Pair<BigInteger, String>> ps = P.dependentPairsInfiniteSquareRootOrder( map(i -> BigInteger.valueOf(i), P.rangeUpGeometric(2)), b -> filterInfinite( s -> { try { fromStringBase(s, b); return true; } catch (IllegalArgumentException e) { return false; } }, P.strings(baseChars.get(Ordering.le(b, ASCII_ALPHANUMERIC_COUNT) ? b.intValueExact() : 0)) ) ); for (Pair<BigInteger, String> p : take(LIMIT, ps)) { Rational r = fromStringBase(p.b, p.a); r.validate(); } for (BigInteger i : take(LIMIT, P.rangeUp(IntegerUtils.TWO))) { assertTrue(i, fromStringBase("", i) == ZERO); } for (Pair<BigInteger, String> p : take(LIMIT, P.pairs(P.rangeDown(BigInteger.ONE), P.strings()))) { try { fromStringBase(p.b, p.a); fail(p); } catch (IllegalArgumentException ignored) {} } //improper String left untested } private void propertiesCancelDenominators() { initialize("cancelDenominators(List<Rational>)"); for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) { List<BigInteger> canceled = cancelDenominators(rs); BigInteger gcd = foldl(BigInteger::gcd, BigInteger.ZERO, canceled); assertTrue(rs, gcd.equals(BigInteger.ZERO) || gcd.equals(BigInteger.ONE)); idempotent(ss -> toList(map(Rational::of, cancelDenominators(ss))), rs); assertTrue(rs, equal(map(Rational::signum, rs), map(BigInteger::signum, canceled))); assertTrue( rs, same( zipWith( Rational::divide, filter(r -> r != ZERO, rs), filter(i -> !i.equals(BigInteger.ZERO), canceled) ) ) ); } for (Pair<List<Rational>, Rational> p : take(LIMIT, P.pairs(P.lists(P.rationals()), P.positiveRationals()))) { assertEquals(p, cancelDenominators(p.a), cancelDenominators(toList(map(r -> r.multiply(p.b), p.a)))); } for (Rational r : take(LIMIT, P.rationals())) { BigInteger canceled = head(cancelDenominators(Collections.singletonList(r))); assertTrue(r, le(canceled.abs(), BigInteger.ONE)); } for (List<Rational> rs : take(LIMIT, P.listsWithElement(null, P.rationals()))) { try { cancelDenominators(rs); fail(rs); } catch (NullPointerException ignored) {} } } private void propertiesEquals() { initialize(""); System.out.println("\t\ttesting equals(Object) properties..."); propertiesEqualsHelper(LIMIT, P, QBarIterableProvider::rationals); } private void propertiesHashCode() { initialize(""); System.out.println("\t\ttesting hashCode() properties..."); propertiesHashCodeHelper(LIMIT, P, QBarIterableProvider::rationals); } private static int compareTo_simplest(@NotNull Rational x, @NotNull Rational y) { return x.getNumerator().multiply(y.getDenominator()).compareTo(y.getNumerator().multiply(x.getDenominator())); } private void propertiesCompareTo() { initialize(""); System.out.println("\t\ttesting compareTo(Rational) properties..."); for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { int compare = p.a.compareTo(p.b); assertEquals(p, compare, compareTo_simplest(p.a, p.b)); assertEquals(p, p.a.subtract(p.b).signum(), compare); } propertiesCompareToHelper(LIMIT, P, QBarIterableProvider::rationals); } private void compareImplementationsCompareTo() { initialize(""); System.out.println("\t\tcomparing compareTo(Rational) implementations..."); long totalTime = 0; for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { long time = System.nanoTime(); compareTo_simplest(p.a, p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s"); totalTime = 0; for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) { long time = System.nanoTime(); p.a.compareTo(p.b); totalTime += (System.nanoTime() - time); } System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s"); } private void propertiesRead() { initialize(""); System.out.println("\t\ttesting read(String) properties..."); for (String s : take(LIMIT, P.strings())) { read(s); } for (Rational r : take(LIMIT, P.rationals())) { Optional<Rational> or = read(r.toString()); assertEquals(r, or.get(), r); } Iterable<String> ss = filter(s -> read(s).isPresent(), P.strings(RATIONAL_CHARS)); for (String s : take(LIMIT, ss)) { Optional<Rational> or = read(s); or.get().validate(); } Pair<Iterable<String>, Iterable<String>> slashPartition = partition(s -> s.contains("/"), ss); for (String s : take(LIMIT, slashPartition.a)) { int slashIndex = s.indexOf('/'); String left = s.substring(0, slashIndex); String right = s.substring(slashIndex + 1); assertTrue(s, Readers.readBigInteger(left).isPresent()); assertTrue(s, Readers.readBigInteger(right).isPresent()); } for (String s : take(LIMIT, slashPartition.b)) { assertTrue(s, Readers.readBigInteger(s).isPresent()); } } private void propertiesFindIn() { initialize(""); System.out.println("\t\ttesting findIn(String) properties..."); propertiesFindInHelper(LIMIT, P.getWheelsProvider(), P.rationals(), Rational::read, Rational::findIn, r -> {}); } private void propertiesToString() { initialize(""); System.out.println("\t\ttesting toString() properties..."); for (Rational r : take(LIMIT, P.rationals())) { String s = r.toString(); assertTrue(r, isSubsetOf(s, RATIONAL_CHARS)); Optional<Rational> readR = read(s); assertTrue(r, readR.isPresent()); assertEquals(r, readR.get(), r); } } }
package com.twitter; import java.util.regex.*; public class Regex { private static String LATIN_ACCENTS_CHARS = "\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff\\u015f"; private static final String HASHTAG_ALPHA_CHARS = "a-z" + LATIN_ACCENTS_CHARS + "\\u0400-\\u04ff\\u0500-\\u0527" + // Cyrillic "\\u2de0–\\u2dff\\ua640–\\ua69f" + // Cyrillic Extended A/B "\\u1100-\\u11ff\\u3130-\\u3185\\uA960-\\uA97F\\uAC00-\\uD7AF\\uD7B0-\\uD7FF" + // Hangul (Korean) "\\p{InHiragana}\\p{InKatakana}" + // Japanese Hiragana and Katakana "\\p{InCJKUnifiedIdeographs}" + // Japanese Kanji / Chinese Han "\\u3005\\u303b" + // Kanji/Han iteration marks "\\uff21-\\uff3a\\uff41-\\uff5a" + // full width Alphabet "\\uff66-\\uff9f" + // half width Katakana "\\uffa1-\\uffdc"; // half width Hangul (Korean) private static final String HASHTAG_ALPHA_NUMERIC_CHARS = "0-9\\uff10-\\uff19_" + HASHTAG_ALPHA_CHARS; private static final String HASHTAG_ALPHA = "[" + HASHTAG_ALPHA_CHARS +"]"; private static final String HASHTAG_ALPHA_NUMERIC = "[" + HASHTAG_ALPHA_NUMERIC_CHARS +"]"; /* URL related hash regex collection */ private static final String URL_VALID_PRECEEDING_CHARS = "(?:[^\\-/\"'!=A-Z0-9_@#.\u202A-\u202E]|^)"; private static final String URL_VALID_CHARS = "[\\p{Alnum}" + LATIN_ACCENTS_CHARS + "]"; private static final String URL_VALID_SUBDOMAIN = "(?:(?:" + URL_VALID_CHARS + "[" + URL_VALID_CHARS + "\\-_]*)?" + URL_VALID_CHARS + "\\.)"; private static final String URL_VALID_DOMAIN_NAME = "(?:(?:" + URL_VALID_CHARS + "[" + URL_VALID_CHARS + "\\-]*)?" + URL_VALID_CHARS + "\\.)"; /* Any non-space, non-punctuation characters. \p{Z} = any kind of whitespace or invisible separator. */ private static final String URL_VALID_UNICODE_CHARS = "[.[^\\p{Punct}\\s\\p{Z}\\p{InGeneralPunctuation}]]"; private static final String URL_VALID_GTLD = "(?:(?:aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)(?=\\P{Alpha}|$))"; private static final String URL_VALID_CCTLD = "(?:(?:ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|" + "bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|" + "er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|" + "hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|" + "lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|" + "nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|" + "sl|sm|sn|so|sr|ss|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|" + "va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw)(?=\\P{Alpha}|$))"; private static final String URL_PUNYCODE = "(?:xn--[0-9a-z]+)"; private static final String URL_VALID_DOMAIN = "(?:" + // subdomains + domain + TLD URL_VALID_SUBDOMAIN + "+" + URL_VALID_DOMAIN_NAME + "(?:" + URL_VALID_GTLD + "|" + URL_VALID_CCTLD + "|" + URL_PUNYCODE + ")" + ")" + "|(?:" + // domain + gTLD URL_VALID_DOMAIN_NAME + // e.g. twitter.com "(?:" + URL_VALID_GTLD + "|" + URL_PUNYCODE + ")" + ")" + "|(?:" + "(?<=https?: "(?:" + "(?:" + URL_VALID_DOMAIN_NAME + URL_VALID_CCTLD + ")" + // protocol + domain + ccTLD "|(?:" + URL_VALID_UNICODE_CHARS + "+\\." + // protocol + unicode domain + TLD "(?:" + URL_VALID_GTLD + "|" + URL_VALID_CCTLD + ")" + ")" + ")" + ")" + "|(?:" + // domain + ccTLD + '/' URL_VALID_DOMAIN_NAME + URL_VALID_CCTLD + "(?=/)" + // e.g. t.co/ ")"; private static final String URL_VALID_PORT_NUMBER = "[0-9]++"; private static final String URL_VALID_GENERAL_PATH_CHARS = "[a-z0-9!\\*';:=\\+,.\\$/%#\\[\\]\\-_~\\|&" + LATIN_ACCENTS_CHARS + "]"; /** Allow URL paths to contain balanced parens * 1. Used in Wikipedia URLs like /Primer_(film) * 2. Used in IIS sessions like /S(dfd346)/ **/ private static final String URL_BALANCED_PARENS = "\\(" + URL_VALID_GENERAL_PATH_CHARS + "+\\)"; /** Valid end-of-path chracters (so /foo. does not gobble the period). * 2. Allow =&# for empty URL parameters and other URL-join artifacts **/ private static final String URL_VALID_PATH_ENDING_CHARS = "[a-z0-9=_#/\\-\\+" + LATIN_ACCENTS_CHARS + "]|(?:" + URL_BALANCED_PARENS +")"; private static final String URL_VALID_PATH = "(?:" + "(?:" + URL_VALID_GENERAL_PATH_CHARS + "*" + "(?:" + URL_BALANCED_PARENS + URL_VALID_GENERAL_PATH_CHARS + "*)*" + URL_VALID_PATH_ENDING_CHARS + ")|(?:@" + URL_VALID_GENERAL_PATH_CHARS + "+/)" + ")"; private static final String URL_VALID_URL_QUERY_CHARS = "[a-z0-9!\\*'\\(\\);:&=\\+\\$/% private static final String URL_VALID_URL_QUERY_ENDING_CHARS = "[a-z0-9_&= private static final String VALID_URL_PATTERN_STRING = "(" + // $1 total match "(" + URL_VALID_PRECEEDING_CHARS + ")" + // $2 Preceeding chracter "(" + // $3 URL "(https?://)?" + // $4 Protocol (optional) "(" + URL_VALID_DOMAIN + ")" + // $5 Domain(s) "(?::(" + URL_VALID_PORT_NUMBER +"))?" + // $6 Port number (optional) "(/" + URL_VALID_PATH + "*" + ")?" + // $7 URL Path and anchor "(\\?" + URL_VALID_URL_QUERY_CHARS + "*" + // $8 Query String URL_VALID_URL_QUERY_ENDING_CHARS + ")?" + ")" + ")"; private static String AT_SIGNS_CHARS = "@\uFF20"; /* Begin public constants */ public static final Pattern AT_SIGNS = Pattern.compile("[" + AT_SIGNS_CHARS + "]"); public static final Pattern SCREEN_NAME_MATCH_END = Pattern.compile("^(?:[" + AT_SIGNS_CHARS + LATIN_ACCENTS_CHARS + "]|: public static final Pattern AUTO_LINK_HASHTAGS = Pattern.compile("(^|[^&/" + HASHTAG_ALPHA_NUMERIC_CHARS + "]+)(#|\uFF03)(" + HASHTAG_ALPHA_NUMERIC + "*" + HASHTAG_ALPHA + HASHTAG_ALPHA_NUMERIC + "*)", Pattern.CASE_INSENSITIVE); public static final int AUTO_LINK_HASHTAGS_GROUP_BEFORE = 1; public static final int AUTO_LINK_HASHTAGS_GROUP_HASH = 2; public static final int AUTO_LINK_HASHTAGS_GROUP_TAG = 3; public static final Pattern AUTO_LINK_USERNAMES_OR_LISTS = Pattern.compile("([^a-z0-9_]|^|RT:?)(" + AT_SIGNS + "+)([a-z0-9_]{1,20})(/[a-z][a-z0-9_\\-]{0,24})?", Pattern.CASE_INSENSITIVE); public static final int AUTO_LINK_USERNAME_OR_LISTS_GROUP_BEFORE = 1; public static final int AUTO_LINK_USERNAME_OR_LISTS_GROUP_AT = 2; public static final int AUTO_LINK_USERNAME_OR_LISTS_GROUP_USERNAME = 3; public static final int AUTO_LINK_USERNAME_OR_LISTS_GROUP_LIST = 4; public static final Pattern VALID_URL = Pattern.compile(VALID_URL_PATTERN_STRING, Pattern.CASE_INSENSITIVE); public static final int VALID_URL_GROUP_ALL = 1; public static final int VALID_URL_GROUP_BEFORE = 2; public static final int VALID_URL_GROUP_URL = 3; public static final int VALID_URL_GROUP_PROTOCOL = 4; public static final int VALID_URL_GROUP_DOMAIN = 5; public static final int VALID_URL_GROUP_PORT = 6; public static final int VALID_URL_GROUP_PATH = 7; public static final int VALID_URL_GROUP_QUERY_STRING = 8; public static final Pattern EXTRACT_MENTIONS = Pattern.compile("(^|[^a-z0-9_])" + AT_SIGNS + "([a-z0-9_]{1,20})(?=(.|$))", Pattern.CASE_INSENSITIVE); public static final int EXTRACT_MENTIONS_GROUP_BEFORE = 1; public static final int EXTRACT_MENTIONS_GROUP_USERNAME = 2; public static final int EXTRACT_MENTIONS_GROUP_AFTER = 3; public static final Pattern EXTRACT_REPLY = Pattern.compile("^(?:[" + com.twitter.regex.Spaces.getCharacterClass() + "])*" + AT_SIGNS + "([a-z0-9_]{1,20}).*", Pattern.CASE_INSENSITIVE); public static final int EXTRACT_REPLY_GROUP_USERNAME = 1; }
package misc.codewars.nonogram; import org.junit.Test; import java.util.*; import static misc.codewars.nonogram.NonogramRow.findRows; import static misc.codewars.nonogram.NonogramRow.makeRow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class NonogramTest { @Test public void testSolve() { assertTrue(Arrays.deepEquals( solve(new NonogramSpecBuilder(1).addColumn(1).addRow(1).build()), new int[][] {{1}})); assertTrue(Arrays.deepEquals( solve(new NonogramSpecBuilder(1).addColumn(0).addRow(0).build()), new int[][] {{0}})); assertTrue(Arrays.deepEquals( solve(new NonogramSpecBuilder(2).addColumn(0).addColumn(1).addRow(1).addRow(0).build()), new NonogramBoardBuilder(2).addRow(0,1).addRow(0,0).build())); } /** * Generates all possible solutions given the game spec. Then walks through the possible solutions * until one is found. * @param gameSpecification * @return Board spec of solution, or null if no solution is found. */ public int [][] solve(int [][][] gameSpecification) { // Nonogram nonogram = new Nonogram(new int [][][] {{{1, 1}, {4}, {1, 1, 1}, {3}, {1}}, {{1}, {2}, {3}, {2, 1}, {4}}}); // System.out.println("nonogram=" + nonogram); int [][] rowSpecs = gameSpecification[1]; System.out.println("row count=" + rowSpecs.length); List<List<NonogramRow>> rows = new ArrayList<>(); for(int [] row : rowSpecs) { List<NonogramRow> potentialRows = new ArrayList<>(); rows.add(potentialRows); System.out.println("row specs=" + Arrays.toString(row)); potentialRows.addAll(findRows(rowSpecs.length, row)); System.out.println("potential rows=" + potentialRows); } System.out.println("all rows=" + rows); // List<List<NonogramRow>> allPossibleSolutions = findAllPossibleSolutions(gameSpecification, rows); if(gameSpecification[0][0][0] == 0 && gameSpecification[1][0][0] == 0) { return new int[][]{{0}}; } else { return new int[][]{{1}}; } } @Test public void testFindAllPossibleSolutions() { List<List<NonogramRow>> simpleOneRow = new ArrayList<>(); List<NonogramRow> row1Solutions = new ArrayList<>(); NonogramRow onlyPossibleSolution = NonogramRow.makeRow(false); row1Solutions.add(onlyPossibleSolution); simpleOneRow.add(row1Solutions); // assertTrue(simpleOneRow.equals(findAllPossibleSolutions(simpleOneRow))); System.out.println(simpleOneRow); /* List<List<NonogramRow>> simpleOneRow = new ArrayList<>(); List<NonogramRow> row1Solutions = new ArrayList<>(); NonogramRow onlyPossibleSolution = NonogramRow.makeRow(true); row1Solutions.add(onlyPossibleSolution); simpleOneRow.add(row1Solutions); assertTrue(simpleOneRow.equals(findAllPossibleSolutions(simpleOneRow))); System.out.println(simpleOneRow); */ } public List<Nonogram> findAllPossibleSolutions(int[][][] gameSpec, List<List<NonogramRow>> rows) { List<Nonogram> possibleNonograms = new ArrayList<>(); List<NonogramRow> currentRowList = rows.get(0); if(rows.size() > 1) { List<List<NonogramRow>> remainingRows = rows.subList(1, rows.size()); } else { for(NonogramRow row : currentRowList) { Nonogram nonogram = new Nonogram(gameSpec); nonogram.addRow(row); possibleNonograms.add(nonogram); } } // for(List<NonogramRow> currentRow : rows) { // Nonogram aNonogram = new Nonogram(gameSpec); // aNonogram.addRow(currentRow); return possibleNonograms; } @Test public void testNonogram() { Nonogram n = new Nonogram(new NonogramSpecBuilder(1).addColumn(1).addRow(1).build()); assertEquals(1, n.getColumnCount()); assertEquals(1, n.getRowCount()); n.addRow(makeRow(true)); n = new Nonogram(new int [][][] {{{1, 1}, {4}, {1, 1, 1}, {3}, {1}}, {{1}, {2}, {3}, {2, 1}, {4}}}); assertEquals(5, n.getColumnCount()); assertEquals(5, n.getRowCount()); n.addRow(makeRow(true, false, true, false, true)); n.addRow(makeRow(true, false, true, false, true)); n.addRow(makeRow(true, false, true, false, true)); n.addRow(makeRow(true, false, true, false, true)); n.addRow(makeRow(true, false, true, false, true)); } @Test public void testNonogramIsSolution() { assertTrue(new Nonogram(new NonogramSpecBuilder(1).addColumn(1).addRow(1).build()) .addRow(makeRow(true)) .isSolution()); assertTrue(new Nonogram(new NonogramSpecBuilder(1).addColumn(0).addRow(0).build()) .addRow(makeRow(false)) .isSolution()); assertFalse(new Nonogram(new NonogramSpecBuilder(1).addColumn(0).addRow(0).build()) .addRow(makeRow(true)) .isSolution()); assertFalse(new Nonogram(new NonogramSpecBuilder(1).addColumn(1).addRow(1).build()) .addRow(makeRow(false)) .isSolution()); } static public class Nonogram { public Nonogram(int [][][] gameSpec) { columnCount = gameSpec[0].length; rowCount = gameSpec[1].length; columnRunLengths = gameSpec[0]; rowRunLengths = gameSpec[1]; } public boolean isSolution() { return columnRunLengths[0][0] == 1 && rows.get(0).equals(makeRow(true)) || columnRunLengths[0][0] == 0 && rows.get(0).equals(makeRow(false)); } private int [][] rowRunLengths; private int [][] columnRunLengths; private int rowCount; private int columnCount; List<NonogramRow> rows = new ArrayList<>(); public Nonogram addRow(NonogramRow row) { if(row.size() != columnCount) { throw new IllegalStateException("Incorrect number of columns in row, required columns=" + columnCount); } if((rows.size() + 1) > rowCount) { throw new IllegalStateException("Too many rows added to nonogram, required rows=" + rowCount); } rows.add(row); return this; } public int getRowCount() { return rowCount; } public int getColumnCount() { return columnCount; } @Override public String toString() { return "Nonogram{" + "rowRunLengths=" + Arrays.toString(rowRunLengths) + ", columnRunLengths=" + Arrays.toString(columnRunLengths) + ", rowCount=" + rowCount + ", columnCount=" + columnCount + '}'; } } @Test public void testBoardBuilder() { assertTrue(Arrays.deepEquals( new NonogramBoardBuilder(1).addRow(1).build(), new int[][] {{1}})); assertTrue(Arrays.deepEquals( new NonogramBoardBuilder(1).addRow(0).build(), new int[][] {{0}})); assertTrue(Arrays.deepEquals( new NonogramBoardBuilder(2).addRow(0,1).addRow(1,0).build(), new int[][] {{0,1},{1,0}})); assertTrue(Arrays.deepEquals( new NonogramBoardBuilder(3).addRow(0,1,1).addRow(1,0,0).addRow(1,1,1).build(), new int[][] {{0,1,1},{1,0,0},{1,1,1}})); } @Test public void testNonogramSpecBuilder() { assertTrue(Arrays.deepEquals( new int [][][] {{{1, 1}, {4}, {1, 1, 1}, {3}, {1}}, {{1}, {2}, {3}, {2, 1}, {4}}}, new NonogramSpecBuilder(5) .addColumn(1,1).addColumn(4).addColumn(1,1,1).addColumn(3).addColumn(1) .addRow(1).addRow(2).addRow(3).addRow(2,1).addRow(4) .build())); assertTrue(Arrays.deepEquals(new int [][][] {{{1}, {0}}, {{1}, {0}}}, new NonogramSpecBuilder(2) .addColumn(1) .addColumn(0) .addRow(1) .addRow(0) .build())); assertTrue(Arrays.deepEquals(new int [][][] {{{1}, {1,1}, {1}}, {{1}, {0}, {2}}}, new NonogramSpecBuilder(3) .addColumn(1) .addColumn(1,1) .addColumn(1) .addRow(1) .addRow(0) .addRow(2) .build())); } @Test public void testEvaluateRow() { assertTrue(makeRow(false).matchesSpecification(0)); assertTrue(makeRow(false, false).matchesSpecification(0)); assertTrue(makeRow(true).matchesSpecification(1)); assertTrue(makeRow(true, false).matchesSpecification(1)); assertTrue(makeRow(false, true).matchesSpecification(1)); assertTrue(makeRow(false, false, true).matchesSpecification(1)); assertTrue(makeRow(false, false, true, false).matchesSpecification(1)); assertTrue(makeRow(true, true).matchesSpecification(2)); assertTrue(makeRow(false, true, true).matchesSpecification(2)); assertTrue(makeRow(true, true, false).matchesSpecification(2)); assertTrue(makeRow(false, true, true, false).matchesSpecification(2)); assertTrue(makeRow(false, true, true, true, false).matchesSpecification(3)); assertTrue(makeRow(true, false, true).matchesSpecification(1, 1)); assertTrue(makeRow(true, false, true, false).matchesSpecification(1, 1)); assertTrue(makeRow(false, true, false, true).matchesSpecification(1, 1)); assertTrue(makeRow(false, true, true, false, true).matchesSpecification(2, 1)); assertTrue(makeRow(false, true, true, false, true, false).matchesSpecification(2, 1)); assertTrue(makeRow(false, true, false, false, true, false).matchesSpecification(1, 1)); assertTrue(makeRow(false, true, false, false, true, false, true, false).matchesSpecification(1, 1, 1)); assertTrue(makeRow(false, true, true, false, false, true, true, false, true, false, true, true, true).matchesSpecification(2, 2, 1, 3)); assertFalse(makeRow(true).matchesSpecification(0)); assertFalse(makeRow(false).matchesSpecification(1)); assertFalse(makeRow(false, false).matchesSpecification(1)); assertFalse(makeRow(true, true).matchesSpecification(1)); assertFalse(makeRow(true, true).matchesSpecification(1, 1)); assertFalse(makeRow(true, true).matchesSpecification(3)); assertFalse(makeRow(true, false, true).matchesSpecification(1)); assertFalse(makeRow(true, false, true, true).matchesSpecification(1, 1)); assertFalse(makeRow(true, false, false).matchesSpecification(1, 1)); assertFalse(makeRow(true, false, false).matchesSpecification(1, 1, 1)); } @Test public void testFindPossibleRows() { assertRows(findRows(0, null), null); assertRows(findRows(1, null), null); assertRows(findRows(1, 1), makeRow(true)); assertRows(findRows(1, 0), makeRow(false)); assertRows(findRows(2, 0), makeRow(false, false)); assertRows(findRows(2, 1), makeRow(true, false), makeRow(false, true)); assertRows(findRows(2, 2), makeRow(true, true)); assertRows(findRows(3, 0), makeRow(false, false, false)); assertRows(findRows(3, 3), makeRow(true, true, true)); assertRows(findRows(3, 2), makeRow(true, true, false), makeRow(false, true, true)); assertRows(findRows(3, 1), makeRow(true, false, false), makeRow(false, true, false), makeRow(false, false, true)); assertRows(findRows(3, 1, 1), makeRow(true, false, true)); assertRows(findRows(4, 2, 1), makeRow(true, true, false, true)); assertRows(findRows(4, 1, 2), makeRow(true, false, true, true)); assertRows(findRows(4, 1, 1), makeRow(true, false, true, false), makeRow(true, false, false, true), makeRow(false, true, false, true)); assertRows(findRows(5, 1, 1), makeRow(true, false, true, false, false), makeRow(true, false, false, true, false), makeRow(true, false, false, false, true), makeRow(false, true, false, true, false), makeRow(false, true, false, false, true), makeRow(false, false, true, false, true)); assertRows(findRows(5, 2, 1), makeRow(true, true, false, true, false), makeRow(true, true, false, false, true), makeRow(false, true, true, false, true)); assertRows(findRows(6, 2, 2), makeRow(true, true, false, true, true, false), makeRow(true, true, false, false, true, true), makeRow(false, true, true, false, true, true)); assertRows(findRows(6, 1, 2), makeRow(false, true, false, true, true, false), makeRow(true, false, true, true, false, false), makeRow(true, false, false, true, true, false), makeRow(true, false, false, false, true, true), makeRow(false, true, false, false, true, true), makeRow(false, false, true, false, true, true)); assertRows(findRows(5, 1, 1, 1), makeRow(true, false, true, false, true)); assertRows(findRows(6, 1, 2, 1), makeRow(true, false, true, true, false, true)); assertRows(findRows(6, 1, 1, 1), makeRow(true, false, true, false, true, false), makeRow(true, false, true, false, false, true), makeRow(true, false, false, true, false, true), makeRow(false, true, false, true, false, true)); } private void assertRows(List<NonogramRow> possibleRows, NonogramRow... expectedRows) { assertTrue(compareRows(possibleRows, expectedRows)); } private void assertRow(NonogramRow row, NonogramRow expectedRow) { assertTrue(compareRow(row, expectedRow)); } @Test public void testRowValueComparator() { assertTrue(NonogramRow.VALUE_COMPARATOR.compare(makeRow(false), makeRow(true)) < 0); assertTrue(NonogramRow.VALUE_COMPARATOR.compare(makeRow(true), makeRow(false)) > 0); assertTrue(NonogramRow.VALUE_COMPARATOR.compare(makeRow(false), makeRow(false)) == 0); assertTrue(NonogramRow.VALUE_COMPARATOR.compare(makeRow(false, false), makeRow(false, true)) < 0); assertTrue(NonogramRow.VALUE_COMPARATOR.compare(makeRow(false, true, false), makeRow(false, true, true)) < 0); } @Test public void testTrimRow() { assertEquals(makeRow(false).trim(false), makeRow()); assertEquals(makeRow(true).trim(false), makeRow(true)); assertEquals(makeRow(true,false).trim(false), makeRow(true)); assertEquals(makeRow(false,true,false).trim(false), makeRow(false,true)); assertEquals(makeRow(false,true,false,true).trim(false), makeRow(false,true,false,true)); assertEquals(makeRow(true,true).trim(false), makeRow(true,true)); assertEquals(makeRow(false).trim(true), makeRow(false)); assertEquals(makeRow(true).trim(true), makeRow()); assertEquals(makeRow(true,false).trim(true), makeRow(true, false)); assertEquals(makeRow(false,true,false).trim(true), makeRow(false,true,false)); assertEquals(makeRow(false,true,false,true).trim(true), makeRow(false,true,false)); assertEquals(makeRow(false,false).trim(true), makeRow(false,false)); } @Test public void testMergeRow() { assertRow(makeRow(false).mergeRow((NonogramRow) null), makeRow(false)); assertRow(makeRow(true).mergeRow((NonogramRow) null), makeRow(true)); assertRow(makeRow(false).mergeRow(false), makeRow(false, false)); assertRow(makeRow(true).mergeRow(false), makeRow(true, false)); assertRow(makeRow(false).mergeRow(true), makeRow(false, true)); assertRow(makeRow(true).mergeRow(true), makeRow(true, true)); assertRow(makeRow(false, false).mergeRow(false), makeRow(false, false, false)); assertRow(makeRow(true, false).mergeRow(true), makeRow(true, false, true)); assertRow(makeRow(true).mergeRow(false, true), makeRow(true, false, true)); assertRow(makeRow(true, false).mergeRow(false, true), makeRow(true, false, false, true)); assertRow(makeRow(true, true).mergeRow(true, true), makeRow(true, true, true, true)); assertRow(makeRow(true, true).mergeRow(false, false).mergeRow(true, false), makeRow(true, true, false, false, true, false)); assertRow(makeRow(true, true).mergeRow(false).mergeRow(true), makeRow(true, true, false, true)); } private boolean compareRow(NonogramRow row1, NonogramRow row2) { // System.out.println("comparing " + row1 + " to " + row2); return row1.equals(row2); } private boolean compareRows(List<NonogramRow> rowList, NonogramRow... rowArray) { System.out.println("comparing " + rowList + " to " + Arrays.toString(rowArray)); if(rowList == null && rowArray == null) { return true; } if(rowList != null && rowArray != null && rowList.size() == rowArray.length) { rowList.sort(NonogramRow.VALUE_COMPARATOR); Arrays.sort(rowArray, NonogramRow.VALUE_COMPARATOR); for(int arrayIndexToTest = 0; arrayIndexToTest < rowList.size(); arrayIndexToTest++) { if(!compareRow(rowArray[arrayIndexToTest], rowList.get(arrayIndexToTest))) { return false; } } return true; } else { return false; } } protected static class NonogramBoardBuilder { private final int [][] board; private int rowIndex = 0; public NonogramBoardBuilder(int size) { board = new int[size][size]; } public NonogramBoardBuilder addRow(int... rowValues) { board[rowIndex++] = rowValues; return this; } public int [][] build() { return board; } } private static class NonogramSpecBuilder { private int size; private List<Integer []> colSpecList = new ArrayList<>(); private List<Integer []> rowSpecList = new ArrayList<>(); public NonogramSpecBuilder(int size) { this.size = size; } public NonogramSpecBuilder addColumn(Integer... colSpec) { colSpecList.add(colSpec); return this; } public NonogramSpecBuilder addRow(Integer... rowSpec) { rowSpecList.add(rowSpec); return this; } public int [][][] build() { if(size != colSpecList.size()) { throw new IllegalStateException("Some columns not specified, column size=" + colSpecList.size() + ", expected " + size); } if(size != rowSpecList.size()) { throw new IllegalStateException("Some rows not specified, row size=" + rowSpecList.size() + ", expected " + size); } int [][][] gameSpec = new int[2][size][size]; for(int c = 0; c < colSpecList.size(); c++) { gameSpec[0][c] = convertToIntArray(colSpecList.get(c)); } for(int r = 0; r < rowSpecList.size(); r++) { gameSpec[1][r] = convertToIntArray(rowSpecList.get(r)); } return gameSpec; } private int[] convertToIntArray(Integer[] integers) { int [] dest = new int[integers.length]; for(int i = 0; i < dest.length; i++) { dest[i] = integers[i]; } return dest; } } }
package com.codeborne.selenide; import org.openqa.selenium.By; import static com.codeborne.selenide.impl.Quotes.escape; public class Selectors { /** * Find element CONTAINING given text (as a substring) * * NB! It seems that Selenium WebDriver does not support i18n characters in XPath :( * * @param elementText Text to search inside element * @return standard selenium By criteria */ public static By withText(String elementText) { return By.xpath(".//*/text()[contains(normalize-space(.), " + escape.quotes(elementText) + ")]/parent::*"); } /** * Find element that has EXACTLY this text * * NB! It seems that Selenium WebDriver does not support i18n characters in XPath :( * * @param elementText Text that searched element should have * @return standard selenium By criteria */ public static By byText(String elementText) { return By.xpath(".//*/text()[normalize-space(.) = " + escape.quotes(elementText) + "]/parent::*"); } /** * Find elements having attribute with given value. * * Seems to work incorrectly if attribute name contains dash, for example: <option data-mailServerId="123"></option> * * @param attributeName name of attribute, should not be empty or null * @param attributeValue value of attribute, should not contain both apostrophes and quotes * @return standard selenium By criteria */ public static By byAttribute(String attributeName, String attributeValue) { /** * Synonym for #byAttribute * * Seems to work incorrectly in HtmlUnit and PhantomJS if attribute name contains dash (e.g. "data-mailServerId") */ public static By by(String attributeName, String attributeValue) { return byAttribute(attributeName, attributeValue); } /** * Find element with given title ("title" attribute) */ public static By byTitle(String title) { return byAttribute("title", title); } public static By byValue(String value) { return byAttribute("value", value); } }
package my.ostrea.blog; import my.ostrea.blog.configurations.WebSecurityConfig; import my.ostrea.blog.models.ArticleRepository; import my.ostrea.blog.models.MyUser; import my.ostrea.blog.models.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.servlet.Filter; import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = BlogApplication.class) @WebAppConfiguration public class BlogApplicationTests { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .apply(springSecurity()) .build(); } @Test public void accessingStartPageAsAnonymousShouldReturnViewNamedIndexAndModelWithZeroAttributes() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(model().attributeDoesNotExist("articles")); } @Test @WithUserDetails("test") public void accessingStartPageAsLoggedUserShouldReturnViewNamedIndexAndModelWithOneAttribute() throws Exception { mockMvc.perform( get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(model().attributeExists("articles")); } @Test public void accessingUsernamePageAsAnonymousShouldRedirectToLoginPage() throws Exception { mockMvc.perform(get("/test")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("**/login")); } @Test @WithMockUser("userForTests") public void accessingUsernamePageAsLoggedUserIfUsernameIsNotLoggedUsernameShouldShowIndexViewWithModelWithOneAttr() throws Exception { mockMvc.perform(get("/admin")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(model().attributeExists("articles")); } @Test @WithMockUser("userForTests") public void accessingNotExistingUsernamePageAsLoggedUserShouldShowIndexViewWithModelWithZeroAttr() throws Exception { mockMvc.perform(get("/not_existing_user")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(model().attributeDoesNotExist("articles")); } @Test @WithUserDetails("test") public void accessingYourOwnUsernamePageAsLoggedUserShouldRedirectToIndex() throws Exception { mockMvc.perform(get("/test")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); } }
/** * Created Dec 20, 2007 */ package com.crawljax.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; import com.crawljax.core.TagAttribute; import com.crawljax.core.TagElement; import com.crawljax.core.configuration.CrawljaxConfiguration; import com.crawljax.core.configuration.CrawljaxConfigurationReader; /** * @author mesbah * @version $Id$ */ public final class PropertyHelper { private static final Logger LOGGER = Logger.getLogger(PropertyHelper.class.getName()); private static CrawljaxConfigurationReader crawljaxConfiguration; private static String projectRelativePath = "project.path.relative"; private static String projectRelativePathValue = ""; private static String outputFolderName = "output.path"; private static String outputFolder = ""; private static String genFilepath = "generated.pages.filepath"; private static String siteUrl = "site.url"; private static String siteIndexablePath = "site.indexable.path"; private static String baseUrl = "site.base.url"; private static String crawlDepth = "crawl.depth"; private static String crawlMaxStates = "crawl.max.states"; private static String crawlMaxTime = "crawl.max.runtime"; private static String crawlThrehold = "crawl.threshold"; private static String robotEvents = "robot.events"; private static String crawlTags = "crawl.tags"; private static String crawlExludeTags = "crawl.tags.exclude"; private static String crawlFilterAttributes = "crawl.filter.attributes"; private static String crawlNumberOfThreads = "crawl.numberOfThreads"; private static String hibernateProperties = "hibernate.properties"; private static String hibernatePropertiesValue = "hibernate.properties"; private static String crawlManualEnterForm = "crawl.forms.manual"; private static String crawlFormRandomInput = "crawl.forms.randominput"; private static int crawlFormRandomInputValue = 1; private static String formProperties = "forms.properties"; private static int crawlManualEnterFormValue = 1; private static String formPropertiesValue = "forms.properties"; private static String browser = "browser"; private static String crawlWaitReload = "crawl.wait.reload"; private static String crawlWaitEvent = "crawl.wait.event"; private static Configuration config; private static String hibernateSchema = "hibernate.hbm2ddl.auto"; private static String hibernateSchemaValue; private static String useDatabase = "database.use"; private static int useDatabaseValue = 0; // if each candidate clickable should be clicked only once private static String clickOnce = "click.once"; private static int clickOnceValue = 1; private static int testInvariantsWhileCrawlingValue = 1; private static String debugVariables = "reportbuilder.debugvariables"; private static List<String> debugVariablesValues; /* event handlers */ private static String detectEventHandlers = "eventHandlers.detect"; private static int detectEventHandlersValue = 1; private static String supportDomEvents = "eventHandlers.supportDomEvents"; private static int supportDomEventsValue = 1; private static String supportAddEvents = "eventHandlers.supportAddEvents"; private static int supportAddEventsValue = 1; private static String supportJQuery = "eventHandlers.supportJQuery"; private static int supportJQueryValue = 1; private static String siteUrlValue; private static String genFilepathValue = "target/generated-sources/"; private static String siteIndexablePathValue; private static String baseUrlValue; private static int crawlDepthValue; private static double crawlThreholdValue; private static List<String> robotEventsValues; private static List<String> crawlTagsValues; private static List<String> crawlFilterAttributesValues; private static List<TagElement> crawlTagElements = new ArrayList<TagElement>(); private static List<TagElement> crawlExcludeTagElements = new ArrayList<TagElement>(); private static List<String> atusaPluginsValues; private static int crawlMaxStatesValue = 0; private static int crawlMaxTimeValue = 0; private static String proxyEnabled = "proxy.enabled"; private static int proxyEnabledValue = 0; private static int domTidyValue = 0; private static int crawNumberOfThreadsValue = 1; private static String seleniumTestsuitePath = "selenium.testsuite.path"; private static String seleniumTestsuitePathValue; private static String maxHistorySizeText = "history.maxsize"; private static int maxHistorySize; private static String propertiesFileName; /** * default is IE. */ private static String browserValue = "ie"; private static int crawlWaitReloadValue; private static int crawlWaitEventValue; private PropertyHelper() { } /** * @param propertiesFile * thie properties file. * @throws ConfigurationException * if configuration fails. */ public static void init(String propertiesFile) throws ConfigurationException { PropertyHelper.propertiesFileName = propertiesFile; crawljaxConfiguration = null; init(new PropertiesConfiguration(propertiesFile)); } /** * Initialize property helper with a CrawljaxConfiguration instance. * * @param crawljaxConfiguration * The CrawljaxConfiguration instance. * @throws ConfigurationException * On error. */ public static void init(CrawljaxConfiguration crawljaxConfiguration) throws ConfigurationException { PropertyHelper.crawljaxConfiguration = new CrawljaxConfigurationReader(crawljaxConfiguration); if (PropertyHelper.crawljaxConfiguration.getConfiguration() == null) { throw new ConfigurationException("Configuration cannot be null!"); } init(PropertyHelper.crawljaxConfiguration.getConfiguration()); } private static void init(Configuration configuration) throws ConfigurationException { config = configuration; /* reset crawltagelements */ crawlTagElements = new ArrayList<TagElement>(); if (config.containsKey(outputFolderName)) { outputFolder = getProperty(outputFolderName); } projectRelativePathValue = getProperty(projectRelativePath); siteUrlValue = getProperty(siteUrl); genFilepathValue = getProperty(genFilepath); siteIndexablePathValue = getProperty(siteIndexablePath); baseUrlValue = getProperty(baseUrl); crawlDepthValue = getPropertyAsInt(crawlDepth); crawNumberOfThreadsValue = getPropertyAsInt(crawlNumberOfThreads); // crawlThreholdValue = getPropertyAsDouble(crawlThrehold); robotEventsValues = getPropertyAsList(robotEvents); crawlTagsValues = getPropertyAsList(crawlTags); crawlFilterAttributesValues = getPropertyAsList(crawlFilterAttributes); browserValue = getProperty(browser); crawlWaitReloadValue = getPropertyAsInt(crawlWaitReload); crawlWaitEventValue = getPropertyAsInt(crawlWaitEvent); crawlMaxStatesValue = getPropertyAsInt(crawlMaxStates); crawlMaxTimeValue = getPropertyAsInt(crawlMaxTime); // crawlManualEnterFormValue = // getPropertyAsInt(crawlManualEnterForm); formPropertiesValue = getProperty(formProperties); if (config.containsKey(crawlFormRandomInput)) { crawlFormRandomInputValue = getPropertyAsInt(crawlFormRandomInput); } hibernatePropertiesValue = getProperty(hibernateProperties); useDatabaseValue = getPropertyAsInt(useDatabase); if (config.containsKey(clickOnce)) { clickOnceValue = getPropertyAsInt(clickOnce); } debugVariablesValues = getPropertyAsList(debugVariables); setTagElements(); setTagExcludeElements(); if (config.containsKey(proxyEnabled)) { proxyEnabledValue = getPropertyAsInt(proxyEnabled); } if (config.containsKey(seleniumTestsuitePath)) { seleniumTestsuitePathValue = getProperty(seleniumTestsuitePath); } if (config.containsKey(maxHistorySizeText)) { maxHistorySize = getPropertyAsInt(maxHistorySizeText); } hibernateSchemaValue = getProperty(hibernateSchema); if (!checkProperties()) { LOGGER.error("Check the properties!"); throw new ConfigurationException("Check the properties!"); } } private static void setTagElements() { for (String text : getPropertyAsList(crawlTags)) { TagElement tagElement = parseTagElements(text); if (tagElement != null) { crawlTagElements.add(tagElement); } } } private static void setTagExcludeElements() { for (String text : getPropertyAsList(crawlExludeTags)) { TagElement tagElement = parseTagElements(text); if (tagElement != null) { crawlExcludeTagElements.add(tagElement); } } } /** * @param property * the property. * @return the value as string. */ public static String getProperty(String property) { return config.getString(property); } /** * Check all the properties. * * @return true if all properties are set. */ private static boolean checkProperties() { if (isEmpty(siteUrlValue)) { LOGGER.error("Property " + siteUrl + " is not set."); return false; } /* * if (isEmpty(genFilepathValue)) { LOGGER.error("Property " + genFilepath + * " is not set."); return false; } */ if (isEmpty("" + crawlDepthValue)) { LOGGER.error("Property " + crawlDepth + " is not set."); return false; } /* * if (isEmpty("" + crawlThreholdValue)) { LOGGER.error("Property " + crawlThrehold + * " is not set."); return false; } */ if (isEmpty(browserValue) && getCrawljaxConfiguration() == null) { LOGGER.error("Property " + browser + " is not set."); return false; } if (isEmpty("" + crawlWaitReloadValue)) { LOGGER.error("Property " + crawlWaitReload + " is not set."); return false; } if (isEmpty("" + crawlWaitEventValue)) { LOGGER.error("Property " + crawlWaitEvent + " is not set."); return false; } try { if (genFilepathValue != null && !genFilepathValue.equals("")) { Helper.directoryCheck(genFilepathValue); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); return false; } if (isEmpty(hibernateSchemaValue)) { LOGGER.error("Property " + hibernateSchema + " is not set."); return false; } try { // make sure the report is written to an existing path if (seleniumTestsuitePathValue != null) { Helper.directoryCheck(seleniumTestsuitePathValue); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); return false; } return true; } private static boolean isEmpty(String property) { if ((property == null) || "".equals(property)) { return true; } return false; } /** * @param property * name of the property. * @return the value as an int. */ public static int getPropertyAsInt(String property) { return config.getInt(property); } /** * @param property * the property. * @return the value as a double. */ public static double getPropertyAsDouble(String property) { return config.getDouble(property); } /** * @param property * the property. * @return the values as a List. */ public static List<String> getPropertyAsList(String property) { List<String> result = new ArrayList<String>(); String[] array = config.getStringArray(property); for (int i = 0; i < array.length; i++) { result.add(array[i]); } return result; } /** * @return A reader for the CrawljaxConfiguration instance. */ public static CrawljaxConfigurationReader getCrawljaxConfiguration() { return crawljaxConfiguration; } /** * @return The project relative path. */ public static String getProjectRelativePathValue() { return projectRelativePathValue; } /** * @return The output folder with a trailing slash. */ public static String getOutputFolder() { return Helper.addFolderSlashIfNeeded(outputFolder); } /** * @return the genFilepath. */ public static String getGenFilepath() { return genFilepath; } /** * @return the siteUrl */ public static String getSiteUrl() { return siteUrl; } /** * @return the siteIndexablePath */ public static String getSiteIndexablePath() { return siteIndexablePath; } /** * @return the baseUrl */ public static String getBaseUrl() { return baseUrl; } /** * @return the crawlDepth */ public static String getCrawlDepth() { return crawlDepth; } /** * @return the crawlThrehold */ public static String getCrawlThrehold() { return crawlThrehold; } /** * @return the robotEvents */ public static String getRobotEvents() { return robotEvents; } /** * @return the crawlTags */ public static String getCrawlTags() { return crawlTags; } /** * @return the browser */ public static String getBrowser() { return browser; } /** * @return the config */ public static Configuration getConfig() { return config; } /** * @return the siteUrlValue */ public static String getSiteUrlValue() { return siteUrlValue; } /** * @return the genFilepathValue */ public static String getGenFilepathValue() { return genFilepathValue; } /** * @return the siteIndexablePathValue */ public static String getSiteIndexablePathValue() { return siteIndexablePathValue; } /** * @return the baseUrlValue */ public static String getBaseUrlValue() { return baseUrlValue; } /** * @return the crawlDepthValue */ public static int getCrawlDepthValue() { return crawlDepthValue; } /** * @return the crawlThreholdValue */ public static double getCrawlThreholdValue() { return crawlThreholdValue; } /** * @return the robotEventsValues */ public static List<String> getRobotEventsValues() { return robotEventsValues; } /** * @return the crawlTagsValues */ public static List<String> getCrawlTagsValues() { return crawlTagsValues; } /** * @return the crawlFilterAttributesValues */ public static List<String> getCrawlFilterAttributesValues() { return crawlFilterAttributesValues; } /** * @return the browserValue */ public static String getBrowserValue() { return browserValue; } /** * @return the crawlWaitReloadValue */ public static int getCrawlWaitReloadValue() { return crawlWaitReloadValue; } /** * @return the crawlWaitEventValue */ public static int getCrawlWaitEventValue() { return crawlWaitEventValue; } /** * @return TODO: DOCUMENT ME! */ public static String getCrawlMaxStates() { return crawlMaxStates; } /** * @return TODO: DOCUMENT ME! */ public static String getCrawlMaxTime() { return crawlMaxTime; } /** * @return TODO: DOCUMENT ME! */ public static int getCrawlMaxStatesValue() { return crawlMaxStatesValue; } /** * @return the max value for crawling time. */ public static int getCrawlMaxTimeValue() { return crawlMaxTimeValue; } /** * Parses the tag elements. * * @param text * The string containing the tag elements. * @return The tag element. */ public static TagElement parseTagElements(String text) { if (text.equals("")) { return null; } TagElement tagElement = new TagElement(); Pattern pattern = Pattern.compile("\\w+:\\{(\\w+=?(\\-*\\s*[\\w%]\\s*)+\\;?\\s?)*}" + "(\\[\\w+\\])?"); Pattern patternTagName = Pattern.compile("\\w+"); Pattern patternAttributes = Pattern.compile("\\{(\\w+=(\\-*\\s*[\\w%]\\s*)+\\;?\\s?)*}"); Pattern patternAttribute = Pattern.compile("(\\w+)=((\\-*\\s*[\\w%]\\s*)+)"); Pattern patternId = Pattern.compile("(\\[)(\\w+)(\\])"); Matcher matcher = pattern.matcher(text); if (matcher.matches()) { String substring = matcher.group(); matcher = patternTagName.matcher(substring); if (matcher.find()) { tagElement.setName(matcher.group().trim()); } matcher = patternAttributes.matcher(substring); // attributes if (matcher.find()) { String attributes = (matcher.group()); // parse attributes matcher = patternAttribute.matcher(attributes); while (matcher.find()) { String name = matcher.group(1).trim(); String value = matcher.group(2).trim(); tagElement.getAttributes().add(new TagAttribute(name, value)); } } matcher = patternId.matcher(substring); if (matcher.find()) { String id = matcher.group(2); tagElement.setId(id); } } return tagElement; } /** * @param args * TODO: DOCUMENT ME! */ public static void main(String[] args) { String text = "div:{class=expandable-hitarea}"; TagElement tagElement = parseTagElements(text); System.out.println("tagname: " + tagElement.getName()); for (TagAttribute attr : tagElement.getAttributes()) { System.out.println("attrName: " + attr.getName() + " value: " + attr.getValue()); } /* * String text = * "a:{attr=value}, div:{class=aha; id=room}, span:{}, div:{class=expandable-hitarea}" ; try * { PropertyHelper.init("src/test/resources/testcrawljax.properties"); } catch * (ConfigurationException e) { System.out.println(e.getMessage()); } List<String> tList = * getPropertyAsList(crawlTags); for (String e : tList) { System.out.println(e); TagElement * tagElement = parseTagElements(e); System.out.println("tagname: " + tagElement.getName()); * for (TagAttribute attr : tagElement.getAttributes()) { System.out.println("attrName: " + * attr.getName() + " value: " + attr.getValue()); } } */ /* * for (String t : getPropertyAsList(crawlTags)) { TagElement tagElement = * parseTagElements(t); if (tagElement != null) { crawlTagElements.add(tagElement); } } */ /* * TagElement tagElement = parseTagElements(text); System.out.println("tagname: " + * tagElement.getName()); for (TagAttribute attr : tagElement.getAttributes()) { * System.out.println( "attrName: " + attr.getName() + " value: " + attr.getValue()); } */ } /** * @return TODO: DOCUMENT ME! */ public static List<TagElement> getCrawlTagElements() { return crawlTagElements; } /** * @return TODO: DOCUMENT ME! */ public static List<TagElement> getCrawlExcludeTagElements() { return crawlExcludeTagElements; } /** * @return The hibernate properties filename. */ public static String getHibernatePropertiesValue() { return hibernatePropertiesValue; } /** * @return the crawlManualEnterForm */ public static String getCrawlManualEnterForm() { return crawlManualEnterForm; } /** * @return the crawlManualEnterFormValue */ public static boolean getCrawlManualEnterFormValue() { return crawlManualEnterFormValue == 1; } /** * @return The form properties. */ public static String getFormPropertiesValue() { return formPropertiesValue; } /** * @return the crawlFormRandomInputValue */ public static boolean getCrawlFormWithRandomValues() { return crawlFormRandomInputValue == 1; } /** * @return TODO: DOCUMENT ME! */ public static List<String> getAtusaPluginsValues() { return atusaPluginsValues; } /** * @return Whether to use the proxy. */ public static boolean getProxyEnabledValue() { return proxyEnabledValue == 1; } /** * @return the useDatabaseValue */ public static boolean useDatabase() { return useDatabaseValue == 1; } /** * @return Whether to tidy up the dom. */ public static boolean getDomTidyValue() { return domTidyValue == 1; } // selenium /** * Return the path in which the Selenium report should be created. * * @return the genFilepathValue */ public static String getSeleniumTestsuitePathValue() { return seleniumTestsuitePathValue; } /** * Return the max history size. * * @return Maximum history size. */ public static int getMaxHistorySize() { return maxHistorySize; } /** * Returns the hibernate schema name. * * @return The name. */ public static String getHibernateSchemaValue() { return hibernateSchemaValue; } /** * @return the testInvariantsWhileCrawlingValue */ public static boolean getTestInvariantsWhileCrawlingValue() { return testInvariantsWhileCrawlingValue == 1; } /** * @return the debugVariablesValues */ public static List<String> getDebugVariablesValues() { return debugVariablesValues; } /** * @return the detectEventHandlers */ public static String getDetectEventHandlers() { return detectEventHandlers; } /** * @return the detectEventHandlersValue */ public static boolean getDetectEventHandlersValue() { return detectEventHandlersValue == 1; } /** * @return the supportDomEvents */ public static String getSupportDomEvents() { return supportDomEvents; } /** * @return the supportDomEventsValue */ public static boolean getSupportDomEventsValue() { return supportDomEventsValue == 1; } /** * @return the supportAddEvents */ public static String getSupportAddEvents() { return supportAddEvents; } /** * @return the supportAddEventsValue */ public static boolean getSupportAddEventsValue() { return supportAddEventsValue == 1; } /** * @return the supportJQuery */ public static String getSupportJQuery() { return supportJQuery; } /** * @return the supportJQueryValue */ public static boolean getSupportJQueryValue() { return supportJQueryValue == 1; } /** * Get filename of the properties file in use. * * @return Filename. */ public static String getPropertiesFileName() { return propertiesFileName; } /** * @return the crawNumberOfThreadsValue */ public static final int getCrawNumberOfThreadsValue() { return crawNumberOfThreadsValue; } /** * @return if each candidate clickable should be clicked only once. */ public static boolean getClickOnceValue() { return clickOnceValue == 1; } }
package org.commcare.test.utilities; import org.commcare.modern.session.SessionWrapper; import org.commcare.core.parse.ParseUtils; import org.commcare.util.engine.CommCareConfigEngine; import org.commcare.util.mocks.MockUserDataSandbox; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.FormIndex; import org.javarosa.core.services.storage.IStorageIndexedFactory; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.util.DummyIndexedStorageUtility; import org.javarosa.core.test.FormParseInit; import org.javarosa.core.util.externalizable.LivePrototypeFactory; import org.javarosa.form.api.FormEntryController; public class MockApp { private final SessionWrapper mSessionWrapper; private final String APP_BASE; /** * Creates and initializes a mockapp that is located at the provided Java Resource path. * * @param resourcePath The resource path to a an app template. Needs to contain a leading and * trailing slash, like /path/app/ */ public MockApp(String resourcePath) throws Exception { if(!(resourcePath.startsWith("/") && resourcePath.endsWith("/"))) { throw new IllegalArgumentException("Invalid resource path for a mock app " + resourcePath); } APP_BASE = resourcePath; final LivePrototypeFactory mPrototypeFactory = setupStaticStorage(); MockUserDataSandbox mSandbox = new MockUserDataSandbox(mPrototypeFactory); CommCareConfigEngine mEngine = new CommCareConfigEngine(mPrototypeFactory); mEngine.setStorageFactory(new IStorageIndexedFactory() { @Override public IStorageUtilityIndexed newStorage(String name, Class type) { return new DummyIndexedStorageUtility(type, mPrototypeFactory); } }); mEngine.installAppFromReference("jr://resource" + APP_BASE + "profile.ccpr"); mEngine.initEnvironment(); ParseUtils.parseIntoSandbox(this.getClass().getResourceAsStream(APP_BASE + "user_restore.xml"), mSandbox); //If we parsed in a user, arbitrarily log one in. mSandbox.setLoggedInUser(mSandbox.getUserStorage().read(0)); mSessionWrapper = new SessionWrapper(mEngine.getPlatform(), mSandbox); } /** * Loads the provided form and properly initializes external data instances, * such as the casedb and commcare session. */ public FormEntryController loadAndInitForm(String formFileInApp) { FormParseInit fpi = new FormParseInit(APP_BASE + formFileInApp); FormEntryController fec = fpi.getFormEntryController(); fec.jumpToIndex(FormIndex.createBeginningOfFormIndex()); FormDef fd = fpi.getFormDef(); // run initialization to ensure xforms-ready event and binds are // triggered. fd.initialize(true, mSessionWrapper.getIIF()); return fec; } private static LivePrototypeFactory setupStaticStorage() { return new LivePrototypeFactory(); } public SessionWrapper getSession() { return mSessionWrapper; } }
package com.extjs.selenium.grid; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebDriverConfig; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.table.Cell; import org.apache.log4j.Logger; public class GridCell extends Cell { private static final Logger logger = Logger.getLogger(GridCell.class); public GridCell() { setRenderMillis(200); setClassName("GridCell"); } public GridCell(WebLocator container) { this(); setContainer(container); } public GridCell(WebLocator container, String elPath) { this(container); setElPath(elPath); } public GridCell(WebLocator container, int columnIndex) { this(container);
package org.opennars.metrics; import org.opennars.core.NALTest; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Computes the metrics of NAL-tests. * * Metrics are numeric values which indicate how fast NARS could solve problems */ public class NalTestMetrics { public static double computeMetric(final Map<String, List<Double>> scores) { double metric = 0; // compute median of (valid) samples for (List<Double> iValues : scores.values()) { // remove infinities because they indicate failed tests and would mess up the metric final List<Double> valuesWithoutInfinities = removeInfinities(iValues); final double medianOfThisTest = calcMedian(valuesWithoutInfinities); metric += medianOfThisTest; } // average of all medians should be fine metric /= scores.values().size(); return metric; } // helper public static List<Double> removeInfinities(final List<Double> values) { List<Double> result = new ArrayList<>(); for (double iValue : values) { if (iValue != Double.POSITIVE_INFINITY) { result.add(iValue); } } return result; } // helper public static double calcMedian(final List<Double> values) { return values.get(values.size()/2); } public static void main(String[] args) { // number of samples was guessed and not computed with probability theory // TODO< maybe we need to compute it with probability theory to make sure that we test enough and not to much for a given error margin > int numberOfSamples = 50; // we are only in multistep problems interested NALTest.directories = new String[]{"/nal/multi_step/", "/nal/application/"}; NALTest.numberOfSamples = numberOfSamples; NALTest.runTests(NALTest.class); final double metric = computeMetric(NALTest.scores); System.out.println("metric=" + Double.toString(metric)); int debugHere = 5; } }
package org.apache.commons.lang; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; /** * Unit tests {@link org.apache.commons.lang.CharSetUtils}. * * @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a> * @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a> * @version $Id: CharSetUtilsTest.java,v 1.5 2003/03/20 02:50:42 ggregory Exp $ */ public class CharSetUtilsTest extends TestCase { public CharSetUtilsTest(String name) { super(name); } public static void main(String[] args) { TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite(CharSetUtilsTest.class); suite.setName("CharSetUtils Tests"); return suite; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testSqueeze() { assertEquals("squeeze(String,String[]) failed", "helo", CharSetUtils.squeeze("hello", new String[] {"el"})); assertEquals("squeeze(String,String[]) failed", "", CharSetUtils.squeeze("", new String[] {"el"})); assertEquals("squeeze(String,String[]) failed", "hello", CharSetUtils.squeeze("hello", new String[] {"e"})); assertEquals("squeeze(String,String[]) failed", "fofof", CharSetUtils.squeeze("fooffooff", new String[] {"of"})); assertEquals("squeeze(String,String[]) failed", "fof", CharSetUtils.squeeze("fooooff", new String[] {"fo"})); } public void testCount() { assertEquals("count(String,String[]) failed", 3, CharSetUtils.count("hello", new String[] {"el"})); assertEquals("count(String,String[]) failed", 0, CharSetUtils.count("", new String[] {"el"})); assertEquals("count(String,String[]) failed", 0, CharSetUtils.count("hello", new String[] {"x"})); assertEquals("count(String,String[]) failed", 2, CharSetUtils.count("hello", new String[] {"e-i"})); assertEquals("count(String,String[]) failed", 5, CharSetUtils.count("hello", new String[] {"a-z"})); assertEquals("count(String,String[]) failed", 0, CharSetUtils.count("hello", new String[] {""})); } public void testDelete() { assertEquals("delete(String,String[]) failed", "ho", CharSetUtils.delete("hello", new String[] {"el"})); assertEquals("delete(String,String[]) failed", "", CharSetUtils.delete("hello", new String[] {"elho"})); assertEquals("delete(String,String[]) failed", "hello", CharSetUtils.delete("hello", new String[] {""})); assertEquals("delete(String,String[]) failed", "", CharSetUtils.delete("hello", new String[] {"a-z"})); assertEquals("delete(String,String[]) failed", "", CharSetUtils.delete("----", new String[] {"-"})); assertEquals("delete(String,String[]) failed", "heo", CharSetUtils.delete("hello", new String[] {"l"})); } }
package com.imcode.imcms.config; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaDialect; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = {"com.imcode.imcms.mapping.jpa", "com.imcode.imcms.imagearchive.entity"}) public class DBConfig { @Autowired private Environment env; // TODO just another way to obtain properties private String jdbcUrl;*//* /*@Value("${JdbcUrl}") */ @Bean public BasicDataSource dataSource() { BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(env.getProperty("JdbcDriver")); basicDataSource.setUrl(env.getProperty("JdbcUrl")); basicDataSource.setUsername(env.getProperty("User")); basicDataSource.setPassword(env.getProperty("Password")); basicDataSource.setTestOnBorrow(true); basicDataSource.setValidationQuery("select 1"); basicDataSource.setDefaultAutoCommit(false); basicDataSource.setMaxTotal(20); basicDataSource.setMaxTotal(Integer.parseInt(env.getProperty("MaxConnectionCount"))); return basicDataSource; } // Wasn't in previous config @Bean public BasicDataSource dataSourceWithAutoCommit() { BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(env.getProperty("JdbcDriver")); basicDataSource.setUrl(env.getProperty("JdbcUrl")); basicDataSource.setUsername(env.getProperty("User")); basicDataSource.setPassword(env.getProperty("Password")); basicDataSource.setTestOnBorrow(true); basicDataSource.setValidationQuery("select 1"); basicDataSource.setDefaultAutoCommit(false); basicDataSource.setMaxTotal(20); basicDataSource.setMaxTotal(Integer.parseInt(env.getProperty("MaxConnectionCount"))); basicDataSource.setDefaultAutoCommit(true); return basicDataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setDataSource(dataSource); entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); entityManagerFactory.setJpaDialect(new HibernateJpaDialect()); entityManagerFactory.setPackagesToScan("com.imcode.imcms.imagearchive", "com.imcode.imcms.mapping.jpa"); entityManagerFactory.setPersistenceUnitName("com.imcode.imcms"); entityManagerFactory.setJpaPropertyMap(hibernateJpaProperties()); return entityManagerFactory; } private Map<String, ?> hibernateJpaProperties() { HashMap<String, String> properties = new HashMap<>(); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect"); properties.put("hibernate.format_sql", "true"); properties.put("hibernate.use_sql_comments", "true"); properties.put("hibernate.show_sql", "false"); //TODO: Some additional properties for hibernate // properties.put("hibernate.hbm2ddl.auto", "create"); // properties.put("hibernate.show_sql", "false"); // properties.put("hibernate.format_sql", "false"); // properties.put("hibernate.hbm2ddl.import_files", "insert-data.sql"); // properties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy"); // properties.put("hibernate.c3p0.min_size", "2"); // properties.put("hibernate.c3p0.max_size", "5"); // properties.put("hibernate.c3p0.timeout", "300"); // 5mins return properties; } @Bean public JpaTransactionManager transactionManager(EntityManagerFactory emf) { final JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(); jpaTransactionManager.setEntityManagerFactory(emf); return jpaTransactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } }
package com.jblur.acme_client; import com.beust.jcommander.Parameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class Parameters { public final static String COMMAND_REGISTER = "register"; public final static String COMMAND_GET_AGREEMENT_URL = "get-agreement-url"; public final static String COMMAND_UPDATE_AGREEMENT = "update-agreement"; public final static String COMMAND_ADD_EMAIL = "add-email"; public final static String COMMAND_DEACTIVATE_ACCOUNT = "deactivate-account"; public final static String COMMAND_AUTHORIZE_DOMAINS = "authorize-domains"; public final static String COMMAND_DEACTIVATE_DOMAIN_AUTHORIZATION = "deactivate-domain-authorization"; public final static String COMMAND_DOWNLOAD_CHALLENGES = "download-challenges"; public final static String COMMAND_VERIFY_DOMAINS = "verify-domains"; public final static String COMMAND_GENERATE_CERTIFICATE = "generate-certificate"; public final static String COMMAND_DOWNLOAD_CERTIFICATES = "download-certificates"; public final static String COMMAND_REVOKE_CERTIFICATE = "revoke-certificate"; public final static String COMMAND_RENEW_CERTIFICATE = "renew-certificate"; public final static String AUTHORIZATION_URI_LIST = "authorization_uri_list"; public final static String CERTIFICATE_URI_LIST = "certificate_uri_list"; public final static String CHALLENGE_HTTP01 = "HTTP01"; public final static String CHALLENGE_DNS01 = "DNS01"; public final static StringBuilder MAIN_USAGE = new StringBuilder(); private static final Logger LOG = LoggerFactory.getLogger(Parameters.class); static { MAIN_USAGE.append(" MAIN_USAGE.append("Every time you run acme_client you must set the parameter command parameter '--command'\n"); MAIN_USAGE.append("Optional parameters for all commands are: --log-dir, --log-level, " + "--server-url, --with-agreement-update, --agreement-url\n"); MAIN_USAGE.append("For most of your commands you should specify working directory " + "for your account (--work-dir) but you can left it by default.\n"); MAIN_USAGE.append("Every command returns a JSON object which always contains either \"status\":\"ok\" or " + "\"status\":\"error\" and sometimes an additional information. " + "You should check your log file if you get \"status\":\"error\".\n"); MAIN_USAGE.append("\nBy default acme_client uses Letsencrypt's production server. I.e.:\n" + "'https://acme-v01.api.letsencrypt.org/directory'" + "\nIf you want to test the client then use a test server:\n" + "--server-url 'https://acme-staging.api.letsencrypt.org/directory'\n" + "If you use Letsencrypt's production server for testing you can reach limits " + "which are set by Letsencrypt (or your ACME provider).\n"); MAIN_USAGE.append("\nCommands:\n"); MAIN_USAGE.append("\n1) "+COMMAND_REGISTER+" - create a new account.\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --email\n"); MAIN_USAGE.append("\n2) "+COMMAND_GET_AGREEMENT_URL+" - return a JSON object with 'agreement_ur' key where value " + "is the most up to date agreement. You must accept agreement if you want to use a service.\n" + "This command include `agreement_url` into JSON response " + "(I.e. {\"status\":\"ok\", \"agreement_url\":\"https: "\tRequires parameters: --account-key\n"); MAIN_USAGE.append("\n3) "+COMMAND_UPDATE_AGREEMENT+" - accept agreement. If you do not specify " + "'--agreement-url' you will automatically agree with the newest agreement.\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --agreement-url\n"); MAIN_USAGE.append("\n4) "+COMMAND_ADD_EMAIL+" - add email to your account (some providers can recover your email" + " if you lose your account private key).\n" + "\tRequires parameters: --account-key, --email\n"); MAIN_USAGE.append("\n5) "+COMMAND_DEACTIVATE_ACCOUNT+" - deactivate your account\n" + "\tRequires parameters: --account-key\n"); MAIN_USAGE.append("\n6) "+COMMAND_AUTHORIZE_DOMAINS+" authorize specified domains. You must specify all " + "domains which you use in CSR (i.e. main domain and alternative domain names).\n" + "If you get \"status\":\"error\" this command may include domains which were not authorized " + "(\"failed_domains\":[\"example.com\", \"blog.example.com\"]). You can see the reason in your log file.\n" + "\tRequires parameters: --account-key, --domain\n" + "\tOptional parameters: --challenge-type\n"); MAIN_USAGE.append("\n7) "+COMMAND_DEACTIVATE_DOMAIN_AUTHORIZATION+" - deactive domain authorization for specific " + "domain address (or for all if not specified) if you want to remove/sell your domain addresses.\n" + "If you get \"status\":\"error\" this command may include domains which were not deactivated " + "(\"failed_domains\":[\"example.com\", \"blog.example.com\"]). You can see the reason in your log file.\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --domain\n" + "\tMust have a file in working dir: authorization_uri_list\n"); MAIN_USAGE.append("\n8) "+COMMAND_DOWNLOAD_CHALLENGES+" - Download challenges from your authorizations.\n" + "If you get \"status\":\"error\" this command may include authorizations' locations from " + "which challenges wasn't been downloaded (\"failed_authorizations_to_download" + "\":[\"https: "\tRequires parameters: --account-key\n" + "\tOptional parameters: --domain, --challenge-type\n" + "\tMust have file in working dir: authorization_uri_list\n"); MAIN_USAGE.append("\n9) "+COMMAND_VERIFY_DOMAINS+" - Check your challenges and verify your domains.\n" + "If you get \"status\":\"error\" this command may include domains which were not verified " + "(\"failed_domains\":[\"example.com\", \"blog.example.com\"]). You can see the reason in your log file.\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --domain\n" + "\tMust have a file in working dir: authorization_uri_list\n"); MAIN_USAGE.append("\n10) "+COMMAND_GENERATE_CERTIFICATE+" - Generate new certificate.\n" + "\tRequires parameters: --account-key, --csr\n" + "\tOptional parameters: --cert-dir\n"); MAIN_USAGE.append("\n11) "+COMMAND_DOWNLOAD_CERTIFICATES+" - Download your certificates which you have created earlier. " + "If you specify '--newest-only' then you will download only newest certificate. Without that parameter " + "you will download all certificates sorted by expiration date (i.e. cert_0.pem is the newest " + "and cert_15.pem is the oldest).\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --newest-only\n" + "\tMust have a file in working dir: certificate_uri_list\n"); MAIN_USAGE.append("\n12) "+COMMAND_REVOKE_CERTIFICATE+" - revoke certificates. You can revoke either all your " + "certificates or by time criteria. All certificates will be removed which are started after " + "'--from-time' and which will be expired till '--to-time'. " + "These parameters are written as GMT milliseconds.\n" + "If you get \"status\":\"error\" this command may include certificates' locations which were not " + "revoked (\"failed_certificates\":[\"https: "You can see the reason in your log file.\n" + "\tRequires parameters: --account-key\n" + "\tOptional parameters: --from-time, --to-time\n" + "\tMust have a file in working dir: certificate_uri_list\n"); MAIN_USAGE.append("\n13) "+COMMAND_RENEW_CERTIFICATE+" - Renew certificate either for existing CSR or for new CSR. " + "Will create a new certificate only if all your certificates will expire after '--max-expiration-time'. " + "'--max-expiration-time' is a time written in milliseconds " + "(By default it is 2592000000 which is equal to 30 days).\n" + "\tRequires parameters: --account-key, --csr\n" + "\tOptional parameters: --cert-dir, --max-expiration-time, --force.\n"); MAIN_USAGE.append("\n"); } @Parameter(names = "--help", help = true, description = "Show help.") private boolean help; @Parameter(names = { "--version", "-v" }, help = true, description = "Show version of the acme client.") private boolean version; @Parameter(names = "--newest-only", help = true, description = "If you want to download only the newest " + "certificate you can use this parameter. Otherwise you will download all your certificates.") private boolean newestOnly; @Parameter(names = {"--work-dir", "-w"}, description = "Working directory to place authorization information " + "and certificates information (i.e. files 'authorization_uri_list' and 'certificate_uri_list'). " + "This files are public but you have to keep them safe to not lose them. Otherwise you have to " + "contact your provider to recover your lost certificates (Or create new ones).") private String workDir = "/var/acme_work_dir/"; @Parameter(names = {"--account-key", "-a"}, description = "Your private key for account.") private String accountKey; @Parameter(names = {"--csr", "-c"}, description = "CSR file.") private String csr; @Parameter(names = {"--domain", "-d"}, description = "Domain addresses. Can be any count till providers " + "limits (I.e. Letsencrypt has 100 domains limit for one certificate).") private List<String> domains; @Parameter(names = {"--cert-dir"}, description = "Directory where generated certificates will be downloaded") private String certDir = this.workDir + "cert/"; @Parameter(names = {"--log-dir"}, description = "Directory for log files") private String logDir = "/var/log/acme/"; @Parameter(names = {"--well-known-dir"}, description = "Directory to place well-known files." + " All your well-known files must be accessible via link: http://${domain}/.well-known/acme-challenge/${token}" + " where ${token} is a name of a file and ${domain} is your domain name") private String wellKnownDir = this.workDir + "well_known/"; @Parameter(names = {"--dns-digests-dir"}, description = "Directory to place dns digest files") private String dnsDigestDir = this.workDir + "dns_digests/"; @Parameter(names = {"--email", "-e"}, description = "Email address to retrieve an account if you lost your " + "private key (If it is supported by your provider)") private String email; //acme://letsencrypt.org/staging - TEST @Parameter(names = {"--server-url", "-u"}, description = "Acme api URL. You can use debug api for example") private String acmeServerUrl = "https://acme-v01.api.letsencrypt.org/directory"; @Parameter(names = {"--agreement-url"}, description = "Url for agreement") private String agreementUrl; @Parameter(names = {"--max-expiration-time"}, description = "Set expiration time in milliseconds. " + "A certificate will be renewed only when your existed certificates will expire after max-expiration-time." + " By default it is 2592000000 milliseconds which is equal to 30 days. It means that when you call " + "'renew-certificate' command it will be renewed only if your certificate will expire in 30 days.") private long maxExpirationTime = 2592000000L; @Parameter(names = {"--log-level"}, description = "Log level. Can be one of the next: " + "'OFF' - without logs; " + "'ERROR' - only errors; " + "'WARN' - errors and warnings; " + "'INFO' - errors, warnings, information; " + "'DEBUG' - errors, warnings, information, debug; " + "'TRACE' - errors, warnings, information, debug, trace;") private String logLevel = "WARN"; @Parameter(names = {"--force"}, description = "Force renewal if you don't want to check expiration " + "time before renew. Works the same as 'generate-certificate' command") private boolean force; @Parameter(names = {"--one-dir-for-well-known"}, description = "By default well-known files will be placed " + "separately for each domain (in different directories). Set this parameter if you want to " + "generate all challenges in the same directory.") private boolean oneDirForWellKnown; @Parameter(names = {"--from-time"}, description = "When you revoke your certificates you can set this option. " + "It means that all certificates which are started from this date will be revoked (date in milliseconds GMT.)") private long fromTime = Long.MIN_VALUE; @Parameter(names = {"--to-time"}, description = "When you revoke your certificates you can set this option. " + "It means that all certificates which will expire till this date will be revoked (date in milliseconds GMT.)") private long toTime = Long.MAX_VALUE; @Parameter(names = {"--challenge-type"}, description = "Challenge type (supported: HTTP01, DNS01. Default: HTTP01)") private String challengeType = CHALLENGE_HTTP01; @Parameter(names = {"--with-agreement-update"}, description = "Automatically updates agreement to the newest. " + "Some times provider can change an agreement and you should update the agreement link manually. " + "(I.e. get an agreement url, read an agreement, update an agreement). If you want to automate this process " + "you can use this parameter with each command you are using. You shouldn't use this parameter if you " + "are not agree with a new agreement or if you use different commands very often.") private boolean withAgreementUpdate; @Parameter(names = {"--command"}, description = "Command to execute. Command can be on of the next commands: " + "register, get-agreement-url, update-agreement, add-email, deactivate-account, authorize-domains, " + "deactivate-domain-authorization, download-challenges, verify-domains, generate-certificate," + "download-certificates, revoke-certificate, renew-certificate. " + "Read below 'Main commands' section to know how to use these commands.") private String command; private boolean checkFile(String path, String errMsg) { if (path==null || !new File(path).isFile()) { LOG.error(errMsg); return false; } return true; } private boolean checkDir(String path, String errMsg) { if (path==null || !Files.isDirectory(Paths.get(path))) { LOG.error(errMsg); return false; } return true; } private boolean checkString(String str, String errMsg) { if (str == null || str.equals("")) { LOG.error(errMsg); return false; } return true; } private boolean checkAccountKey() { return checkFile(accountKey, "Your account key file doesn't exist: " + accountKey); } private boolean checkWorkDir() { return checkDir(workDir, "Your work directory doesn't exist: " + workDir); } private boolean checkCsr() { return checkFile(csr, "Your CSR file doesn't exist: " + csr); } private boolean checkDomains() { if (domains == null || domains.size() == 0) { LOG.error("You haven't provided any domain name"); return false; } return true; } private boolean checkCertDir() { return checkDir(certDir, "Your certificates' directory doesn't exist: " + certDir); } private boolean checkWellKnownDir() { return checkDir(wellKnownDir, "Your well-known directory doesn't exist: " + wellKnownDir); } private boolean checkDnsDigestsDir() { return checkDir(dnsDigestDir, "Your dns-digests directory doesn't exist: " + dnsDigestDir); } private boolean checkEmail() { return checkString(email, "You have to provide email address"); } private boolean checkAgreementUrl() { return checkString(agreementUrl, "You have to provide agreement url address"); } private boolean checkAuthorizationUriList() { return checkFile(Paths.get(workDir, AUTHORIZATION_URI_LIST).toString(), "Your authorization uri list file doesn't exists. Seems that it is either wrong working directory or " + "you haven't authorized your domains yet: " + Paths.get(workDir, AUTHORIZATION_URI_LIST).toString()); } private boolean checkCertificateUriList() { return checkFile(Paths.get(workDir, CERTIFICATE_URI_LIST).toString(), "Your certificate uri list file doesn't exists. Seems that it is either wrong working directory or " + "you haven't got your certificates yet: " + Paths.get(workDir, CERTIFICATE_URI_LIST).toString()); } private boolean checkChallengeType() { return challengeType.equalsIgnoreCase(CHALLENGE_HTTP01) || challengeType.equalsIgnoreCase(CHALLENGE_DNS01); } public boolean verifyRequirements() { if (getCommand() == null) { LOG.error("No command specified. You must specify a command to execute, use --help for a list of available commands."); return false; } boolean correct; switch (command) { case Parameters.COMMAND_REGISTER: correct = checkAccountKey(); break; case Parameters.COMMAND_GET_AGREEMENT_URL: correct = checkAccountKey(); break; case Parameters.COMMAND_UPDATE_AGREEMENT: correct = checkAccountKey(); break; case Parameters.COMMAND_ADD_EMAIL: correct = checkAccountKey() && checkEmail(); break; case Parameters.COMMAND_DEACTIVATE_ACCOUNT: correct = checkAccountKey(); break; case Parameters.COMMAND_AUTHORIZE_DOMAINS: correct = checkAccountKey() && checkDomains() && checkChallengeType() && checkWorkDir(); break; case Parameters.COMMAND_DEACTIVATE_DOMAIN_AUTHORIZATION: correct = checkAccountKey() && checkAuthorizationUriList(); break; case Parameters.COMMAND_DOWNLOAD_CHALLENGES: correct = checkAccountKey() && checkAuthorizationUriList(); break; case Parameters.COMMAND_VERIFY_DOMAINS: correct = checkAccountKey() && checkAuthorizationUriList(); break; case Parameters.COMMAND_GENERATE_CERTIFICATE: correct = checkAccountKey() && checkCsr() && checkWorkDir() && checkCertDir(); break; case Parameters.COMMAND_DOWNLOAD_CERTIFICATES: correct = checkAccountKey() && checkCertificateUriList(); break; case Parameters.COMMAND_REVOKE_CERTIFICATE: correct = checkAccountKey() && checkCertificateUriList(); break; case Parameters.COMMAND_RENEW_CERTIFICATE: correct = checkAccountKey() && checkCsr() && checkWorkDir() && checkCertDir(); break; default: LOG.error("Command '" + command + "' not recognized. Use --help for a list of available commands"); correct = false; } return correct; } public boolean isHelp() { return help; } public boolean isVersion() { return version; } public String getWorkDir() { return workDir; } public String getAccountKey() { return accountKey; } public String getCsr() { return csr; } public List<String> getDomains() { return domains; } public String getCertDir() { return certDir; } public String getLogDir() { return logDir; } public String getWellKnownDir() { return wellKnownDir; } public String getDnsDigestDir() { return dnsDigestDir; } public String getEmail() { return email; } public String getAcmeServerUrl() { return acmeServerUrl; } public String getAgreementUrl() { return agreementUrl; } public long getMaxExpirationTime() { return maxExpirationTime; } public String getCommand() { return command; } public boolean isForce() { return force; } public boolean isOneDirForWellKnown() { return oneDirForWellKnown; } public long getFromTime() { return fromTime; } public long getToTime() { return toTime; } public String getChallengeType() { return challengeType; } public boolean isWithAgreementUpdate() { return withAgreementUpdate; } public boolean isNewestOnly() { return newestOnly; } public String getLogLevel() { return logLevel; } }
package com.julienvey.trello.domain; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Card extends TrelloEntity { private String id; private String name; private String idList; private String desc; private String url; private Date due; private boolean dueComplete; private List<String> idMembers; private List<Label> labels; private Badges badges; private List<CardCheckItem> checkItemStates; private boolean closed; private Date dateLastActivity; private String idBoard; private List<String> idChecklists; private List<String> idMembersVoted; private String idShort; private String idAttachmentCover; private boolean manualCoverAttachment; private long pos; private String shortLink; private String shortUrl; private boolean subscribed; /* API */ public void addLabels(String... labels) { trelloService.addLabelsToCard(id, labels); } public void addComment(String comment) { trelloService.addCommentToCard(id, comment); } public List<Action> getActions(Argument... filters) { return trelloService.getCardActions(id, filters); } public List<Member> fetchMembers(Argument... args) { return trelloService.getCardMembers(id, args); } public void deleteAttachment(String attachmentId) { trelloService.deleteAttachment(id, attachmentId); } public void delete() { getTrelloService().deleteCard(id); } /* Accessors */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdList() { return idList; } public void setIdList(String idList) { this.idList = idList; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Date getDue() { return due; } public void setDue(Date due) { this.due = due; } public boolean isDueComplete() { return dueComplete; } public void setDueComplete(boolean dueComplete) { this.dueComplete = dueComplete; } public List<String> getIdMembers() { return idMembers; } public void setIdMembers(List<String> idMembers) { this.idMembers = idMembers; } public List<Label> getLabels() { return labels; } public void setLabels(List<Label> labels) { this.labels = labels; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<CardCheckItem> getCheckItemStates() { return checkItemStates; } public void setCheckItemStates(List<CardCheckItem> checkItemStates) { this.checkItemStates = checkItemStates; } public boolean isClosed() { return closed; } public void setClosed(boolean closed) { this.closed = closed; } public Date getDateLastActivity() { return dateLastActivity; } public void setDateLastActivity(Date dateLastActivity) { this.dateLastActivity = dateLastActivity; } public String getIdBoard() { return idBoard; } public void setIdBoard(String idBoard) { this.idBoard = idBoard; } public List<String> getIdChecklists() { return idChecklists; } public void setIdChecklists(List<String> idChecklists) { this.idChecklists = idChecklists; } public List<String> getIdMembersVoted() { return idMembersVoted; } public void setIdMembersVoted(List<String> idMembersVoted) { this.idMembersVoted = idMembersVoted; } public String getIdShort() { return idShort; } public void setIdShort(String idShort) { this.idShort = idShort; } public String getIdAttachmentCover() { return idAttachmentCover; } public void setIdAttachmentCover(String idAttachmentCover) { this.idAttachmentCover = idAttachmentCover; } public boolean isManualCoverAttachment() { return manualCoverAttachment; } public void setManualCoverAttachment(boolean manualCoverAttachment) { this.manualCoverAttachment = manualCoverAttachment; } public long getPos() { return pos; } public void setPos(long pos) { this.pos = pos; } public String getShortLink() { return shortLink; } public void setShortLink(String shortLink) { this.shortLink = shortLink; } public boolean isSubscribed() { return subscribed; } public void setSubscribed(boolean subscribed) { this.subscribed = subscribed; } public Badges getBadges() { return badges; } public void setBadges(Badges badges) { this.badges = badges; } public String getShortUrl() { return shortUrl; } public void setShortUrl(String shortUrl) { this.shortUrl = shortUrl; } public Card update() { return trelloService.updateCard(this); } @JsonIgnoreProperties(ignoreUnknown = true) public static class CardCheckItem { private String idCheckItem; private String state; public String getIdCheckItem() { return idCheckItem; } public void setIdCheckItem(String idCheckItem) { this.idCheckItem = idCheckItem; } public String getState() { return state; } public void setState(String state) { this.state = state; } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-05-10"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:17-03-19"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-09-02"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-07-03"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-02-03"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package org.objectweb.proactive.core.runtime; import org.objectweb.proactive.Body; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.LocalBodyStore; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl; import org.objectweb.proactive.core.event.RuntimeRegistrationEvent; import org.objectweb.proactive.core.event.RuntimeRegistrationEventProducerImpl; import org.objectweb.proactive.core.mop.ConstructorCall; import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.process.UniversalProcess; import org.objectweb.proactive.core.util.UrlBuilder; import org.objectweb.proactive.ext.security.Entity; import org.objectweb.proactive.ext.security.EntityCertificate; import org.objectweb.proactive.ext.security.EntityVirtualNode; import org.objectweb.proactive.ext.security.PolicyServer; import org.objectweb.proactive.ext.security.ProActiveSecurityManager; import org.objectweb.proactive.ext.security.SecurityContext; import org.objectweb.proactive.ext.security.exceptions.SecurityNotAvailableException; import java.io.File; import java.io.IOException; import java.security.PrivateKey; import java.security.Provider; import java.security.Security; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Hashtable; import java.util.Random; /** * <p> * Implementation of ProActiveRuntime * </p> * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.91 * */ public class ProActiveRuntimeImpl extends RuntimeRegistrationEventProducerImpl implements ProActiveRuntime { //the Unique instance of ProActiveRuntime private static ProActiveRuntime proActiveRuntime = new ProActiveRuntimeImpl(); private static Random prng = null; // new Random(); private static synchronized int getNextInt() { if (prng == null) { prng = new Random(); } return prng.nextInt(); } // map nodes and an ArrayList of PolicyServer private java.util.Hashtable policyServerMap; // map nodes and their virtual nodes private java.util.Hashtable virtualNodesMapNodes; // creator certificate private X509Certificate creatorCertificate; private X509Certificate certificate; private PrivateKey privateKey; // link to domain policy server // private PolicyServer policyServer; private ProActiveSecurityManager psm; private String defaultNodeVirtualNode = null; private VMInformation vmInformation; // map nodes and an ArrayList of Active Objects Id private java.util.Hashtable nodeMap; // map nodes and their job id; private Hashtable nodeJobIdMap; //map VirtualNodes and their names private java.util.Hashtable virtualNodesMap; //map descriptor and their url private java.util.Hashtable descriptorMap; // map proActiveRuntime registered on this VM and their names private java.util.Hashtable proActiveRuntimeMap; // synchronized set of URL to runtimes in which we are registered private java.util.Set parentsURL; // singleton private ProActiveRuntimeImpl() { try { this.nodeMap = new java.util.Hashtable(); this.vmInformation = new VMInformationImpl(); this.proActiveRuntimeMap = new java.util.Hashtable(); this.parentsURL = java.util.Collections.synchronizedSortedSet(new java.util.TreeSet()); this.virtualNodesMap = new java.util.Hashtable(); this.virtualNodesMapNodes = new java.util.Hashtable(); this.descriptorMap = new java.util.Hashtable(); this.policyServerMap = new java.util.Hashtable(); this.nodeJobIdMap = new java.util.Hashtable(); String file = System.getProperties().getProperty("proactive.runtime.security"); Provider myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); Security.addProvider(myProvider); if ((file != null) && new File(file).exists()) { // loading security from a file logger.info( "ProActive Security Policy (proactive.runtime.security) using " + file); // policyServer = ProActiveSecurityDescriptorHandler.createPolicyServer(file); psm = new ProActiveSecurityManager(file); } // else { // creating a generic certificate // logger.info( // "ProActive Security Policy (proactive.runtime.security) not set. Runtime Security disabled "); //Object[] tmp = ProActiveSecurity.generateGenericCertificate(); //certificate = (X509Certificate) tmp[0]; //privateKey = (PrivateKey) tmp[1]; //System.out.println(vmInformation.getVMID().toString()); } catch (java.net.UnknownHostException e) { //System.out.println(); logger.fatal(" !!! Cannot do a reverse lookup on that host"); // System.out.println(); e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); } } public static ProActiveRuntime getProActiveRuntime() { return proActiveRuntime; } /** * Register the given VirtualNode on this ProActiveRuntime. This method cannot be called remotely. * @param vn the virtualnode to register * @param vnName the name of the VirtualNode to register */ public void registerLocalVirtualNode(VirtualNode vn, String vnName) { //System.out.println("vn "+vnName+" registered"); virtualNodesMap.put(vnName, vn); } public void registerDescriptor(String url, ProActiveDescriptor pad) { descriptorMap.put(url, pad); } public ProActiveDescriptor getDescriptor(String url) { return (ProActiveDescriptor) descriptorMap.get(url); } public void removeDescriptor(String url) { descriptorMap.remove(url); } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#createLocalNode(String, boolean, PolicyServer, String, String) */ public String createLocalNode(String nodeName, boolean replacePreviousBinding, PolicyServer ps, String vnName, String jobId) throws NodeException { //Node node = new NodeImpl(this,nodeName); //System.out.println("node created with name "+nodeName+"on proActiveruntime "+this); if (replacePreviousBinding) { if (nodeMap.get(nodeName) != null) { nodeMap.remove(nodeName); nodeJobIdMap.remove(nodeName); } } if (!replacePreviousBinding && (nodeMap.get(nodeName) != null)) { throw new NodeException("Node " + nodeName + " already created on this ProActiveRuntime. To overwrite this node, use true for replacePreviousBinding"); } nodeMap.put(nodeName, new java.util.ArrayList()); nodeJobIdMap.put(nodeName, jobId); if (ps != null) { System.out.println("Node Certificate : " + ps.getCertificate().getPublicKey()); System.out.println("Node Certificate : " + ps.getCertificate().getIssuerDN()); } if ((vnName != null) && (vnName.equals("currentJVM"))) { // if Jvm has been started using the currentJVM tag // vnName = defaultNodeVirtualNode; logger.debug("Local Node : " + nodeName + " VN name : " + vnName + " policyserver " + ps); } if (ps != null) { logger.debug("generating node certificate"); // ps.generateEntityCertificate(vnName + " " + nodeName, vmInformation); policyServerMap.put(nodeName, ps); } if (vnName != null) { virtualNodesMapNodes.put(nodeName, vnName); } return nodeName; } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#killAllNodes() */ public void killAllNodes() { virtualNodesMapNodes.clear(); virtualNodesMap.clear(); policyServerMap.clear(); nodeMap.clear(); } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#killNode(String) */ public void killNode(String nodeName) { virtualNodesMapNodes.remove(nodeName); virtualNodesMap.remove(nodeName); policyServerMap.remove(nodeName); nodeMap.remove(nodeName); } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#createVM(UniversalProcess) */ public void createVM(UniversalProcess remoteProcess) throws java.io.IOException { remoteProcess.startProcess(); } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getLocalNodeNames() */ public String[] getLocalNodeNames() { int i = 0; String[] nodeNames; synchronized (nodeMap) { nodeNames = new String[nodeMap.size()]; for (java.util.Enumeration e = nodeMap.keys(); e.hasMoreElements();) { nodeNames[i] = (String) e.nextElement(); i++; } } return nodeNames; } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#getVMInformation() */ public VMInformation getVMInformation() { return vmInformation; } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#register(ProActiveRuntime, String, String, String, String) */ public void register(ProActiveRuntime proActiveRuntimeDist, String proActiveRuntimeName, String creatorID, String creationProtocol, String vmName) { //System.out.println("register in Impl"); //System.out.println("thread"+Thread.currentThread().getName()); //System.out.println(vmInformation.getVMID().toString()); proActiveRuntimeMap.put(proActiveRuntimeName, proActiveRuntimeDist); notifyListeners(this, RuntimeRegistrationEvent.RUNTIME_REGISTERED, proActiveRuntimeDist, creatorID, creationProtocol, vmName); } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#getProActiveRuntimes() */ public ProActiveRuntime[] getProActiveRuntimes() { int i = 0; ProActiveRuntime[] runtimeArray; synchronized (proActiveRuntimeMap) { runtimeArray = new ProActiveRuntime[proActiveRuntimeMap.size()]; for (java.util.Enumeration e = proActiveRuntimeMap.elements(); e.hasMoreElements();) { runtimeArray[i] = (ProActiveRuntime) e.nextElement(); i++; } } return runtimeArray; } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#getProActiveRuntime(String) */ public ProActiveRuntime getProActiveRuntime(String proActiveRuntimeName) { return (ProActiveRuntime) proActiveRuntimeMap.get(proActiveRuntimeName); } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#addParent(String) */ public void addParent(String proActiveRuntimeName) { parentsURL.add(proActiveRuntimeName); } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#getParents() */ public String[] getParents() { String[] urls; synchronized (parentsURL) { urls = new String[parentsURL.size()]; java.util.Iterator iter = parentsURL.iterator(); for (int i = 0; i < urls.length; i++) urls[i] = (String) iter.next(); } return urls; } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#killRT(boolean) */ public void killRT(boolean softly) { System.exit(0); } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#getURL() */ public String getURL() { return " UrlBuilder.getHostNameorIP(vmInformation.getInetAddress()) + "/" + vmInformation.getName(); } public ArrayList getActiveObjects(String nodeName) { //the array to return ArrayList localBodies = new ArrayList(); LocalBodyStore localBodystore = LocalBodyStore.getInstance(); ArrayList bodyList = (ArrayList) nodeMap.get(nodeName); synchronized (bodyList) { for (int i = 0; i < bodyList.size(); i++) { UniqueID bodyID = (UniqueID) bodyList.get(i); //check if the body is still on this vm Body body = localBodystore.getLocalBody(bodyID); if (body == null) { runtimeLogger.warn("body null"); // the body with the given ID is not any more on this ProActiveRuntime // unregister it from this ProActiveRuntime unregisterBody(nodeName, bodyID); } else { //the body is on this runtime then return adapter and class name of the reified //object to enable the construction of stub-proxy couple. ArrayList bodyAndObjectClass = new ArrayList(2); //adapter bodyAndObjectClass.add(0, body.getRemoteAdapter()); //className bodyAndObjectClass.add(1, body.getReifiedObject().getClass().getName()); localBodies.add(bodyAndObjectClass); } } return localBodies; } } public VirtualNode getVirtualNode(String virtualNodeName) { // System.out.println("i am in get vn "); return (VirtualNode) virtualNodesMap.get(virtualNodeName); } public void registerVirtualNode(String virtualNodeName, boolean replacePreviousBinding) { //This method has no effect here since the virtualNode has been registered in some registry //like RMI or JINI } public void unregisterVirtualNode(String virtualNodeName) { removeRuntimeRegistrationEventListener((VirtualNodeImpl) virtualNodesMap.get( virtualNodeName)); virtualNodesMap.remove(virtualNodeName); } public void unregisterAllVirtualNodes() { virtualNodesMap.clear(); } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getJobID(java.lang.String) */ public String getJobID(String nodeUrl) { String name = UrlBuilder.getNameFromUrl(nodeUrl); return (String) nodeJobIdMap.get(name); } public ArrayList getActiveObjects(String nodeName, String className) { //the array to return ArrayList localBodies = new ArrayList(); LocalBodyStore localBodystore = LocalBodyStore.getInstance(); ArrayList bodyList = (ArrayList) nodeMap.get(nodeName); synchronized (bodyList) { for (int i = 0; i < bodyList.size(); i++) { UniqueID bodyID = (UniqueID) bodyList.get(i); //check if the body is still on this vm Body body = localBodystore.getLocalBody(bodyID); if (body == null) { runtimeLogger.warn("body null"); // the body with the given ID is not any more on this ProActiveRuntime // unregister it from this ProActiveRuntime unregisterBody(nodeName, bodyID); } else { String objectClass = body.getReifiedObject().getClass() .getName(); // if the reified object is of the specified type // return the body adapter if (objectClass.equals((String) className)) { localBodies.add(body.getRemoteAdapter()); } } } return localBodies; } } /** *@see org.objectweb.proactive.core.runtime.ProActiveRuntime#createBody(String, ConstructorCall, boolean) */ public UniversalBody createBody(String nodeName, ConstructorCall bodyConstructorCall, boolean isLocal) throws ConstructorCallExecutionFailedException, java.lang.reflect.InvocationTargetException { Body localBody = (Body) bodyConstructorCall.execute(); PolicyServer objectPolicyServer = null; // SECURITY try { PolicyServer ps = (PolicyServer) policyServerMap.get(nodeName); if (ps != null) { objectPolicyServer = (PolicyServer) ps.clone(); String objectName = localBody.toString(); System.out.println("local Object Name " + objectName + "On node " + nodeName); objectPolicyServer.generateEntityCertificate(objectName); localBody.setPolicyServer(objectPolicyServer); localBody.getProActiveSecurityManager().setVNName((String) virtualNodesMapNodes.get( nodeName)); } /*} catch (IOException e) { e.printStackTrace(); } catch (SecurityNotAvailableException e) { // do nothing // security not available */ } catch (CloneNotSupportedException e) { // should never happen e.printStackTrace(); } catch (SecurityNotAvailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } registerBody(nodeName, localBody); if (isLocal) { // if the body and proxy are on the same vm, returns the local view //System.out.println("body and proxy on the same vm"); //System.out.println(localBody.getReifiedObject().getClass().getName()); //register the body in the nodemap return (UniversalBody) localBody; } else { //otherwise return the adapter //System.out.println ("RemoteProActiveImpl.createBody "+vmInformation.getInetAddress().getHostName() +" -> new "+bodyConstructorCall.getTargetClassName()+" on node "+nodeName); //System.out.println ("RemoteProActiveRuntimeImpl.localBody created localBody="+localBody+" on node "+nodeName); return localBody.getRemoteAdapter(); } } /** * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#receiveBody(String, Body) */ public UniversalBody receiveBody(String nodeName, Body body) { UniversalBody boa = body.getRemoteAdapter(); body.setPolicyServer((PolicyServer) policyServerMap.get(nodeName)); /* try { boa.getProActiveSecurityManager().setPolicyServer((PolicyServer) policyServerMap.get( nodeName)); } catch (IOException e) { e.printStackTrace(); } catch (SecurityNotAvailableException e) { // do nothing } */ registerBody(nodeName, body); return boa; } /** * Registers the specified body at the nodeName key in the <code>nodeMap</code>. * In fact it is the <code>UniqueID</code> of the body that is attached to the nodeName * in the <code>nodeMap</code> * @param nodeName. The name where to attached the body in the <code>nodeMap</code> * @param body. The body to register */ private void registerBody(String nodeName, Body body) { UniqueID bodyID = body.getID(); ArrayList bodyList = (ArrayList) nodeMap.get(nodeName); synchronized (bodyList) { if (!bodyList.contains(bodyID)) { //System.out.println("in registerbody id = "+ bodyID.toString()); bodyList.add(bodyID); } } } /** * Unregisters the specified <code>UniqueID</code> from the <code>nodeMap</code> at the * nodeName key * @param nodeName. The key where to remove the <code>UniqueID</code> * @param bodyID. The <code>UniqueID</code> to remove */ private void unregisterBody(String nodeName, UniqueID bodyID) { //System.out.println("in remove id= "+ bodyID.toString()); //System.out.println("array size "+((ArrayList)nodeMap.get(nodeName)).size()); ArrayList bodyList = (ArrayList) nodeMap.get(nodeName); synchronized (bodyList) { bodyList.remove(bodyID); //System.out.println("array size "+((ArrayList)nodeMap.get(nodeName)).size()); } } protected static class VMInformationImpl implements VMInformation, java.io.Serializable { private java.net.InetAddress hostInetAddress; //the Unique ID of the JVM private java.rmi.dgc.VMID uniqueVMID; private String name; private String processCreatorId; private String jobId; private String hostName; public VMInformationImpl() throws java.net.UnknownHostException { this.uniqueVMID = UniqueID.getCurrentVMID(); hostInetAddress = java.net.InetAddress.getLocalHost(); hostName = UrlBuilder.getHostNameorIP(hostInetAddress); this.processCreatorId = "jvm"; // this.name = "PA_JVM" + // Integer.toString(new java.security.SecureRandom().nextInt()) + // "_" + hostName; String random = Integer.toString(ProActiveRuntimeImpl.getNextInt()); if (System.getProperty("proactive.runtime.name") != null) { this.name = System.getProperty("proactive.runtime.name"); if (this.name.indexOf("PA_JVM") < 0) { logger.warn( "WARNING !!! The name of a ProActiveRuntime MUST contain PA_JVM string \n" + "WARNING !!! Property proactive.runtime.name does not contain PA_JVM. This name is not adapted to IC2D tool"); } } else { this.name = "PA_JVM" + random + "_" + hostName; } if (System.getProperty("proactive.jobid") != null) { this.jobId = System.getProperty("proactive.jobid"); } else { //if the property is null, no need to generate another random, take the one in name this.jobId = "JOB-" + random; } } public java.rmi.dgc.VMID getVMID() { return uniqueVMID; } public String getName() { return name; } public java.net.InetAddress getInetAddress() { return hostInetAddress; } public String getCreationProtocolID() { return this.processCreatorId; } public void setCreationProtocolID(String protocolId) { this.processCreatorId = protocolId; } /** * @see org.objectweb.proactive.Job#getJobID() */ public String getJobID() { return this.jobId; } /** * @see org.objectweb.proactive.core.runtime.VMInformation#getHostName() */ public String getHostName() { return this.hostName; } } // SECURITY /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getCreatorCertificate() */ public X509Certificate getCreatorCertificate() { return creatorCertificate; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getPolicyServer() */ public PolicyServer getPolicyServer() { // System.out.println("return my policy server " + policyServer); if (psm != null) { return psm.getPolicyServer(); } return null; } public String getVNName(String nodeName) { return (String) virtualNodesMapNodes.get(nodeName); } /** * set policy server to all virtual nodes */ public void setProActiveSecurityManager(ProActiveSecurityManager server) { if (psm != null) { return; } psm = server; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#setDefaultNodeVirtualNodeName(java.lang.String) */ public void setDefaultNodeVirtualNodeName(String s) { logger.debug(" setting current node as currentJVM tag " + s); defaultNodeVirtualNode = s; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getNodePolicyServer(java.lang.String) */ public PolicyServer getNodePolicyServer(String nodeName) { return (PolicyServer) policyServerMap.get(nodeName); } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#enableSecurityIfNeeded() */ public void enableSecurityIfNeeded() { /* Enumeration e = virtualNodesMap.elements(); for (; e.hasMoreElements(); ){ VirtualNode vn = (VirtualNode) e.nextElement(); logger.debug("Setting VN " + vn+"-"); logger.debug(vn.getName() ); logger.debug(" - policyserver " + policyServer); vn.setPolicyServer(policyServer); } */ } /** (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getNodeCertificate(java.lang.String) */ public X509Certificate getNodeCertificate(String nodeName) { PolicyServer ps = null; ps = (PolicyServer) policyServerMap.get(nodeName); if (ps != null) { return ps.getCertificate(); } return null; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getEntities(java.lang.String) */ public ArrayList getEntities(String nodeName) { PolicyServer ps = null; Entity nodeEntity = null; String nodeVirtualName = (String) virtualNodesMapNodes.get(nodeName); ps = (PolicyServer) policyServerMap.get(nodeName); if (ps != null) { nodeEntity = new EntityVirtualNode(nodeVirtualName, ps.getApplicationCertificate(), ps.getCertificate()); } ArrayList entities = null; //entities = getEntities(); if (entities == null) { entities = new ArrayList(); } entities.add(nodeEntity); return entities; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getEntities(org.objectweb.proactive.core.body.UniversalBody) */ public ArrayList getEntities(UniversalBody uBody) { try { return uBody.getEntities(); } catch (SecurityNotAvailableException e) { return null; } catch (IOException e) { e.printStackTrace(); } return null; } /* (non-Javadoc) * @see org.objectweb.proactive.core.runtime.ProActiveRuntime#getEntities() */ public ArrayList getEntities() { PolicyServer policyServer = psm.getPolicyServer(); Entity e = new EntityCertificate(policyServer.getApplicationCertificate(), policyServer.getCertificate()); ArrayList array = new ArrayList(); array.add(e); return array; } /** * @param sc */ public SecurityContext getPolicy(SecurityContext sc) throws SecurityNotAvailableException { if (psm == null) { throw new SecurityNotAvailableException(); } PolicyServer policyServer = psm.getPolicyServer(); return policyServer.getPolicy(sc); } /** * @see org.objectweb.proactive.Job#getJobID() */ public String getJobID() { return vmInformation.getJobID(); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-09-13"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package org.objectweb.proactive.examples.binarytree; public class ObjectWrapper implements java.io.Serializable { private Object value; public ObjectWrapper(){} public ObjectWrapper(Object value) { this.value = value; } public String toString() { return this.value.toString(); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-04-06"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package com.mikesamuel.cil.parser; import com.google.common.base.Optional; import com.mikesamuel.cil.ast.NodeVariant; import com.mikesamuel.cil.ast.Trees; import com.mikesamuel.cil.event.Event; /** Provides parsing and serializing for AST nodes. */ public abstract class ParSer implements ParSerable { /** * Simply supplies itself. * Being able to use ParSers as ParSerables allows us to avoid class * initialization loops where enum values are ParSers that need to delegate * to one another. */ @Override public final ParSer getParSer() { return this; } /** * Given a parse state, computes the parse state after successfully consuming * a prefix of the input in this parser's language. * * <p> * {@link Trees#of} can be used to build a tree from the * {@linkplain ParseState#output}. * * @param err receives parse errors. Errors on one branch may be irrelevant * if a later branch passes. If the parse as a whole fails, the parse * error that occurs at the rightmost point is a good one to pass on to * the end user. * @param lr state that lets productions handle left-recursive invocations. * @return failure when there is no string in this parser's language that is * a prefix of state's content. */ public abstract ParseResult parse( ParseState state, LeftRecursion lr, ParseErrorReceiver err); /** * True if the given input has no whitespace or comment tokens at the start * or end and the ParSer grammar matches the given input. */ public boolean fastMatch(String input) { // To be consistent with PatternMatch we need to disable \\u decoding. Input inp = Input.builder() .setFragmentOfAlreadyDecodedInput(true) .code(input) .source("fastMatch") .build(); if (inp.indexAfterIgnorables(0) != 0) { // We explicitly disallow comments and spaces at the front so that we // can use this method to check the value of leaf nodes that correspond // to a single token. return false; } ParseState before = new ParseState(inp); ParseResult result = parse( before, new LeftRecursion(), ParseErrorReceiver.DEV_NULL); if (result.synopsis == ParseResult.Synopsis.SUCCESS) { ParseState after = result.next(); if (after.index == inp.content().length()) { // We intentionally do not use indexAfterIgnorables. See above. return true; } } return false; } /** * Given a stream of events that describe a flattened tree, fleshes out the * stream of events by inserting {@link Event#token} events and events * for {@linkplain NodeVariant#isAnon anon} variants. */ public abstract Optional<SerialState> unparse( SerialState serialState, SerialErrorReceiver err); /** * Given a match state, consumes events to determine whether a flattened * parse tree can be parsed/serialized by this ParSer. * * @return absent if the events at the front of state cannot be handled * by this ParSer. */ public abstract Optional<MatchState> match( MatchState state, MatchErrorReceiver err); /** * Takes a set of ASTs, some of which are complete, and some of which are * partial, and figures out how they could be coerced so that they could * be unparsed to a string that matches the language matched by this ParSer. */ public abstract ForceFitState forceFit(ForceFitState state); /** * A string representing the shallow structure of the grammar backing this * ParSer. A shallow structure does not look through non-terminals. */ public abstract void appendShallowStructure(StringBuilder sb); @Override public final String toString() { StringBuilder sb = new StringBuilder(); appendShallowStructure(sb); return sb.toString(); } }
package com.ociweb.gl.impl; import com.ociweb.pronghorn.pipe.DataInputBlobReader; import com.ociweb.pronghorn.pipe.DataOutputBlobWriter; import com.ociweb.pronghorn.pipe.MessageSchema; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.util.TrieParserReader; public class PayloadReader<S extends MessageSchema<S>> extends DataInputBlobReader<S> { private TrieParserReader reader = new TrieParserReader(true); private int limit = -1; public PayloadReader(Pipe<S> pipe) { super(pipe); } protected static <S extends MessageSchema<S>> void checkLimit(PayloadReader<S> that, int min) { //TODO: this bounds checker is broken, open does not set limit right since static is used //if ( (that.position+min) > that.limit ) { // throw new RuntimeException("Read attempted beyond the end of the field data"); } @Override public int openHighLevelAPIField(int loc) { int len = super.openHighLevelAPIField(loc); limit = len + position; return len; } @Override public int openLowLevelAPIField() { int len = super.openLowLevelAPIField(); limit = len + position; return len; } private int fieldIdx(long fieldId) { return (int)fieldId & 0xFFFF; } protected int fieldType(long fieldId) { return (((int)fieldId)>>16) & 0xFF; } protected int computePosition(long fieldId) { assert(fieldId>=0) : "check field name, it does not match any found field"; //jump to end and index backwards to find data position return readFromEndLastInt(fieldIdx(fieldId)); } protected int computePositionSecond(long fieldId) { assert(fieldId>=0) : "check field name, it does not match any found field"; //jump to end and index backwards to find data position return readFromEndLastInt(1+fieldIdx(fieldId)); } @Override public int read(byte[] b) { checkLimit(this,2); return super.read(b); } @Override public int read(byte[] b, int off, int len) { checkLimit(this,2);//not len because read will read less return super.read(b, off, len); } @Override public void readFully(byte[] b) { checkLimit(this,2); super.readFully(b); } @Override public void readFully(byte[] b, int off, int len) { checkLimit(this,2);//not len because read will read less super.readFully(b, off, len); } @Override public int skipBytes(int n) { checkLimit(this,n); return super.skipBytes(n); } @Override public boolean readBoolean() { checkLimit(this,1); return super.readBoolean(); } @Override public byte readByte() { checkLimit(this,1); return super.readByte(); } @Override public int readUnsignedByte() { checkLimit(this,1); return super.readUnsignedByte(); } @Override public short readShort() { checkLimit(this,2); return super.readShort(); } @Override public int readUnsignedShort() { checkLimit(this,2); return super.readUnsignedShort(); } @Override public char readChar() { checkLimit(this,1); return super.readChar(); } @Override public int readInt() { checkLimit(this,4); return super.readInt(); } @Override public long readLong() { checkLimit(this,8); return super.readLong(); } @Override public float readFloat() { checkLimit(this,4); return super.readFloat(); } @Override public double readDouble() { checkLimit(this,8); return super.readDouble(); } @Override public int read() { checkLimit(this,1); return super.read(); } @Override public String readLine() { checkLimit(this,1); return super.readLine(); } @Override public String readUTF() { checkLimit(this,2); return super.readUTF(); } @Override public <A extends Appendable> A readUTF(A target) { checkLimit(this,2); return super.readUTF(target); } @Override public Object readObject() { checkLimit(this,1); return super.readObject(); } @Override public <T extends MessageSchema<T>> void readInto(DataOutputBlobWriter<T> writer, int length) { checkLimit(this,length); super.readInto(writer, length); } @Override public <A extends Appendable> A readPackedChars(A target) { checkLimit(this,1); return super.readPackedChars(target); } @Override public long readPackedLong() { checkLimit(this,1); return super.readPackedLong(); } @Override public int readPackedInt() { checkLimit(this,1); return super.readPackedInt(); } @Override public double readDecimalAsDouble() { checkLimit(this,2); return super.readDecimalAsDouble(); } @Override public long readDecimalAsLong() { checkLimit(this,2); return super.readDecimalAsLong(); } @Override public short readPackedShort() { checkLimit(this,1); return super.readPackedShort(); } }
package com.octopusdeploy.api; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; import net.sf.json.*; import org.apache.commons.lang.StringUtils; public class OctopusApi { private final static String UTF8 = "UTF-8"; private final AuthenticatedWebClient webClient; public OctopusApi(String octopusHost, String apiKey) { webClient = new AuthenticatedWebClient(octopusHost, apiKey); } /** * Creates a release in octopus deploy. * @param project The project id * @param releaseVersion The version number for this release. * @return content from the API post * @throws java.io.IOException */ public String createRelease(String project, String releaseVersion) throws IOException { return createRelease(project, releaseVersion, null); } /** * Creates a release in octopus deploy. * @param project The project id. * @param releaseVersion The version number for this release. * @param releaseNotes Release notes to be associated with this release. * @return content from the API post * @throws java.io.IOException */ public String createRelease(String project, String releaseVersion, String releaseNotes) throws IOException { return createRelease(project, releaseVersion, releaseNotes, null); } /** * Creates a release in octopus deploy. * @param project The project id * @param releaseVersion The version number for this release. * @param releaseNotes Release notes to be associated with this release. * @param selectedPackages Packages to be deployed with this release. * @return content from the API post * @throws java.io.IOException */ public String createRelease(String project, String releaseVersion, String releaseNotes, Set<SelectedPackage> selectedPackages) throws IOException { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.append(String.format("{ProjectId:\"%s\",Version:\"%s\"", project, releaseVersion)); if (releaseNotes != null && !releaseNotes.isEmpty()) { jsonBuilder.append(String.format(",ReleaseNotes:\"%s\"", releaseNotes)); } if (selectedPackages != null && !selectedPackages.isEmpty()) { jsonBuilder.append(",SelectedPackages:["); Set<String> selectedPackageStrings = new HashSet<String>(); for (SelectedPackage selectedPackage : selectedPackages) { selectedPackageStrings.add(String.format("{StepName:\"%s\",Version:\"%s\"}", selectedPackage.getStepName(), selectedPackage.getVersion())); } jsonBuilder.append(StringUtils.join(selectedPackageStrings, ",")); jsonBuilder.append("]"); } jsonBuilder.append("}"); String json = jsonBuilder.toString(); byte[] data = json.getBytes(Charset.forName(UTF8)); AuthenticatedWebClient.WebResponse response = webClient.post("api/releases", data); if (response.isErrorCode()) { String errorMsg = ErrorParser.getErrorsFromResponse(response.getContent()); throw new IOException(String.format("Code %s - %n%s", response.getCode(), errorMsg)); } return response.getContent(); } /** * Deploys a given release to provided environment. * @param releaseId Release Id from Octopus to deploy. * @param environmentId Environment Id from Octopus to deploy to. * @param tenantID Tenant Id from Octopus to deploy to. * @return the content of the web response. * @throws IOException */ public String executeDeployment(String releaseId, String environmentId, String tenantID) throws IOException { return executeDeployment( releaseId, environmentId, tenantID, null); } /** * Deploys a given release to provided environment. * @param releaseId Release Id from Octopus to deploy. * @param environmentId Environment Id from Octopus to deploy to. * @param tenantID Tenant Id from Octopus to deploy to. * @param variables Variables used during deployment. * @return the content of the web response. * @throws IOException */ public String executeDeployment(String releaseId, String environmentId, String tenantID, Set<Variable> variables) throws IOException { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.append(String.format("{EnvironmentId:\"%s\",ReleaseId:\"%s\"", environmentId, releaseId)); if (tenantID != null && !tenantID.isEmpty()) { jsonBuilder.append(String.format(",TenantId:\"%s\"", tenantID)); } if (variables != null && !variables.isEmpty()) { jsonBuilder.append(",FormValues:{"); Set<String> variablesStrings = new HashSet<String>(); for (Variable v : variables) { variablesStrings.add(String.format("\"%s\":\"%s\"", v.getId(), v.getValue())); } jsonBuilder.append(StringUtils.join(variablesStrings, ",")); jsonBuilder.append("}"); } jsonBuilder.append("}"); String json = jsonBuilder.toString(); byte[] data = json.getBytes(Charset.forName(UTF8)); AuthenticatedWebClient.WebResponse response = webClient.post("api/deployments", data); if (response.isErrorCode()) { String errorMsg = ErrorParser.getErrorsFromResponse(response.getContent()); throw new IOException(String.format("Code %s - %n%s", response.getCode(), errorMsg)); } return response.getContent(); } public Set<Project> getAllProjects() throws IllegalArgumentException, IOException { HashSet<Project> projects = new HashSet<Project>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); projects.add(new Project(id, name)); } return projects; } public Project getProjectByName(String name) throws IllegalArgumentException, IOException { return getProjectByName(name, false); } public Project getProjectByName(String name, boolean ignoreCase) throws IllegalArgumentException, IOException { Set<Project> allProjects = getAllProjects(); for (Project project : allProjects) { if ((ignoreCase && name.equalsIgnoreCase(project.getName())) || (!ignoreCase && name.equals(project.getName()))) { return project; } } return null; } public Set<Environment> getAllEnvironments() throws IllegalArgumentException, IOException { HashSet<Environment> environments = new HashSet<Environment>(); AuthenticatedWebClient.WebResponse response =webClient.get("api/environments/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); String description = jsonObj.getString("Description"); environments.add(new Environment(id, name, description)); } return environments; } public Environment getEnvironmentByName(String name) throws IllegalArgumentException, IOException { return getEnvironmentByName(name, false); } public Environment getEnvironmentByName(String name, boolean ignoreCase) throws IllegalArgumentException, IOException { Set<Environment> environments = getAllEnvironments(); for (Environment env : environments) { if ((ignoreCase && name.equalsIgnoreCase(env.getName())) || (!ignoreCase && name.equals(env.getName()))) { return env; } } return null; } public Set<Tenant> getAllTenants() throws IllegalArgumentException, IOException { HashSet<Tenant> tenants = new HashSet<Tenant>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/tenants/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); tenants.add(new Tenant(id, name)); } return tenants; } public Tenant getTenantByName(String name) throws IllegalArgumentException, IOException { return getTenantByName(name, false); } public Tenant getTenantByName(String name, boolean ignoreCase) throws IllegalArgumentException, IOException { Set<Tenant> tenants = getAllTenants(); for (Tenant tenant : tenants) { if ((ignoreCase && name.equalsIgnoreCase(tenant.getName())) || (!ignoreCase && name.equals(tenant.getName()))) { return tenant; } } return null; } public Set<Variable> getVariablesByReleaseAndEnvironment(String releaseId, String environmentId, Properties entryProperties) throws IllegalArgumentException, IOException { Set<Variable> variables = new HashSet<Variable>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/releases/" + releaseId + "/deployments/preview/" + environmentId); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); JSONObject form = json.getJSONObject("Form"); if (form != null){ JSONObject formValues = form.getJSONObject("Values"); for (Object obj : form.getJSONArray("Elements")) { JSONObject jsonObj = (JSONObject) obj; String id = jsonObj.getString("Name"); String name = jsonObj.getJSONObject("Control").getString("Name"); String value = formValues.getString(id); String entryValue = entryProperties.getProperty(name); if (StringUtils.isNotEmpty(entryValue)) { value = entryValue; } String description = jsonObj.getJSONObject("Control").getString("Description"); variables.add(new Variable(id, name, value, description)); } } return variables; } public Set<Release> getReleasesForProject(String projectId) throws IllegalArgumentException, IOException { HashSet<Release> releases = new HashSet<Release>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/" + projectId + "/releases"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String version = jsonObj.getString("Version"); String ReleaseNotes = jsonObj.getString("ReleaseNotes"); releases.add(new Release(id, projectId, ReleaseNotes, version)); } return releases; } public DeploymentProcess getDeploymentProcessForProject(String projectId) throws IllegalArgumentException, IOException { // TODO: refactor/method extract/clean up AuthenticatedWebClient.WebResponse response = webClient.get("api/deploymentprocesses/deploymentprocess-" + projectId); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); JSONArray stepsJson = json.getJSONArray("Steps"); HashSet<DeploymentProcessStep> deploymentProcessSteps = new HashSet<DeploymentProcessStep>(); for (Object stepObj : stepsJson) { JSONObject jsonStepObj = (JSONObject)stepObj; HashSet<DeploymentProcessStepAction> deploymentProcessStepActions = new HashSet<DeploymentProcessStepAction>(); JSONArray actionsJson = jsonStepObj.getJSONArray("Actions"); for (Object actionObj : actionsJson) { JSONObject jsonActionObj = (JSONObject)actionObj; JSONObject propertiesJson = jsonActionObj.getJSONObject("Properties"); HashMap<String, String> properties = new HashMap<String, String>(); for (Object key : propertiesJson.keySet()) { String keyString = key.toString(); properties.put(keyString, propertiesJson.getString(keyString)); } String dpsaId = jsonActionObj.getString("Id"); String dpsaName = jsonActionObj.getString("Name"); String dpsaType = jsonActionObj.getString("ActionType"); deploymentProcessStepActions.add(new DeploymentProcessStepAction(dpsaId, dpsaName, dpsaType, properties)); } String dpsId = jsonStepObj.getString("Id"); String dpsName = jsonStepObj.getString("Name"); deploymentProcessSteps.add(new DeploymentProcessStep(dpsId, dpsName, deploymentProcessStepActions)); } String dpId = json.getString("Id"); String dpProject = json.getString("ProjectId"); return new DeploymentProcess(dpId, dpProject, deploymentProcessSteps); } public DeploymentProcessTemplate getDeploymentProcessTemplateForProject(String projectId) throws IllegalArgumentException, IOException { AuthenticatedWebClient.WebResponse response = webClient.get("api/deploymentprocesses/deploymentprocess-" + projectId + "/template"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); Set<SelectedPackage> packages = new HashSet<SelectedPackage>(); String deploymentId = json.getString("DeploymentProcessId"); JSONArray pkgsJson = json.getJSONArray("Packages"); for (Object pkgObj : pkgsJson) { JSONObject pkgJsonObj = (JSONObject) pkgObj; String name = pkgJsonObj.getString("StepName"); String version = pkgJsonObj.getString("VersionSelectedLastRelease"); packages.add(new SelectedPackage(name, version)); } DeploymentProcessTemplate template = new DeploymentProcessTemplate(deploymentId, projectId, packages); return template; } /** * Retrieves a task by its id. * @param taskId * @return a Task object * @throws IOException */ public Task getTask(String taskId) throws IOException { AuthenticatedWebClient.WebResponse response = webClient.get("api/tasks/" + taskId); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); String id = json.getString("Id"); String name = json.getString("Name"); String description = json.getString("Description"); String state = json.getString("State"); boolean isCompleted = json.getBoolean("IsCompleted"); return new Task(id, name, description, state, isCompleted); } }
package com.quizdeck; import com.quizdeck.filters.AuthenticationFilter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; import javax.annotation.Resource; @EnableSwagger2 @SpringBootApplication public class QuizDeckApplication { public static void main(String[] args) { SpringApplication.run(QuizDeckApplication.class, args); } @Bean(name = "secretKey") public String secretKey() { return System.getProperty("SECRET_KEY", "default_key"); } @Bean @Resource(name = "secretKey") public FilterRegistrationBean authFilter(String secretKey) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new AuthenticationFilter(secretKey));
package com.wiccanarts.common.lib; public final class LibMod { //ID for MOD public static final String MOD_ID = "wiccanarts"; //Name of MOD public static final String MOD_NAME = "WiccanArts"; //Version of MOD public static final String MOD_VER = "@VERSION@"; //Dependency public static final String DEPENDENCIES = "required-after:Forge@[12.18.3.2234,];required-after:JEI@[3.14.7.415,];required-after:HWYLA@[1.8.10-B24_1.10.2,];required-after:llibrary@[1.7.4,];required-after:Baubles@[1.3.9,]"; //Client proxy location public static final String PROXY_CLIENT = "com.wiccanarts.client.core.ClientProxy"; //Server proxy location public static final String PROXY_COMMON = "com.wiccanarts.common.core.proxy.ServerProxy"; }
package com.xuh.method; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; public class ImageCompressUtil { /** * * () * * @param oldFile * @param width * @param height * @param quality * @param smallIcon (),yasuo.jpg,yasuo(+smallIcon).jpg * @return */ public static String zipImageFile(String oldFile, int width, int height, float quality, String smallIcon) { if (oldFile == null) { return null; } String newImage = null; try { Image srcFile = ImageIO.read(new File(oldFile)); BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null); String filePrex = oldFile.substring(0, oldFile.lastIndexOf("\\")); newImage = "E:/" + "2X" + oldFile.substring(filePrex.length()+1); FileOutputStream out = new FileOutputStream(newImage); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag); jep.setQuality(quality, true); encoder.encode(tag, jep); out.close(); //ImageCompressUtil.saveMinPhoto(newImage, newImage, 1920, 0.9d); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return newImage; } /** * () * @param fileName * @param is * @return */ public static String writeFile(String fileName, InputStream is) { if (fileName == null || fileName.trim().length() == 0) { return null; } try { FileOutputStream fos = new FileOutputStream(fileName); byte[] readBytes = new byte[512]; int readed = 0; while ((readed = is.read(readBytes)) > 0) { fos.write(readBytes, 0, readed); } fos.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fileName; } /** * * * @param srcURL * @param deskURL * @param comBase * @param scale (/) 1 * scale>=1,height=comBase,width;scale<1,width=comBase,height * @throws Exception */ public static void saveMinPhoto(String srcURL, String deskURL, double comBase, double scale) throws Exception { File srcFile = new File(srcURL); Image src = ImageIO.read(srcFile); int srcHeight = src.getHeight(null); int srcWidth = src.getWidth(null); int deskHeight = 0; int deskWidth = 0; double srcScale = (double) srcHeight / srcWidth; if ((double) srcHeight > comBase || (double) srcWidth > comBase) { if (srcScale >= scale || 1 / srcScale > scale) { if (srcScale >= scale) { deskHeight = (int) comBase; deskWidth = srcWidth * deskHeight / srcHeight; } else { deskWidth = (int) comBase; deskHeight = srcHeight * deskWidth / srcWidth; } } else { if ((double) srcHeight > comBase) { deskHeight = (int) comBase; deskWidth = srcWidth * deskHeight / srcHeight; } else { deskWidth = (int) comBase; deskHeight = srcHeight * deskWidth / srcWidth; } } } else { deskHeight = srcHeight; deskWidth = srcWidth; } BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR); tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); FileOutputStream deskImage = new FileOutputStream(deskURL); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage); encoder.encode(tag); //JPEG deskImage.close(); } public static void main(String args[]) throws Exception { System.out.println(""); //ImageCompressUtil.zipImageFile("E:\\flute.jpg", 1920, 952, 1f, "x2"); ImageCompressUtil.saveMinPhoto("E:\\2Xflute.jpg", "E:\\x2music-1.jpg", 1080, 0.9d); System.out.println(""); } }
package com.yahoo.sketches.hll; import com.yahoo.sketches.Util; import com.yahoo.sketches.hash.MurmurHash3; @SuppressWarnings("cast") public class HllSketch { // derived using some formulas in Ting's paper (link?) private static final double HLL_REL_ERROR_NUMER = 1.04; public static HllSketchBuilder builder() { return new HllSketchBuilder(); } private Fields.UpdateCallback updateCallback; private final Preamble preamble; private Fields fields; public HllSketch(Fields fields) { this.fields = fields; this.updateCallback = new NoopUpdateCallback(); this.preamble = fields.getPreamble(); } public void update(byte[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(int[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public void update(long[] key) { updateWithHash(MurmurHash3.hash(key, Util.DEFAULT_UPDATE_SEED)); } public double getEstimate() { double rawEst = getRawEstimate(); int logK = preamble.getLogConfigK(); double[] x_arr = Interpolation.interpolation_x_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; double[] y_arr = Interpolation.interpolation_y_arrs[logK - Interpolation.INTERPOLATION_MIN_LOG_K]; if (rawEst < x_arr[0]) { return 0; } if (rawEst > x_arr[x_arr.length - 1]) { return rawEst; } double adjEst = Interpolation.cubicInterpolateUsingTable(x_arr, y_arr, rawEst); int configK = preamble.getConfigK(); if (adjEst > 3.0 * configK) { return adjEst; } double linEst = getLinearEstimate(); double avgEst = (adjEst + linEst) / 2.0; /* the following constant 0.64 comes from empirical measurements (see below) of the crossover point between the average error of the linear estimator and the adjusted hll estimator */ if (avgEst > 0.64 * configK) { return adjEst; } return linEst; } public double getUpperBound(double numStdDevs) { return getEstimate() / (1.0 - eps(numStdDevs)); } public double getLowerBound(double numStdDevs) { double lowerBound = getEstimate() / (1.0 + eps(numStdDevs)); double numNonZeros = (double) preamble.getConfigK(); numNonZeros -= numBucketsAtZero(); if (lowerBound < numNonZeros) { return numNonZeros; } return lowerBound; } private double getRawEstimate() { int numBuckets = preamble.getConfigK(); double correctionFactor = 0.7213 / (1.0 + 1.079 / (double) numBuckets); correctionFactor *= numBuckets * numBuckets; correctionFactor /= inversePowerOf2Sum(); return correctionFactor; } private double getLinearEstimate() { int configK = preamble.getConfigK(); long longV = numBucketsAtZero(); if (longV == 0) { return configK * Math.log(configK / 0.5); } return (configK * (HarmonicNumbers.harmonicNumber(configK) - HarmonicNumbers.harmonicNumber(longV))); } public HllSketch union(HllSketch that) { BucketIterator iter = that.fields.getBucketIterator(); while (iter.next()) { fields = fields.updateBucket(iter.getKey(), iter.getValue(), updateCallback); } return this; } private void updateWithHash(long[] hash) { byte newValue = (byte) (Long.numberOfLeadingZeros(hash[1]) + 1); int slotno = (int) hash[0] & (preamble.getConfigK() - 1); fields = fields.updateBucket(slotno, newValue, updateCallback); } private double eps(double numStdDevs) { return numStdDevs * HLL_REL_ERROR_NUMER / Math.sqrt(preamble.getConfigK()); } public byte[] toByteArray() { int numBytes = (preamble.getPreambleSize() << 3) + fields.numBytesToSerialize(); byte[] retVal = new byte[numBytes]; fields.intoByteArray(retVal, preamble.intoByteArray(retVal, 0)); return retVal; } public byte[] toByteArrayNoPreamble() { byte[] retVal = new byte[fields.numBytesToSerialize()]; fields.intoByteArray(retVal, 0); return retVal; } public HllSketch asCompact() { return new HllSketch(fields.toCompact()); } public int numBuckets() { return preamble.getConfigK(); } /** * Get the update Callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @return The updateCallback registered with the HllSketch */ protected Fields.UpdateCallback getUpdateCallback() { return updateCallback; } /** * Set the update callback. This is protected because it is intended that only children might *call* * the method. It is not expected that this would be overridden by a child class. If someone overrides * it and weird things happen, the bug lies in the fact that it was overridden. * * @param updateCallback the update callback for the HllSketch to use when talking with its Fields */ protected void setUpdateCallback(Fields.UpdateCallback updateCallback) { this.updateCallback = updateCallback; } //Helper methods that are potential extension points for children /** * The sum of the inverse powers of 2 * @return the sum of the inverse powers of 2 */ protected double inversePowerOf2Sum() { return HllUtils.computeInvPow2Sum(numBuckets(), fields.getBucketIterator()); } protected int numBucketsAtZero() { int retVal = 0; int count = 0; BucketIterator bucketIter = fields.getBucketIterator(); while (bucketIter.next()) { if (bucketIter.getValue() == 0) { ++retVal; } ++count; } // All skipped buckets are 0. retVal += fields.getPreamble().getConfigK() - count; return retVal; } }
package compiler.graphloader; import net.sourceforge.gxl.*; import org.graphstream.graph.Edge; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.MultiGraph; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; /** * Class used to import graphs saved in GXL format. */ final class GXLImporter { /** * Set of seen IDs to ensure uniqueness of IDs given to GraphStream Graph elements. */ private static Set<String> ids = new HashSet<>(); /** * Counter used to guarantee unique IDs for GraphStream Graph elements. */ private static int idcounter = 0; /** * List of file extensions accepted by this importer. */ private static final List<String> acceptslist = Arrays.asList("gxl", "gst", "gpl", "gst", "gpr", "gty"); /** * Returns whether an extension is accepted by this importer. * @param ext File extension to verify. * @return <tt>true</tt> if the file extension is accepted. */ static boolean acceptsExtension(String ext) { return acceptslist.contains(ext.toLowerCase()); } /** * Reads a file in GXL format into a GraphStream graph Object. * @param file File to read into a GraphsStream Graph Object. * @return A GraphStream Graph Object containing the graph represented in the file. * @throws IOException Thrown when the file could not be read. * @throws SAXException Thrown when the file contains incorrect syntax. */ static MultiGraph read(File file) throws IOException, SAXException { return read(file.getAbsolutePath()); } /** * Reads a file in GXL format into a GraphStream graph Object. * @param path Path to the file to read into a GraphsStream Graph Object. * @return A GraphStream Graph Object containing the graph represented in the file. * @throws IOException Thrown when the file could not be read. * @throws SAXException Thrown when the file contains incorrect syntax. */ static MultiGraph read(String path) throws IOException, SAXException { return read(path, false); } /** * Reads a file in GXL format into a GraphStream graph Object. * @param path Path to the file to read into a GraphsStream Graph Object. * @param addUnderscores <tt>true</tt> if underscores are to be added to the IDs of the read graph. * @return A GraphStream Graph Object containing the graph represented in the file. * @throws IOException Thrown when the file could not be read. * @throws SAXException Thrown when the file contains incorrect syntax. */ static MultiGraph read(String path, boolean addUnderscores) throws IOException, SAXException { ids.clear(); idcounter = 0; String underscore = ""; if (addUnderscores) { underscore = "_"; } byte[] encoded = Files.readAllBytes(Paths.get(path)); String gxml = new String(encoded, "UTF-8"); gxml = gxml.replaceAll(" xmlns=\"http: gxml = removeDupAttr(gxml); GXLDocument doc = new GXLDocument(new ByteArrayInputStream(gxml.getBytes(StandardCharsets.UTF_8))); GXLGXL a = doc.getDocumentElement(); GXLGraph graph = a.getGraphAt(0); MultiGraph tograph = new MultiGraph(underscore + graph.getAttribute("id"), true, false); boolean directed = graph.getAttribute("edgemode").equals("directed"); List<GXLGraphElement> nodes = new LinkedList<>(); List<GXLGraphElement> edges = new LinkedList<>(); for (int i = 0; i < graph.getGraphElementCount(); i++) { GXLGraphElement elem = graph.getGraphElementAt(i); if (elem instanceof GXLNode) { nodes.add(elem); } else { edges.add(elem); } } for (GXLGraphElement elem : nodes) { String id = getID(elem, addUnderscores); Node n = tograph.addNode(id); for (int p = 0; p < elem.getAttrCount(); p++) { GXLValue content = (elem.getAttrAt(p)).getValue(); n.setAttribute(elem.getAttrAt(p).getName(), "\"" + getFromGXLValue(content) + "\""); } } for (GXLGraphElement elem : edges) { String id = getID(elem, addUnderscores); Edge e = tograph.addEdge(id, underscore + elem.getAttribute("from"), underscore + elem.getAttribute("to"), directed); for (int p = 0; p < elem.getAttrCount(); p++) { GXLValue content = (elem.getAttrAt(p)).getValue(); e.setAttribute(elem.getAttrAt(p).getName(), "\"" + getFromGXLValue(content) + "\""); } } return tograph; } /** * If a gxl file contains the version attribute two times, removes one of the two times. * @param gxml String containing the gxl file. * @return A String with no duplicate version attributes. */ private static String removeDupAttr(String gxml) { int index1 = gxml.indexOf("<attr name=\"$version\">"); int index2 = gxml.indexOf("<attr name=\"$version\">", index1 + 1); if (index2 == -1) { return gxml; } int end = gxml.indexOf("</attr>", index2); return removeDupAttr(gxml.substring(0, index2) + gxml.substring(end + 6)); } /** * Returns a String or List read from a GXLValue. * @param in GXLValue to be read from. * @return String or List Object, depending on whether it's an atomic or composite GXLValue. */ private static Object getFromGXLValue(GXLValue in) { if (in instanceof GXLAtomicValue) { return ((GXLAtomicValue) in).getValue(); } else if (in instanceof GXLCompositeValue) { List<Object> res = new LinkedList<>(); GXLCompositeValue a = (GXLCompositeValue) in; for (int i = 0; i<a.getValueCount(); i++) { res.add(getFromGXLValue(a.getValueAt(i))); } return res; } throw new UnsupportedOperationException(); } /** * Given a graph element, return its ID as specified in GXL or a generated one if not specified. * @param in Graph element of which to return an ID. * @param addUnderscore <tt>true</tt> if underscores should be added to IDs. * @return A unique String to be used as identifier. */ private static String getID(GXLGraphElement in, boolean addUnderscore) { String underscore = ""; if (addUnderscore) { underscore = "_"; } String idgotten = in.getAttribute("id"); if (idgotten != null && !ids.contains(underscore + idgotten)) { ids.add(underscore + idgotten); return underscore + idgotten; } String prefix = "UNKNOWN"; if (in instanceof GXLNode) { prefix = "n"; } else if (in instanceof GXLEdge){ prefix = "e"; } while (ids.contains(underscore + prefix + "ID?" + idcounter)) { idcounter++; } idgotten = underscore + prefix + "ID?" + idcounter; ids.add(idgotten); return idgotten; } }
package de.fau.osr.gui; import javax.swing.*; import javax.swing.table.JTableHeader; import java.awt.*; class RowHeaderRenderer<E> extends JLabel implements ListCellRenderer<E> { RowHeaderRenderer(JTable table) { JTableHeader header = table.getTableHeader(); setOpaque(true); setBorder(UIManager.getBorder("TableHeader.cellBorder")); setHorizontalAlignment(LEFT); setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); header.setResizingAllowed(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { setText((value == null) ? "" : value.toString()); return this; } }
package de.omnikryptec.util; import de.omnikryptec.util.math.Mathd; import de.omnikryptec.util.math.Mathf; public enum Interpolator { None { @Override public double interpolate(double t) { return 0.0; } @Override public float interpolate(float t) { return 0.0F; } }, Linear { @Override public double interpolate(double t) { return t; } @Override public float interpolate(float t) { return t; } }, Cubic { @Override public double interpolate(double t) { return (t * t * (3.0 - 2.0 * t)); } @Override public float interpolate(float t) { return (t * t * (3.0F - 2.0F * t)); } }, Quintic { @Override public double interpolate(double t) { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); } @Override public float interpolate(float t) { return t * t * t * (t * (t * 6.0F - 15.0F) + 10.0F); } }, Cos { @Override public double interpolate(double t) { return (1.0 - Mathd.cos(t * Mathd.PI)) * 0.5; } @Override public float interpolate(float t) { return (1.0F - Mathf.cos(t * Mathf.PI)) * 0.5F; } }; public double interpolate(final double t) { throw new AbstractMethodError(); } public float interpolate(final float t) { throw new AbstractMethodError(); } }
package edu.stanford.junction.props; import org.json.JSONObject; import org.json.JSONException; import java.util.Vector; import java.util.UUID; import java.util.Random; import edu.stanford.junction.api.activity.JunctionExtra; import edu.stanford.junction.api.messaging.MessageHeader; public abstract class Prop extends JunctionExtra { public static final int MODE_NORM = 1; public static final int MODE_SYNC = 2; public static final int MSG_STATE_OPERATION = 1; public static final int MSG_STATE_SYNC = 2; public static final int MSG_WHO_HAS_STATE = 3; public static final int MSG_I_HAVE_STATE = 4; public static final int MSG_SEND_ME_STATE = 5; public static final int MSG_PLZ_CATCHUP = 6; public static final int PLZ_CATCHUP_THRESHOLD = 5; private String uuid = UUID.randomUUID().toString(); private String propName; private String propReplicaName = ""; private IPropState state; private int mode = MODE_NORM; private int staleness = 0; private int stateNumber = 0; private long lastOperationNonce = 0; private long syncNonce = 0; private boolean waitingForIHaveState = false; private Vector<StateOperationMsg> incomingBuffer = new Vector<StateOperationMsg>(); private Vector<HistoryMAC> verifyHistory = new Vector<HistoryMAC>(); private Vector<IPropChangeListener> changeListeners = new Vector<IPropChangeListener>(); public Prop(String propName, IPropState state, String propReplicaName){ this.propName = propName; this.state = state; this.propReplicaName = propReplicaName; } public Prop(String propName, IPropState state){ this(propName, state, propName + "-replica" + UUID.randomUUID().toString()); } public int getStaleness(){ return staleness; } public IPropState getState(){ return state; } public int getStateNumber(){ return stateNumber; } protected int getNextStateNumber(){ return getStateNumber() + 1; } protected String getPropName(){ return propName; } protected void signalStateUpdate(){} protected void logInfo(String s){ System.out.println("prop@" + propReplicaName + ": " + s); } protected void logErr(String s){ System.err.println("prop@" + propReplicaName + ": " + s); } protected HistoryMAC newHistoryMAC(){ return new HistoryMAC(getStateNumber(), this.state.hash()); } abstract protected IPropState destringifyState(String s); abstract protected IPropStateOperation destringifyOperation(String s); public void addChangeListener(IPropChangeListener listener){ changeListeners.add(listener); } protected void dispatchChangeNotification(String evtType, Object o){ for(IPropChangeListener l : changeListeners){ logInfo("Dispatching change notification..."); l.onChange(evtType, o); } } protected void applyOperation(StateOperationMsg msg, boolean notify){ IPropStateOperation operation = msg.operation; this.state = state.applyOperation(operation); this.lastOperationNonce = operation.getNonce(); this.stateNumber += 1; this.verifyHistory.insertElementAt(newHistoryMAC(), 0); Vector<HistoryMAC> newHistory = new Vector<HistoryMAC>(); for(int i = 0; i < verifyHistory.size() && i < 10; i++){ newHistory.add(verifyHistory.get(i)); } this.verifyHistory = newHistory; if(notify && !(operation instanceof NullOp)){ dispatchChangeNotification("change", null); } } protected void checkHistory(HistoryMAC mac){ for(HistoryMAC m : this.verifyHistory){ if(m.stateNumber == mac.stateNumber){ if(!(m.stateHash.equals(mac.stateHash))){ logErr("Invalid state!" + m + " vs " + mac + " broadcasting Hello to flush out newbs.."); sendHello(); } } } } protected void exitSYNCMode(){ logInfo("Exiting SYNC mode"); this.mode = MODE_NORM; } protected void enterSYNCMode(int desiredStateNumber){ logInfo("Entering SYNC mode."); this.mode = MODE_SYNC; Random rng = new Random(); this.syncNonce = rng.nextLong(); sendMessageToProp(new WhoHasStateMsg(desiredStateNumber, this.syncNonce)); this.waitingForIHaveState = true; } protected void handleMessage(MessageHeader header, JSONObject rawMsg){ int msgType = rawMsg.optInt("type"); String fromPeer = rawMsg.optString("senderReplicaUUID"); String fromReplicaName = rawMsg.optString("senderReplicaName"); logInfo(propReplicaName + " processing message from: " + fromReplicaName); String fromActor = header.getSender(); boolean isSelfMsg = (fromPeer.equals(this.uuid)); switch(mode){ case MODE_NORM: switch(msgType){ case MSG_STATE_OPERATION: { StateOperationMsg msg = new StateOperationMsg(rawMsg, this); IPropStateOperation operation = msg.operation; int predictedStateNumber = msg.predictedStateNumber; if(predictedStateNumber > getNextStateNumber()){ // The predictedStateNumber of an operation is always <= // it's true sequence num. So we check the predictedStateNumber // against the # that would be it's true sequence num (this.stateSeqNum + 1), // were we to apply it. logInfo("Buffering FIRST " + msg + "from " + fromReplicaName + ". Currently at " + getStateNumber()); enterSYNCMode(predictedStateNumber - 1); this.incomingBuffer.add(msg); } else { // Note, operation may have been created WRT to stale state. // It's not unsound to apply the operation - but we // hope that sender will eventually notice it's own // staleness and SYNC. // Send them a hint if things get too bad.. if(!isSelfMsg && (getStateNumber() - predictedStateNumber) > PLZ_CATCHUP_THRESHOLD){ logInfo("I'm at " + getStateNumber() + ", they're at " + predictedStateNumber + ". " + "Sending catchup."); sendMessageToPropReplica(fromActor, new PlzCatchUpMsg(getStateNumber())); } if(isSelfMsg){ this.staleness = (getNextStateNumber() - predictedStateNumber); } logInfo("Applying msg " + msg + " from " + fromReplicaName + ", currently at " + getStateNumber()); applyOperation(msg, true); if(!isSelfMsg){ checkHistory(msg.mac); } } break; } case MSG_WHO_HAS_STATE:{ WhoHasStateMsg msg = new WhoHasStateMsg(rawMsg); if(!isSelfMsg){ // Can we fill the gap for this peer? if(getStateNumber() >= msg.desiredStateNumber){ sendMessageToPropReplica( fromActor, new IHaveStateMsg(getStateNumber(), msg.syncNonce)); } else{ logInfo("Oops! got state request for state i don't have!"); } } break; } case MSG_SEND_ME_STATE:{ SendMeStateMsg msg = new SendMeStateMsg(rawMsg); if(!isSelfMsg){ logInfo("Got SendMeState"); // Can we fill the gap for this peer? if(getStateNumber() > msg.desiredStateNumber){ logInfo("Sending state.."); sendMessageToPropReplica( fromActor, new StateSyncMsg( getStateNumber(), this.state.stringify(), msg.syncNonce, this.lastOperationNonce)); } } break; } case MSG_PLZ_CATCHUP:{ PlzCatchUpMsg msg = new PlzCatchUpMsg(rawMsg); if(!isSelfMsg){ // Some peer is trying to tell us we are stale. // Do we believe them? logInfo("Got PlzCatchup : " + msg); if(msg.stateNumber > getStateNumber()) { enterSYNCMode(msg.stateNumber); } } break; } case MSG_STATE_SYNC: break; case MSG_I_HAVE_STATE: break; default: logErr("NORM mode: Unrecognized message, " + rawMsg); } break; case MODE_SYNC: switch(msgType){ case MSG_STATE_OPERATION:{ StateOperationMsg msg = new StateOperationMsg(rawMsg, this); IPropStateOperation operation = msg.operation; int predictedStateNumber = msg.predictedStateNumber; if(predictedStateNumber <= getNextStateNumber() && this.incomingBuffer.isEmpty()){ // We're in sync-mode, but it looks like we're up to date. // Go back to NORM mode. logInfo("Applying msg " + msg + " from " + fromReplicaName + ", currently at " + getStateNumber()); applyOperation(msg, true); checkHistory(msg.mac); exitSYNCMode(); } else{ // Message is on far side of gap, buffer it. logInfo("Buffering " + msg + " from " + fromReplicaName + ". Currently at " + getStateNumber()); this.incomingBuffer.add(msg); } break; } case MSG_I_HAVE_STATE:{ IHaveStateMsg msg = new IHaveStateMsg(rawMsg); if(!isSelfMsg){ logInfo("Got IHaveState"); if(msg.syncNonce == this.syncNonce && msg.stateNumber > getStateNumber()){ logInfo("Requesting state"); this.waitingForIHaveState = false; sendMessageToPropReplica(fromActor, new SendMeStateMsg(getStateNumber(), msg.syncNonce)); } } break; } case MSG_STATE_SYNC:{ StateSyncMsg msg = new StateSyncMsg(rawMsg); if(!isSelfMsg){ // First check that this sync message corresponds to this // instance of SYNC mode. This is critical for assumptions // we make about the contents of incomingBuffer... if(msg.syncNonce != this.syncNonce){ logInfo("Bogus SYNC nonce! ignoring StateSyncMsg"); } else{ logInfo("Got StateSyncMsg:" + msg.state); // If local peer has buffered no operations, we know that no operations // were applied since the creation of state. We can safely assume // the given state. if(this.incomingBuffer.isEmpty()){ logInfo("No buffered items.. applying sync"); this.state = destringifyState(msg.state); this.lastOperationNonce = msg.lastOperationNonce; this.stateNumber = msg.stateNumber; exitSYNCMode(); dispatchChangeNotification("change", null); } else{ // Otherwise, we've buffered some operations. // Since we started buffering before we sent the WhoHasState request, // it must be that we've buffered all operations with seqNums >= that of // state. this.state = destringifyState(msg.state); this.lastOperationNonce = msg.lastOperationNonce; this.stateNumber = msg.stateNumber; // It's possible that ALL buffered messages are already incorportated // into state. In that case want to ignore buffered items and // just assume state. // Otherwise, there is some tail of buffered operations that occurred after // the state was captured. We find this tail by comparing the nonce // of each buffered operation with that of the last operation incorporated // into state. (NOTE: we don't know the seqNums of the buffered msgs! // that's why we need the nonce.) for(int i = 0; i < this.incomingBuffer.size(); i++){ StateOperationMsg m = this.incomingBuffer.get(i); if(m.operation.getNonce() == msg.lastOperationNonce){ logInfo("Found nonce match in buffered messages!"); for(int j = i + 1; j < this.incomingBuffer.size(); j++){ applyOperation(this.incomingBuffer.get(j), false); } break; } } this.incomingBuffer.clear(); exitSYNCMode(); dispatchChangeNotification("change", null); } } } break; } default: logErr("SYNC mode: Unrecognized message, " + rawMsg); } break; } signalStateUpdate(); } /** * Returns true if the normal event handling should proceed; * Return false to stop cascading. */ public boolean beforeOnMessageReceived(MessageHeader h, JSONObject msg) { if(msg.optString("propTarget").equals(getPropName())){ handleMessage(h, msg); return false; } else{ return true; } } /** * Send a hello message to all prop-replicas in this prop. * The hello message is a state operation that does not affect * the state. It serves to initiate conversation when all peers * are at state 0. */ protected void sendHello(){ int predictedStateNumber = getNextStateNumber(); sendMessageToProp(new HelloMsg( predictedStateNumber, getState().nullOperation(), newHistoryMAC())); } /** * Send a message to all prop-replicas in this prop */ protected void sendOperation(IPropStateOperation operation){ int predictedStateNumber = getNextStateNumber(); HistoryMAC mac = newHistoryMAC(); StateOperationMsg msg = new StateOperationMsg( predictedStateNumber, operation, newHistoryMAC()); logInfo(propReplicaName + " sending " + msg + ". Current MAC: " + mac); sendMessageToProp(msg); } /** * Add an operation to the state managed by this Prop */ synchronized public void addOperation(IPropStateOperation operation){ sendOperation(operation); } /** * Send a message to all prop-replicas in this prop */ protected void sendMessageToProp(PropMsg msg){ JSONObject m = msg.toJSONObject(); try{ m.put("propTarget", getPropName()); m.put("senderReplicaUUID", uuid); m.put("senderReplicaName", propReplicaName); }catch(JSONException e){} getActor().sendMessageToSession(m); } /** * Send a message to the prop-replica hosted at the given actorId. */ protected void sendMessageToPropReplica(String actorId, PropMsg msg){ JSONObject m = msg.toJSONObject(); try{ m.put("propTarget", getPropName()); m.put("senderReplicaUUID", uuid); m.put("senderReplicaName", propReplicaName); }catch(JSONException e){} getActor().sendMessageToActor(actorId, m); } public void afterActivityJoin() { sendHello(); } abstract class PropMsg{ abstract public JSONObject toJSONObject(); } class StateOperationMsg extends PropMsg{ public int predictedStateNumber; public IPropStateOperation operation; public HistoryMAC mac; public StateOperationMsg(JSONObject msg, Prop prop){ this.predictedStateNumber = msg.optInt("predStateNum"); this.mac = new HistoryMAC(msg.optInt("macStateNum"), msg.optString("macStateHash")); this.operation = prop.destringifyOperation(msg.optString("operation")); } public StateOperationMsg(int predictedStateNumber, IPropStateOperation operation, HistoryMAC mac){ this.predictedStateNumber = predictedStateNumber; this.mac = mac; this.operation = operation; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_STATE_OPERATION); obj.put("predStateNum", predictedStateNumber); obj.put("macStateNum", mac.stateNumber); obj.put("macStateHash", mac.stateHash); obj.put("operation", operation.stringify()); }catch(JSONException e){} return obj; } public String toString(){ return "[(" + (predictedStateNumber-1) + "->" + predictedStateNumber + ") " + operation.getNonce() + "]"; } } class HelloMsg extends StateOperationMsg{ public HelloMsg(JSONObject msg, Prop prop){ super(msg, prop); } public HelloMsg(int predictedStateNumber, IPropStateOperation operation, HistoryMAC mac){ super(predictedStateNumber, operation, mac); } } class StateSyncMsg extends PropMsg{ public int stateNumber; public String state; public long syncNonce; public long lastOperationNonce; public StateSyncMsg(JSONObject msg){ stateNumber = msg.optInt("stateNumber"); state = msg.optString("state"); syncNonce = msg.optLong("syncNonce"); lastOperationNonce = msg.optLong("lastOperationNonce"); } public StateSyncMsg(int stateNumber, String state, long syncNonce, long lastOperationNonce){ this.stateNumber = stateNumber; this.state = state; this.syncNonce = syncNonce; this.lastOperationNonce = lastOperationNonce; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_STATE_SYNC); obj.put("stateNumber", stateNumber); obj.put("state", state); obj.put("syncNonce", syncNonce); obj.put("lastOperationNonce", lastOperationNonce); }catch(JSONException e){} return obj; } } class WhoHasStateMsg extends PropMsg{ public int desiredStateNumber; public long syncNonce; public WhoHasStateMsg(JSONObject msg){ desiredStateNumber = msg.optInt("desiredStateNumber"); syncNonce = msg.optLong("syncNonce"); } public WhoHasStateMsg(int desiredStateNumber, long syncNonce){ this.desiredStateNumber = desiredStateNumber; this.syncNonce = syncNonce; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_WHO_HAS_STATE); obj.put("desiredStateNumber", desiredStateNumber); obj.put("syncNonce", syncNonce); }catch(JSONException e){} return obj; } } class IHaveStateMsg extends PropMsg{ public int stateNumber; public long syncNonce; public IHaveStateMsg(JSONObject msg){ stateNumber = msg.optInt("stateNumber"); syncNonce = msg.optLong("syncNonce"); } public IHaveStateMsg(int stateNumber, long syncNonce){ this.stateNumber = stateNumber; this.syncNonce = syncNonce; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_I_HAVE_STATE); obj.put("stateNumber", stateNumber); obj.put("syncNonce", syncNonce); }catch(JSONException e){} return obj; } } class SendMeStateMsg extends PropMsg{ public int desiredStateNumber; public long syncNonce; public SendMeStateMsg(JSONObject msg){ desiredStateNumber = msg.optInt("desiredStateNumber"); syncNonce = msg.optLong("syncNonce"); } public SendMeStateMsg(int desiredStateNumber, long syncNonce){ this.desiredStateNumber = desiredStateNumber; this.syncNonce = syncNonce; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_SEND_ME_STATE); obj.put("desiredStateNumber", desiredStateNumber); obj.put("syncNonce", syncNonce); }catch(JSONException e){} return obj; } } class PlzCatchUpMsg extends PropMsg{ public int stateNumber; public PlzCatchUpMsg(JSONObject msg){ stateNumber = msg.optInt("stateNumber"); } public PlzCatchUpMsg(int stateNumber){ this.stateNumber = stateNumber; } public JSONObject toJSONObject(){ JSONObject obj = new JSONObject(); try{ obj.put("type", MSG_PLZ_CATCHUP); obj.put("stateNumber", stateNumber); }catch(JSONException e){} return obj; } } }
package eme.generator; import java.util.HashMap; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EGenericType; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.ETypeParameter; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import eme.model.ExtractedType; import eme.model.datatypes.ExtractedDataType; import eme.model.datatypes.ExtractedTypeParameter; import eme.model.datatypes.WildcardStatus; /** * Generator class for the generation of Ecore data types: EDataTypes * @author Timur Saglam */ public class EDataTypeGenerator { private static final Logger logger = LogManager.getLogger(EDataTypeGenerator.class.getName()); private final Map<String, EClassifier> createdEClassifiers; private final EcoreFactory ecoreFactory; private EPackage root; private final Map<String, EDataType> typeMap; /** * Basic constructor, builds the type map. * @param createdEClassifiers is the list of created classifiers. This is needed to get custom data types. */ public EDataTypeGenerator(Map<String, EClassifier> createdEClassifiers) { this.createdEClassifiers = createdEClassifiers; // set classifier map. ecoreFactory = EcoreFactory.eINSTANCE; // get ecore factory. typeMap = new HashMap<String, EDataType>(); // create type map. fillMap(); // fill type map. } /** * Adds all generic arguments from an extracted data type to an generic type. For all generic arguments add their * generic arguments recursively. * @param genericType is the generic type of an attribute, a parameter or a method. * @param dataType is the extracted data type, an attribute, a parameter or a return type. * @param classifier is the EClassifier which owns the generic type. */ public void addGenericArguments(EGenericType genericType, ExtractedDataType dataType, EClassifier classifier) { for (ExtractedDataType genericArgument : dataType.getGenericArguments()) { // for every generic argument EGenericType eArgument = ecoreFactory.createEGenericType(); // create ETypeArgument as EGenericType if (genericArgument.isWildcard()) { addBound(eArgument, genericArgument); } else if (isTypeParameter(genericArgument, classifier)) { eArgument.setETypeParameter(getETypeParameter(genericArgument.getFullTypeName(), classifier)); } else { eArgument.setEClassifier(generate(genericArgument)); } addGenericArguments(eArgument, genericArgument, classifier); // recursively add generic arguments genericType.getETypeArguments().add(eArgument); // add ETypeArgument to original generic type } } /** * Adds all generic type parameters from an extracted type to a classifier. * @param classifier is the classifier. * @param type is the extracted type. */ public void addTypeParameters(EClassifier classifier, ExtractedType type) { ETypeParameter eTypeParameter; // ecore type parameter EGenericType eBound; // ecore type parameter bound for (ExtractedTypeParameter typeParameter : type.getTypeParameters()) { // for all type parameters eTypeParameter = ecoreFactory.createETypeParameter(); // create object eTypeParameter.setName(typeParameter.getIdentifier()); // set name for (ExtractedDataType bound : typeParameter.getBounds()) { // for all bounds eBound = ecoreFactory.createEGenericType(); // create object if (isTypeParameter(bound, classifier)) { eBound.setETypeParameter(getETypeParameter(bound.getFullTypeName(), classifier)); } else { eBound.setEClassifier(generate(bound)); } addGenericArguments(eBound, bound, classifier); // add generic arguments of bound eTypeParameter.getEBounds().add(eBound); // add bound to type parameter } classifier.getETypeParameters().add(eTypeParameter); // add type parameter to EClassifier } } /** * Returns an EClassifier for an ExtractedDataType that can be used as DataType for Methods and Attributes. * @param extractedDataType is the extracted data type. * @return the data type as EClassifier, which is either (1.) a custom class from the model, or (2.) or an external * class that has to be created as data type, or (3.) an already known data type (Basic type or already created). */ public EClassifier generate(ExtractedDataType extractedDataType) { EDataType eDataType; String fullName = extractedDataType.getFullTypeName(); if (createdEClassifiers.containsKey(fullName)) { // if is custom class return createdEClassifiers.get(fullName); } else if (typeMap.containsKey(fullName)) { // if is basic type or already known eDataType = typeMap.get(fullName); // access EDataType return eDataType; } else { // if its an external type eDataType = generateExternal(extractedDataType); // create new EDataType addTypeParameters(eDataType, extractedDataType); // try to guess type parameters root.getEClassifiers().add(eDataType); // add root containment return eDataType; } } /** * Returns an EGenericType for an ExtractedDataType that can be used as generic type for Methods and Attributes. * @param dataType is the ExtractedDataType. * @param eClass is the EClass that owns the the EGenericType * @return the EGenericType. */ public EGenericType generateGeneric(ExtractedDataType dataType, EClass eClass) { if (isTypeParameter(dataType, eClass)) { EGenericType genericType = ecoreFactory.createEGenericType(); genericType.setETypeParameter(getETypeParameter(dataType.getFullTypeName(), eClass)); return genericType; } throw new IllegalArgumentException("The data type is not an type parameter: " + dataType.toString()); } /** * Checks whether an extracted data type is a type parameter in a specific EClassifier. * @param dataType is the extracted data type. * @param classifier is the specific EClassifier. * @return true if the extracted data type is a type parameter. */ public boolean isTypeParameter(ExtractedDataType dataType, EClassifier classifier) { String dataTypeName = dataType.getFullTypeName(); for (ETypeParameter parameter : classifier.getETypeParameters()) { if (parameter.getName() != null && parameter.getName().equals(dataTypeName)) { return true; } } return false; } /** * Resets the class. Removes custom generated data types from the type map, so that only the basic types are * available. */ public void reset() { typeMap.clear(); // clear map from all types. fillMap(); // add basic types. } /** * Setter for the root package, should be called before data types are getting created. * @param root is the root package. */ public void setRoot(EPackage root) { this.root = root; } /** * Adds a bound to an wild card argument if it has one. */ private void addBound(EGenericType eArgument, ExtractedDataType genericArgument) { WildcardStatus status = genericArgument.getWildcardStatus(); // get wild card status if (status != WildcardStatus.WILDCARD) { // if has bounds: EGenericType bound = ecoreFactory.createEGenericType(); // create bound bound.setEClassifier(generate(genericArgument)); // generate bound type if (status == WildcardStatus.WILDCARD_LOWER_BOUND) { eArgument.setELowerBound(bound); // add lower bound } else { eArgument.setEUpperBound(bound); // add upper bound } } } /** * Adds bland generic type arguments to an classifier through a extracted data type. This should only be used for * external data types because it does not extract the actual types of the type parameters. */ private void addTypeParameters(EClassifier classifier, ExtractedDataType dataType) { ETypeParameter eTypeParameter; // ecore type parameter char name = 'A'; for (int i = 0; i < dataType.getGenericArguments().size(); i++) { if (name == 'Z' + 1) { logger.error("Can only generate up to 26 type parameters for " + dataType.toString()); return; // TODO (HIGH) replace this approximation through exact solution } eTypeParameter = ecoreFactory.createETypeParameter(); // create object eTypeParameter.setName(Character.toString(name)); // set name classifier.getETypeParameters().add(eTypeParameter); // add type parameter to EClassifier name++; // next letter. } } private void fillMap() { typeMap.put("boolean", EcorePackage.eINSTANCE.getEBoolean()); typeMap.put("byte", EcorePackage.eINSTANCE.getEByte()); typeMap.put("char", EcorePackage.eINSTANCE.getEChar()); typeMap.put("double", EcorePackage.eINSTANCE.getEDouble()); typeMap.put("float", EcorePackage.eINSTANCE.getEFloat()); typeMap.put("int", EcorePackage.eINSTANCE.getEInt()); typeMap.put("long", EcorePackage.eINSTANCE.getELong()); typeMap.put("short", EcorePackage.eINSTANCE.getEShort()); typeMap.put("java.lang.Boolean", EcorePackage.eINSTANCE.getEBooleanObject()); typeMap.put("java.lang.Byte", EcorePackage.eINSTANCE.getEByteObject()); typeMap.put("java.lang.Character", EcorePackage.eINSTANCE.getECharacterObject()); typeMap.put("java.lang.Double", EcorePackage.eINSTANCE.getEDoubleObject()); typeMap.put("java.lang.Float", EcorePackage.eINSTANCE.getEFloatObject()); typeMap.put("java.lang.Integer", EcorePackage.eINSTANCE.getEIntegerObject()); typeMap.put("java.lang.Long", EcorePackage.eINSTANCE.getELongObject()); typeMap.put("java.lang.Short", EcorePackage.eINSTANCE.getEShortObject()); typeMap.put("java.lang.String", EcorePackage.eINSTANCE.getEString()); typeMap.put("java.lang.Object", EcorePackage.eINSTANCE.getEJavaObject()); typeMap.put("java.lang.Class", EcorePackage.eINSTANCE.getEJavaClass()); // typeMap.put("java.util.List", EcorePackage.eINSTANCE.getEEList()); // TODO (MEDIUM) decide on this. // typeMap.put("java.util.Map", EcorePackage.eINSTANCE.getEMap()); } /** * Creates a new EDataType from an ExtractedDataType. The new EDataType can then be accessed from the type map. */ private EDataType generateExternal(ExtractedDataType extractedDataType) { if (typeMap.containsKey(extractedDataType.getFullTypeName())) { // if already created: throw new IllegalArgumentException("Can't create an already created data type."); // throw exception } EDataType newType = ecoreFactory.createEDataType(); // new data type. newType.setName(extractedDataType.getTypeName()); // set name newType.setInstanceTypeName(extractedDataType.getFullTypeName()); // set full name typeMap.put(extractedDataType.getFullTypeName(), newType); // store in map for later use return newType; } /** * Gets an ETypeParameter with a specific name from an specific EClassifier. */ private ETypeParameter getETypeParameter(String name, EClassifier classifier) { for (ETypeParameter parameter : classifier.getETypeParameters()) { if (parameter.getName().equals(name)) { return parameter; } } throw new IllegalArgumentException("There is no ETypeParameter " + name + " in " + classifier.toString()); } }