public void run() { while (!_closed) { try { updateAll(); long now = System.currentTimeMillis(); if (inetAddrCacheMS > 0 && _nextResolveTime < now) { _nextResolveTime = now + inetAddrCacheMS; for (Node node : _all) { node.updateAddr(); } } // force check on master // otherwise master change may go unnoticed for a while if no write concern _mongo.getConnector().checkMaster(true, false); } catch (Exception e) { _logger.log(Level.WARNING, "couldn't do update pass", e); } try { Thread.sleep(updaterIntervalMS); } catch (InterruptedException ie) { } } }
public boolean save() { Node node = ForumManager.getCloud().getNode(id); node.setValue("mode", mode); node.setValue("body", body); node.setValue("encoding", encoding); node.commit(); return true; }
Node getMasterNode() { _checkClosed(); for (int i = 0; i < _all.size(); i++) { Node n = _all.get(i); if (n.master()) return n; } return null; }
public boolean delete() { Node node = ForumManager.getCloud().getNode(id); if (node != null) { node.delete(true); } parent.deleteSignature(this); return true; }
public String getProperty(String pPropertyName) { String propertyValue = null; NodeList nodeList = mConfigFileDocument.getElementsByTagName(pPropertyName); int nodeListLength = nodeList.getLength(); if (nodeListLength > 0) { Node firstChildNode = nodeList.item(nodeListLength - 1).getFirstChild(); if (null != firstChildNode) { propertyValue = firstChildNode.getNodeValue(); } } return (propertyValue); }
@Override public VPackage parse() { logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath()); long startParsing = System.currentTimeMillis(); try { Document document = getDocument(); Element root = document.getDocumentElement(); _package = new VPackage(xmlFile); Node name = root.getElementsByTagName(EL_NAME).item(0); _package.setName(name.getTextContent()); Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0); _package.setDescription(descr.getTextContent()); NodeList list = root.getElementsByTagName(EL_CLASS); boolean initPainters = false; for (int i = 0; i < list.getLength(); i++) { PackageClass pc = parseClass((Element) list.item(i)); if (pc.getPainterName() != null) { initPainters = true; } } if (initPainters) { _package.initPainters(); } logger.info( "Parsing the package '{}' finished in {}ms.\n", _package.getName(), (System.currentTimeMillis() - startParsing)); } catch (Exception e) { collector.collectDiagnostic(e.getMessage(), true); if (RuntimeProperties.isLogDebugEnabled()) { e.printStackTrace(); } } try { checkProblems("Error parsing package file " + xmlFile.getName()); } catch (Exception e) { return null; } return _package; }
FoundItem getFoundItem(Node n, String text) { String s = n.getNodeValue(); if (s == null) s = n.getNodeName(); String string; if (text != null) { int index = s.indexOf(text); int left = Math.max(0, index - 5); int right = Math.min(s.length(), index + text.length() + 20); string = s.substring(left, right); } else string = s; TreeNode tn = jtree.getTreeNode(n); TreePath tp = getTreePath(tn); return new FoundItem(string, tp); }
/** * Populates LOCALES list with contents of xml. * * @param list the configuration list */ private static void parseLocales(NodeList list) { for (int i = 0; i < list.getLength(); ++i) { Node node = list.item(i); NamedNodeMap attributes = node.getAttributes(); String label = ((Attr) attributes.getNamedItem("label")).getValue(); String code = ((Attr) attributes.getNamedItem("isoCode")).getValue(); String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue(); try { LOCALES.add(new Locale(label, code, new URL(dictLocation))); } catch (MalformedURLException exc) { logger.warn( "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc); } } }
/** * Returns a URI that represents the Node. * * @param node the node representing the URI. * @throws GraphException * @return URI */ protected String getURI(Node node) throws GraphException { // value to be returned String uri = null; // determine type of subject node and create uri from it if (node != null) { try { if (node instanceof URIReference) { uri = ((URIReference) node).getURI().toString(); } else if (node instanceof BlankNode) { uri = new URI("#" + ((BlankNode) node).toString()).toString(); } else { uri = node.toString(); } } catch (URISyntaxException uriException) { throw new GraphException("Could not get URI for Node: " + node + ".", uriException); } } else { throw new GraphException("Could not get URI for Node: " + node + ". Node is null."); } // return the URI with any namespaces replaced with prefixes return this.replaceNamespace(uri); }
synchronized void updateAll() { HashSet<Node> seenNodes = new HashSet<Node>(); for (int i = 0; i < _all.size(); i++) { Node n = _all.get(i); n.update(seenNodes); } if (!seenNodes.isEmpty()) { // not empty, means that at least 1 server gave node list // remove unused hosts Iterator<Node> it = _all.iterator(); while (it.hasNext()) { if (!seenNodes.contains(it.next())) it.remove(); } } }
Node ensureMaster() { Node n = getMasterNode(); if (n != null) { n.update(); if (n._isMaster) return n; } if (_lastPrimarySignal != null) { n = findNode(_lastPrimarySignal); n.update(); if (n._isMaster) return n; } updateAll(); return getMasterNode(); }
/** * Returns a String representation of an ObjectNode. Object values do not have to be escaped. * * @param node Node * @throws GraphException * @return String */ protected String getNodeString(Node node) throws GraphException { // value to be returned String object = null; // determine type of subject node and create uri from it if (node != null) { try { if (node instanceof URIReference) { object = ((URIReference) node).getURI().toString(); } else if (node instanceof BlankNode) { object = new URI("#" + ((BlankNode) node).toString()).toString(); } else if (node instanceof Literal) { object = ((Literal) node).getLexicalForm(); } else { object = node.toString(); } } catch (URISyntaxException uriException) { throw new GraphException( "Could not get String for ObjectNode: " + node + ".", uriException); } } else { throw new GraphException( "Could not get String for ObjectNode: " + node + ". ObjectNode is null."); } return object; }
public void disconnect(String name, I_InfoPlayer player) { try { Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame"); Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/" + name); } catch (Exception e) { System.out.println("Failed unbind"); System.exit(128); } System.out.println("Disconnected"); ServerTimer timer = new ServerTimer(5); Thread thread = new Thread(timer); thread.start(); while (!timer.finished()) ; timer.shutDown(); timer = null; System.gc(); try { Naming.rebind("rmi://" + serverAddress + ":1099/I_InfoGame", game); Naming.rebind("rmi://" + serverAddress + ":1099/" + name, player); } catch (Exception e) { System.out.println("Failed rebind"); System.exit(128); } System.out.println("Reconnected"); }
private static void serverWaiting() throws Exception { System.out.println("Waiting Mode"); ServerSocket waitingSocket = new ServerSocket(serverInfo.getPort()); String line; while (true) { Socket connectionSocket = waitingSocket.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream()); // System.out.println("Waiting for migration"); line = in.readLine(); // System.out.println("Received: " + line); String info = line; out.writeBytes("Info OK\n"); line = in.readLine(); // System.out.println("Received: " + line); serverInit(); game.setMoving(true); reconstruction(info); out.writeBytes("Bind OK\n"); waitingSocket.close(); break; } while (!allConnected) { System.out.print(""); } game.setMoving(false); // System.out.println("Fin server waiting"); serverRunning(); }
/** * If CS throws an exception it handled and transalated to a Openfire exception if possible. This * is done using <code>exceptionMap</code> that has a mapping from CS to OF. If no mapping is * found then it tries to instantiete the original exception. If this fails it throws a <code> * Exception</code> with the message of the CS exception. * * @param response the response from CS to check if it is an exception message. * @throws Exception if the response is an exception message. */ private void checkFault(Element response) throws Exception { Node node = response.selectSingleNode("ns1:faultstring"); if (node != null) { String exceptionText = node.getText(); // Text accepted samples: // 'java.lang.Exception: Exception message' // 'java.lang.Exception' // Get the exception class and message if any int index = exceptionText.indexOf(":"); String className; String message; // If there is no message, save the class only if (index == -1) { className = exceptionText; message = null; } else { // Else save both className = exceptionText.substring(0, index); message = exceptionText.substring(index + 2); } // Map the exception to a Openfire one, if possible if (exceptionMap.containsKey(className)) { className = exceptionMap.get(className); } // Tries to create an instance with the message Exception exception; try { Class exceptionClass = Class.forName(className); if (message == null) { exception = (Exception) exceptionClass.newInstance(); } else { Constructor constructor = exceptionClass.getConstructor(String.class); exception = (Exception) constructor.newInstance(message); } } catch (Exception e) { // failed to create an specific exception, creating a standard one. exception = new Exception(exceptionText); } throw exception; } }
public static void serverInit() { String serverAddress = "rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame"; try { game = new InfoGame(); server = new Server(); game.setServer(server); game.setServerAddress(serverInfo.getIpAddr()); game.setNextAddress(serverInfo.getNext().getIpAddr()); game.setNbPlayerExpected(numPlayer); Naming.rebind(serverAddress, game); socketPortClient = serverInfo.getPortClient(); // System.out.println("End initialisation"); } catch (RemoteException e) { System.out.println("Hubo una excepcion creando la instancia del objeto distribuido"); } catch (MalformedURLException e) { System.out.println("URL mal formada al tratar de publicar el objeto"); } }
/** used for cut and paste. */ public void addObjectFromClipboard(String a_value) throws CircularIncludeException { Reader reader = new StringReader(a_value); Document document = null; try { document = UJAXP.getDocument(reader); } catch (Exception e) { e.printStackTrace(); return; } // try-catch Element root = document.getDocumentElement(); if (!root.getNodeName().equals("clipboard")) { return; } // if Node child; for (child = root.getFirstChild(); child != null; child = child.getNextSibling()) { if (!(child instanceof Element)) { continue; } // if Element element = (Element) child; IGlyphFactory factory = GlyphFactory.getFactory(); if (XModule.isMatch(element)) { EModuleInvoke module = (EModuleInvoke) factory.createXModule(element); addModule(module); continue; } // if if (XContour.isMatch(element)) { EContour contour = (EContour) factory.createXContour(element); addContour(contour); continue; } // if if (XInclude.isMatch(element)) { EIncludeInvoke include = (EIncludeInvoke) factory.createXInclude(element); addInclude(include); continue; } // if } // while }
private static void serverCall() throws Exception { String sentence = "move"; String line; while (!gameStopped) { System.out.print(""); } playing = false; try { setDiscussion(); } catch (Exception ex) { System.out.println("Failed to discuss with clients"); } BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); try { InetAddress inetAddress = InetAddress.getByName(serverInfo.getNext().getIpAddr()); Socket clientSocket = new Socket(inetAddress, serverInfo.getNext().getPort()); DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sendInfo(out); line = in.readLine(); while (!game.getUnbinding()) ; Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame"); out.writeBytes("Unbinding finished\n"); line = in.readLine(); clientSocket.close(); } catch (RemoteException e) { System.out.println("Failed get info from game"); System.exit(1); } catch (Exception ex) { System.out.println("Failed to socket with waiting server"); } discussion.shutDown(); discussion = null; game = null; System.gc(); serverWaiting(); }
/** @return a good secondary or null if can't find one */ ServerAddress getASecondary() { _checkClosed(); Node best = null; double badBeforeBest = 0; int start = _random.nextInt(_all.size()); double mybad = 0; for (int i = 0; i < _all.size(); i++) { Node n = _all.get((start + i) % _all.size()); if (!n.secondary()) { mybad++; continue; } if (best == null) { best = n; badBeforeBest = mybad; mybad = 0; continue; } long diff = best._pingTime - n._pingTime; if (diff > slaveAcceptableLatencyMS || // this is a complex way to make sure we get a random distribution of slaves ((badBeforeBest - mybad) / (_all.size() - 1)) > _random.nextDouble()) { best = n; badBeforeBest = mybad; mybad = 0; } } if (best == null) return null; return best._addr; }
static { try { URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC); InputStream stream = url.openStream(); if (stream == null) throw new IOException(); // strict parsing options DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); // parses configuration xml /*- * Warning: Felix is unable to import the com.sun.rowset.internal * package, meaning this can't use the XmlErrorHandler. This causes * a warning and a default handler to be attached. Otherwise this * should have: builder.setErrorHandler(new XmlErrorHandler()); */ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); // iterates over nodes, parsing contents Node root = doc.getChildNodes().item(1); NodeList categories = root.getChildNodes(); for (int i = 0; i < categories.getLength(); ++i) { Node node = categories.item(i); if (node.getNodeName().equals(NODE_DEFAULTS)) { parseDefaults(node.getChildNodes()); } else if (node.getNodeName().equals(NODE_LOCALES)) { parseLocales(node.getChildNodes()); } else { logger.warn("Unrecognized category: " + node.getNodeName()); } } } catch (IOException exc) { logger.error("Unable to load spell checker parameters", exc); } catch (SAXException exc) { logger.error("Unable to parse spell checker parameters", exc); } catch (ParserConfigurationException exc) { logger.error("Unable to parse spell checker parameters", exc); } }
/** * Resolve a constraint against an RDF/XML document. * * <p>Resolution is by filtration of a URL stream, and thus very slow. */ public Resolution resolve(Constraint constraint) throws QueryException { if (logger.isDebugEnabled()) { logger.debug("Resolve " + constraint); } // Validate "constraint" parameter if (constraint == null) { throw new IllegalArgumentException("Null \"constraint\" parameter"); } if (!(constraint.getModel() instanceof LocalNode)) { if (logger.isDebugEnabled()) logger.debug("Ignoring solutions for " + constraint); return new EmptyResolution(constraint, false); } if (!(constraint.getElement(1) instanceof LocalNode) || !(constraint.getElement(2) instanceof LocalNode)) { throw new QueryException( "Prefix resolver can only be used for fixed prefixes: " + constraint); } try { long property = ((LocalNode) constraint.getElement(1)).getValue(); LocalNode object = (LocalNode) constraint.getElement(2); Node prefixNode = resolverSession.globalize(object.getValue()); // check the constraint for consistency if ((property != mulgaraPrefix && property != mulgaraStringPrefix) || !(prefixNode instanceof Literal || prefixNode instanceof URIReference)) { logger.debug("property = " + property + ", mulgaraPrefix = " + mulgaraPrefix); logger.debug("element(2): " + prefixNode + " [" + prefixNode.getClass().getName() + "]"); throw new QueryException( "Prefix resolver can only be used for prefix constraints: " + constraint); } if (logger.isDebugEnabled()) { logger.debug( "Evaluating " + constraint.getElement(0) + " has prefix " + constraint.getElement(2)); } ConstraintElement node = constraint.getElement(0); assert node != null; Tuples tuples; if (node instanceof Variable) { // convert the prefix into a string pool object SPObjectFactory spoFact = SPObjectFactoryImpl.getInstance(); SPObject startPrefixObj = getStartObject(spoFact, prefixNode, property); SPObject endPrefixObj = getEndObject(spoFact, prefixNode, property); // get the extents of the prefix from the string pool tuples = resolverSession.findStringPoolRange(startPrefixObj, true, endPrefixObj, false); assert tuples != null; // rename variables away from subject, predicate and object tuples.renameVariables(constraint); long resultSize; try { // Get the size of the final result. resultSize = tuples.getRowCount(); } catch (TuplesException e) { throw new QueryException("Unable to build result", e); } if (logger.isDebugEnabled()) { try { logger.debug( "tuples size = " + tuples.getRowCount() + " (should be " + resultSize + ")"); } catch (TuplesException e) { logger.debug("Error getting the length of the tuples object"); } } return new TuplesWrapperResolution(tuples, constraint); } else { // if (node instanceof Variable) // node must therefore be an instanceof LocalNode // we can shortcut the process here assert node instanceof LocalNode; LocalNode n = (LocalNode) node; // get the node out of the string pool SPObject spo = resolverSession.findStringPoolObject(n.getValue()); // check that the node exists if (spo == null) { tuples = TuplesOperations.empty(); } else { // see if the node starts with the required prefix String prefix; // extract the string from the literal if (prefixNode instanceof Literal) { prefix = ((Literal) prefixNode).getLexicalForm(); } else { prefix = ((URIReference) prefixNode).getURI().toString(); } if (spo.getLexicalForm().startsWith(prefix)) { tuples = TuplesOperations.unconstrained(); } else { tuples = TuplesOperations.empty(); } } } // convert the tuples to a resolution return new TuplesWrapperResolution(tuples, constraint); } catch (GlobalizeException ge) { throw new QueryException("Couldn't convert internal data into a string", ge); } catch (StringPoolException e) { throw new QueryException("Couldn't query constraint", e); } }
/** * Constructs an attribute designator element from an existing XML block. * * @param element representing a DOM tree element. * @exception SAMLException if that there is an error in the sender or in the element definition. */ public AttributeDesignator(Element element) throws SAMLException { // make sure that the input xml block is not null if (element == null) { SAMLUtilsCommon.debug.message("AttributeDesignator: Input is null."); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } // Make sure this is an AttributeDesignator. String tag = null; tag = element.getLocalName(); if ((tag == null) || (!tag.equals("AttributeDesignator"))) { SAMLUtilsCommon.debug.message("AttributeDesignator: wrong input"); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } // handle attributes int i = 0; NamedNodeMap atts = ((Node) element).getAttributes(); int attrCount = atts.getLength(); for (i = 0; i < attrCount; i++) { Node att = atts.item(i); if (att.getNodeType() == Node.ATTRIBUTE_NODE) { String attName = att.getLocalName(); if (attName == null || attName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator:" + "Attribute Name is either null or empty."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } if (attName.equals("AttributeName")) { _attributeName = ((Attr) att).getValue().trim(); } else if (attName.equals("AttributeNamespace")) { _attributeNameSpace = ((Attr) att).getValue().trim(); } } } // AttributeName is required if (_attributeName == null || _attributeName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator: " + "AttributeName is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // AttributeNamespace is required if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator: " + "AttributeNamespace is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // handle the children of AttributeDesignator element // Since AttributeDesignator does not have any child element_node, // we will throw exception if we found any such child. NodeList nodes = element.getChildNodes(); int nodeCount = nodes.getLength(); if (nodeCount > 0) { for (i = 0; i < nodeCount; i++) { Node currentNode = nodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("AttributeDesignator: illegal input!"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } } } }
private static boolean handleURL(String address) { Main.status(String.format("Processing page \"%s\".", address)); try { NodeList posts = getPosts(address); if (posts.toNodeArray().length == 0) { return false; } for (Node post_node : posts.toNodeArray()) { if (post_node instanceof TagNode) { TagNode post = (TagNode) post_node; Post new_post = new Post(Long.parseLong(post.getAttribute("id").substring(5))); if (!Main.post_post_hash.containsKey(new_post)) { NodeList photo_posts = getPhotoPosts(post.getChildren()); NodeList remarks = getRemarks(photo_posts); for (Node node : remarks.toNodeArray()) { Matcher matcher = lores.matcher(node.getText()); String media_url = ""; if (matcher.find()) { media_url = matcher.group(); media_url = media_url.substring(17, media_url.length() - 1); } String thumb = media_url.replace( media_url.substring(media_url.lastIndexOf("_"), media_url.lastIndexOf(".")), "_75sq"); URL thumb_url = new URL(thumb); new_post.pictures.add(new Picture(new URL(media_url), thumb_url)); } NodeList photoset_posts = getPhotosetPosts(post.getChildren()); NodeList iframes = getIFrames(photoset_posts); for (Node node : iframes.toNodeArray()) { if (node instanceof TagNode) { String iframe_url = ((TagNode) node).getAttribute("src"); Parser parser2 = new Parser(iframe_url); NodeList a_list = parser2.extractAllNodesThatMatch(new TagNameFilter("a")); Node[] a_array = a_list.toNodeArray(); Node[] img_array = a_list.extractAllNodesThatMatch(new TagNameFilter("img"), true).toNodeArray(); String media_url; for (int i = 0; i < a_array.length; i++) { media_url = ((TagNode) img_array[i]).getAttribute("src"); String thumb = media_url.replace( media_url.substring( media_url.lastIndexOf("_"), media_url.lastIndexOf(".")), "_75sq"); URL thumb_url = new URL(thumb); new_post.pictures.add(new Picture(new URL(media_url), thumb_url)); } } } Main.handlePost(new_post); } else { new_post = post_post_hash.get(new_post); handleNonDownloadPost(new_post); } } } } catch (Exception ex) { ex.printStackTrace(); Main.status("Error handling post."); } return true; }