code
stringlengths
73
34.1k
label
stringclasses
1 value
private boolean tryPath(StringBuilder prefix, String el, boolean dir) { String path = prefix + "/" + el; if (dir && directoryBrowsingDisallowed) { path += "/" + xsltdirMarkerName; } if (debug()) { debug("trypath: " + path); } try { URL u = new URL(path); URLConnection...
java
public static final DumbData[][] createDatas(final int[] pDatasPerRevision) { final DumbData[][] returnVal = new DumbData[pDatasPerRevision.length][]; for (int i = 0; i < pDatasPerRevision.length; i++) { returnVal[i] = new DumbData[pDatasPerRevision[i]]; for (int j = 0; j < pData...
java
public Void call() throws TTException { emitStartDocument(); long[] versionsToUse; // if there are no versions specified, take the last one, of not version==0 if (mVersions.length == 0) { if (mSession.getMostRecentVersion() > 0) { versionsToUse = new long[] ...
java
public static Node getOneTaggedNode(final Node el, final String name) throws SAXException { if (!el.hasChildNodes()) { return null; } final NodeList children = el.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node n ...
java
public static String getOneNodeVal(final Node el, final String name) throws SAXException { /* We expect one child of type text */ if (!el.hasChildNodes()) { return null; } NodeList children = el.getChildNodes(); if (children.getLength() > 1){ throw new SAXException("Multiple prop...
java
public static String getReqOneNodeVal(final Node el, final String name) throws SAXException { String str = getOneNodeVal(el, name); if ((str == null) || (str.length() == 0)) { throw new SAXException("Missing property value: " + name); } return str; }
java
public static String getAttrVal(final Element el, final String name) throws SAXException { Attr at = el.getAttributeNode(name); if (at == null) { return null; } return at.getValue(); }
java
public static String getReqAttrVal(final Element el, final String name) throws SAXException { String str = getAttrVal(el, name); if ((str == null) || (str.length() == 0)) { throw new SAXException("Missing attribute value: " + name); } return str; }
java
public static String getAttrVal(final NamedNodeMap nnm, final String name) { Node nmAttr = nnm.getNamedItem(name); if ((nmAttr == null) || (absent(nmAttr.getNodeValue()))) { return null; } return nmAttr.getNodeValue(); }
java
public static Boolean getYesNoAttrVal(final NamedNodeMap nnm, final String name) throws SAXException { String val = getAttrVal(nnm, name); if (val == null) { return null; } if ((!"yes".equals(val)) && (!"no".equals(val))) { throw new SAXException("Invalid attribute value: " + val); ...
java
public static List<Element> getElements(final Node nd) throws SAXException { final List<Element> al = new ArrayList<>(); NodeList children = nd.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node curnode = children.item(i); if (curnode.getNodeType() == Node.TEXT_NODE) { ...
java
public static String getElementContent(final Element el, final boolean trim) throws SAXException { StringBuilder sb = new StringBuilder(); NodeList children = el.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node curnode = children.item(i)...
java
public static void setElementContent(final Node n, final String s) throws SAXException { NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node curnode = children.item(i); n.removeChild(curnode); } Document d = n...
java
public static boolean hasContent(final Element el) throws SAXException { String s = getElementContent(el); return (s != null) && (s.length() > 0); }
java
public static boolean hasChildren(final Element el) throws SAXException { NodeList children = el.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node curnode = children.item(i); short ntype = curnode.getNodeType(); if ((ntype != Node.TEXT_NODE) && (ntype != Node....
java
public static boolean nodeMatches(final Node nd, final QName tag) { if (tag == null) { return false; } String ns = nd.getNamespaceURI(); if (ns == null) { /* It appears a node can have a NULL namespace but a QName has a zero length */ if ((tag.getNamespaceURI() != null) && (!"...
java
public static QName fromNode(final Node nd) { String ns = nd.getNamespaceURI(); if (ns == null) { /* It appears a node can have a NULL namespace but a QName has a zero length */ ns = ""; } return new QName(ns, nd.getLocalName()); }
java
public static SSLSocketFactory getSslSocketFactory() { if (!sslDisabled) { return SSLSocketFactory.getSocketFactory(); } try { final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; final SSLContext ctx = SSLContext.getInstance("TLS"); final X509TrustManager tm = new ...
java
public void setCredentials(final String user, final String pw) { if (user == null) { credentials = null; } else { credentials = new UsernamePasswordCredentials(user, pw); } }
java
public int sendRequest(final String methodName, final String url, final List<Header> hdrs, final String contentType, final int contentLen, final byte[] content) throws HttpException { int sz = 0; if (content != n...
java
protected HttpRequestBase findMethod(final String name, final URI uri) throws HttpException { String nm = name.toUpperCase(); if ("PUT".equals(nm)) { return new HttpPut(uri); } if ("GET".equals(nm)) { return new HttpGet(uri); } if ("DELETE".e...
java
public void release() throws HttpException { try { HttpEntity ent = getResponseEntity(); if (ent != null) { InputStream is = ent.getContent(); is.close(); } } catch (Throwable t) { throw new HttpException(t.getLocalizedMessage(), t); } }
java
public int addItem(final AtomicValue pItem) { final int key = mList.size(); pItem.setNodeKey(key); // TODO: +2 is necessary, because key -1 is the NULLDATA final int itemKey = (key + 2) * (-1); pItem.setNodeKey(itemKey); mList.add(pItem); return itemKey; }
java
static void release(BufferPool.Buffer buff) throws IOException { if (buff.buf.length == staticConf.getSmallBufferSize()) { smallBufferPool.put(buff); } else if (buff.buf.length == staticConf.getMediumBufferSize()) { mediumBufferPool.put(buff); } else if (buff.buf.length == staticConf.getLargeBuf...
java
private static NotificationsHandler getHandler(final String queueName, final Properties pr) throws NotificationException { if (handler != null) { return handler; } synchronized (synchit) { handler = new JmsNotificationsHandlerImpl(queueName, pr);...
java
public static void post(final SysEvent ev, final String queueName, final Properties pr) throws NotificationException { getHandler(queueName, pr).post(ev); }
java
public static <T> AdjustCollectionResult<T> adjustCollection(final Collection<T> newCol, final Collection<T> toAdjust) { final AdjustCollectionResult<T> acr = new AdjustCollectionResult<>(); acr.removed = new ArrayList<>(); acr.added = new ArrayLi...
java
public static String pathElement(final int index, final String path) { final String[] paths = path.split("/"); int idx = index; if ((paths[0] == null) || (paths[0].length() == 0)) { // skip empty first part - leading "/" idx++; } if (idx >= paths.len...
java
public static Locale makeLocale(final String val) throws Throwable { String lang = null; String country = ""; // NOT null for Locale String variant = ""; if (val == null) { throw new Exception("Bad Locale: NULL"); } if (val.length() == 2) { lang = val; } else { int pos = ...
java
public static Properties getPropertiesFromResource(final String name) throws Throwable { Properties pr = new Properties(); InputStream is = null; try { try { // The jboss?? way - should work for others as well. ClassLoader cl = Thread.currentThread().getContextClassLoader(); i...
java
public static Object getObject(final String className, final Class cl) throws Exception { try { Object o = Class.forName(className).newInstance(); if (o == null) { throw new Exception("Class " + className + " not found"); } if (!cl.isInstance(o)) { ...
java
public static String fmtMsg(final String fmt, final String arg1, final String arg2) { Object[] o = new Object[2]; o[0] = arg1; o[1] = arg2; return MessageFormat.format(fmt, o); }
java
public static String fmtMsg(final String fmt, final int arg) { Object[] o = new Object[1]; o[0] = new Integer(arg); return MessageFormat.format(fmt, o); }
java
public static String makeRandomString(int length, int maxVal) { if (length < 0) { return null; } length = Math.min(length, 1025); if (maxVal < 0) { return null; } maxVal = Math.min(maxVal, 35); StringBuffer res = new StringBuffer(); Random rand = new Random(); for (i...
java
public static String[] appendTextToArray(String[] sarray, final String val, final int maxEntries) { if (sarray == null) { if (maxEntries > 0) { sarray = new String[1]; sarray[0] = val; } return sarray; } if (sarray.length > maxEntries) {...
java
public static String encodeArray(final String[] val){ if (val == null) { return null; } int len = val.length; if (len == 0) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i++) { if (i > 0) { sb.append(" "); } String s ...
java
public static String[] decodeArray(final String val){ if (val == null) { return null; } int len = val.length(); if (len == 0) { return new String[0]; } ArrayList<String> al = new ArrayList<String>(); int i = 0; while (i < len) { int end = val.indexOf(" ", i); ...
java
public static boolean equalsString(final String thisStr, final String thatStr) { if ((thisStr == null) && (thatStr == null)) { return true; } if (thisStr == null) { return false; } return thisStr.equals(thatStr); }
java
public static int compareStrings(final String s1, final String s2) { if (s1 == null) { if (s2 != null) { return -1; } return 0; } if (s2 == null) { return 1; } return s1.compareTo(s2); }
java
public static List<String> getList(final String val, final boolean emptyOk) throws Throwable { List<String> l = new LinkedList<String>(); if ((val == null) || (val.length() == 0)) { return l; } StringTokenizer st = new StringTokenizer(val, ",", false); while (st.hasMoreTokens()) { Stri...
java
public static int compare(final char[] thisone, final char[] thatone) { if (thisone == thatone) { return 0; } if (thisone == null) { return -1; } if (thatone == null) { return 1; } if (thisone.length < thatone.length) { return -1; } if (thisone.length > th...
java
public Diff add(final Diff paramChange) { assert paramChange != null; final ITreeData item = paramChange.getDiff() == EDiff.DELETED ? paramChange.getOldNode() : paramChange.getNewNode(); if (mChangeByNode.containsKey(item)) { return paramChange; } mChange...
java
public void startListening() throws FileNotFoundException, ClassNotFoundException, IOException, ResourceNotExistingException, TTException { mProcessingThread = new Thread() { public void run() { try { processFileNotifications(); } catch (In...
java
private void initSessions() throws FileNotFoundException, ClassNotFoundException, IOException, ResourceNotExistingException, TTException { Map<String, String> filelisteners = getFilelisteners(); mSessions = new HashMap<String, ISession>(); mTrx = new HashMap<String, IFilelistenerWriteTrx...
java
private void watchParents(Path p, String until) throws IOException { if (p.getParent() != null && !until.equals(p.getParent().toString())) { watchDir(p.getParent().toFile()); watchParents(p.getParent(), until); } }
java
private void releaseSessions() throws TTException { if (mSessions == null) { return; } // Closing all transactions. try { for (IFilelistenerWriteTrx trx : mTrx.values()) { trx.close(); } } catch (IllegalStateException ise) { ...
java
public void shutDownListener() throws TTException, IOException { for (ExecutorService s : mExecutorMap.values()) { s.shutdown(); while (!s.isTerminated()) { // Do nothing. try { Thread.sleep(1000); } catch (InterruptedE...
java
private void processFileNotifications() throws InterruptedException, TTException, IOException { while (true) { WatchKey key = mWatcher.take(); Path dir = mKeyPaths.get(key); for (WatchEvent<?> evt : key.pollEvents()) { WatchEvent.Kind<?> eventType = evt.kind()...
java
private void process(Path dir, Path file, WatchEvent.Kind<?> evtType) throws TTException, IOException, InterruptedException { // LOGGER.info("Processing " + file.getFileName() + " with event " // + evtType); IFilelistenerWriteTrx trx = null; String rootPath = getListenerRootPath(...
java
private void addSubDirectory(Path root, Path filePath) throws IOException { String listener = getListenerRootPath(root); List<String> listeners = mSubDirectories.get(listener); if (listeners != null) { if (mSubDirectories.get(listener).contains(filePath.toAbsolutePath())) { ...
java
private String getListenerRootPath(Path root) { String listener = ""; for (String s : mFilelistenerToPaths.values()) { if (root.toString().contains(s)) { listener = s; } } return listener; }
java
public static Map<String, String> getFilelisteners() throws FileNotFoundException, IOException, ClassNotFoundException { mFilelistenerToPaths = new HashMap<String, String>(); File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data"); getFileListener...
java
public static boolean addFilelistener(String pResourcename, String pListenerPath) throws FileNotFoundException, IOException, ClassNotFoundException { mFilelistenerToPaths = new HashMap<String, String>(); File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data...
java
public boolean removeFilelistener(String pResourcename) throws IOException, TTException, ResourceNotExistingException { mFilelistenerToPaths = new HashMap<String, String>(); File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data"); getFileListenersF...
java
private static void getFileListenersFromSystem(File pListenerFilePaths) throws IOException { if (!pListenerFilePaths.exists()) { java.nio.file.Files.createFile(pListenerFilePaths.toPath()); } else { byte[] bytes = java.nio.file.Files.readAllBytes(pListenerFilePaths.toPath()); ...
java
public static <K, V extends Comparable<V>> List<Entry<K, V>> sortByValue(Map<K, V> map) { List<Entry<K, V>> entries = new ArrayList<>(map.entrySet()); entries.sort(new ByValue<>()); return entries; }
java
public static <K extends Comparable<K>, V extends Comparable<V>> List<Map.Entry<K, V>> sortByValueAndKey(Map<K, V> map) { List<Map.Entry<K, V>> entries = new ArrayList<>(map.entrySet()); entries.sort(new ByValueAndKey<>()); return entries; }
java
public String getReqPar(final String name, final String def) { final String s = Util.checkNull(request.getParameter(name)); if (s != null) { return s; } return def; }
java
public Integer getIntReqPar(final String name) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return null; } return Integer.valueOf(reqpar); }
java
public int getIntReqPar(final String name, final int defaultVal) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return defaultVal; } try { return Integer.parseInt(reqpar); } catch (Throwable t) { return defaultVal; // XXX excep...
java
public Long getLongReqPar(final String name) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return null; } return Long.valueOf(reqpar); }
java
public long getLongReqPar(final String name, final long defaultVal) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return defaultVal; } try { return Long.parseLong(reqpar); } catch (Throwable t) { return defaultVal; // XXX ex...
java
public Boolean getBooleanReqPar(final String name) throws Throwable { String reqpar = getReqPar(name); if (reqpar == null) { return null; } try { if (reqpar.equalsIgnoreCase("yes")) { reqpar = "true"; } return Boolean.valueOf(reqpar); } catch (Throwable t) { ...
java
public boolean getBooleanReqPar(final String name, final boolean defVal) throws Throwable { boolean val = defVal; Boolean valB = getBooleanReqPar(name); if (valB != null) { val = valB; } return val; }
java
public void setSessionAttr(final String attrName, final Object val) { final HttpSession sess = request.getSession(false); if (sess == null) { return; } sess.setAttribute(attrName, val); }
java
public void removeSessionAttr(final String attrName) { final HttpSession sess = request.getSession(false); if (sess == null) { return; } sess.removeAttribute(attrName); }
java
public Object getSessionAttr(final String attrName) { final HttpSession sess = request.getSession(false); if (sess == null) { return null; } return sess.getAttribute(attrName); }
java
@SuppressWarnings("unchecked") public static void registerMBean(final ManagementContext context, final Object object, final ObjectName objectName) throws Exception { String mbeanName = object.getClass().getName() + "MBean"; for (Class...
java
private Method getMethod(final MBeanOperationInfo op) { final MBeanParameterInfo[] params = op.getSignature(); final String[] paramTypes = new String[params.length]; for (int i = 0; i < params.length; i++) { paramTypes[i] = params[i].getType(); } return getMethod(getMBeanInterface(), op.getNa...
java
private static Method getMethod(final Class<?> mbean, final String method, final String... params) { try { final ClassLoader loader = mbean.getClassLoader(); final Class<?>[] paramClasses = new Class<?>[params.length]; for (int i ...
java
@Around("@annotation(org.treetank.aspects.logging.Logging)") public Object advice(ProceedingJoinPoint pjp) throws Throwable { final Signature sig = pjp.getSignature(); final Logger logger = FACTORY.getLogger(sig.getDeclaringTypeName()); logger.debug(new StringBuilder("Entering ").append(sig....
java
private void doXPathRes(final String resource, final Long revision, final OutputStream output, final boolean nodeid, final String xpath) throws TTException { // Storage connection to treetank ISession session = null; INodeReadTrx rtx = null; try { if (mDatabase.exists...
java
@Override public ConfigurationStore getStore(final String name) throws ConfigException { try { final File dir = new File(dirPath); final String newPath = dirPath + name; final File[] files = dir.listFiles(new DirsOnly()); for (final File f: files) { if (f.getName().equals(name)) ...
java
public static String jsonNameVal(final String indent, final String name, final String val) { StringBuilder sb = new StringBuilder(); sb.append(indent); sb.append("\""); sb.append(name); sb.append("\": "); if (val != null) ...
java
private static Element createResultElement(final Document document) { return document.createElementNS(JaxRxConstants.URL, JaxRxConstants.JAXRX + ":results"); }
java
public static StreamingOutput buildDOMResponse(final List<String> availableResources) { try { final Document document = createSurroundingXMLResp(); final Element resElement = createResultElement(document); final List<Element> resources = createCollectionElement(availableRes...
java
public static StreamingOutput createStream(final Document doc) { return new StreamingOutput() { @Override public void write(final OutputStream output) { synchronized (output) { final DOMSource domSource = new DOMSource(doc); final ...
java
private void writeFile(final String fileName, final byte[] bs, final boolean append) throws IOException { FileOutputStream fstr = null; try { fstr = new FileOutputStream(fileName, append); fstr.write(bs); // Terminate key with newline f...
java
static String root(final ResourcePath path) { if (path.getDepth() == 1) return path.getResourcePath(); throw new JaxRxException(404, "Resource not found: " + path); }
java
public String getResourcePath() { final StringBuilder sb = new StringBuilder(); for (final String r : resource) sb.append(r + '/'); return sb.substring(0, Math.max(0, sb.length() - 1)); }
java
public String getResource(final int level) { if (level < resource.length) { return resource[level]; } // offset is out of bounds... throw new IndexOutOfBoundsException("Index: " + level + ", Size: " + resource.length); }
java
public static String getHeaders(final HttpServletRequest req) { Enumeration en = req.getHeaderNames(); StringBuffer sb = new StringBuffer(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); sb.append(name); sb.append(": "); sb.append(req.getHeader(name)); ...
java
public static void dumpHeaders(final HttpServletRequest req) { Enumeration en = req.getHeaderNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); logger.debug(name + ": " + req.getHeader(name)); } }
java
public static Collection<Locale> getLocales(final HttpServletRequest req) { if (req.getHeader("Accept-Language") == null) { return null; } @SuppressWarnings("unchecked") Enumeration<Locale> lcs = req.getLocales(); ArrayList<Locale> locales = new ArrayList<Locale>(); while (lcs.hasMoreElem...
java
public static void initTimezones(final String serverUrl) throws TimezonesException { try { if (tzs == null) { tzs = (Timezones)Class.forName("org.bedework.util.timezones.TimezonesImpl").newInstance(); } tzs.init(serverUrl); } catch (final TimezonesException te) { throw te; }...
java
public static String getThreadDefaultTzid() throws TimezonesException { final String id = threadTzid.get(); if (id != null) { return id; } return getSystemDefaultTzid(); }
java
public static String getUtc(final String time, final String tzid) throws TimezonesException { return getTimezones().calculateUtc(time, tzid); }
java
public static void rolloverLogfile() { Logger logger = Logger.getRootLogger(); // NOSONAR - local logger used on purpose here @SuppressWarnings("unchecked") Enumeration<Object> appenders = logger.getAllAppenders(); while(appenders.hasMoreElements()) { Object obj = appenders.nextElement(); if(obj ins...
java
public static synchronized boolean createStorage(final StorageConfiguration pStorageConfig) throws TTIOException { boolean returnVal = true; // if file is existing, skipping if (!pStorageConfig.mFile.exists() && pStorageConfig.mFile.mkdirs()) { returnVal = IOU...
java
public static synchronized void truncateStorage(final StorageConfiguration pConf) throws TTException { // check that database must be closed beforehand if (!STORAGEMAP.containsKey(pConf.mFile)) { if (existsStorage(pConf.mFile)) { final IStorage storage = new Storage(pConf); ...
java
public static synchronized boolean existsStorage(final File pStoragePath) { // if file is existing and folder is a tt-dataplace, delete it if (pStoragePath.exists() && IOUtils.compareStructure(pStoragePath, StorageConfiguration.Paths.values()) == 0) { return true; } else ...
java
public static synchronized IStorage openStorage(final File pFile) throws TTException { checkState(existsStorage(pFile), "DB could not be opened (since it was not created?) at location %s", pFile); StorageConfiguration config = StorageConfiguration.deserialize(pFile); final Storage st...
java
private static void bootstrap(final Storage pStorage, final ResourceConfiguration pResourceConf) throws TTException { final IBackend storage = pResourceConf.mBackend; storage.initialize(); final IBackendWriter writer = storage.getWriter(); final UberBucket uberBucket = new Uber...
java
public IXPathToken nextToken() { // some tokens start in another state than the START state mState = mStartState; // reset startState mStartState = State.START; mOutput = new StringBuilder(); mFinnished = false; mType = TokenType.INVALID; mLastPos = mPos;...
java
private void scanStart() { if (isNumber(mInput)) { mState = State.NUMBER; mOutput.append(mInput); mType = TokenType.VALUE; // number } else if (isFirstLetter(mInput)) { mState = State.TEXT; // word mOutput.append(mInput); mType = T...
java
private TokenType retrieveType(final char paramInput) { TokenType type; switch (paramInput) { case ',': type = TokenType.COMMA; break; case '(': type = TokenType.OPEN_BR; break; case ')': type = TokenType.CLOSE_BR; ...
java
private boolean isSpecial(final char paramInput) { return (paramInput == ')') || (paramInput == ';') || (paramInput == ',') || (paramInput == '@') || (paramInput == '[') || (paramInput == ']') || (paramInput == '=') || (paramInput == '"') || (paramInput == '\'') || (paramInput == '$') |...
java
private void scanNumber() { if (mInput >= '0' && mInput <= '9') { mOutput.append(mInput); mPos++; } else { // could be an e-number if (mInput == 'E' || mInput == 'e') { mStartState = State.E_NUM; } mFinnished = true...
java
private void scanText() { if (isLetter(mInput)) { mOutput.append(mInput); mPos++; } else { mType = TokenType.TEXT; mFinnished = true; } }
java
private void scanENum() { if (mInput == 'E' || mInput == 'e') { mOutput.append(mInput); mState = State.START; mType = TokenType.E_NUMBER; mFinnished = true; mPos++; } else { mFinnished = true; mState = State.START; ...
java